-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathbioio.py
1316 lines (1169 loc) · 50.2 KB
/
bioio.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 python
#Copyright (C) 2006-2012 by Benedict Paten ([email protected])
#
#Released under the MIT license, see LICENSE.txt
import sys
import os
import re
import logging
import resource
import logging.handlers
import tempfile
import random
import math
import shutil
from argparse import ArgumentParser
from optparse import OptionParser, OptionContainer, OptionGroup
from tree import BinaryTree
from misc import close
import subprocess
import array
import string
import xml.etree.cElementTree as ET
from xml.dom import minidom # For making stuff pretty
DEFAULT_DISTANCE = 0.001
#########################################################
#########################################################
#########################################################
#global logging settings / log functions
#########################################################
#########################################################
#########################################################
loggingFormatter = logging.Formatter('%(asctime)s %(levelname)s %(lineno)s %(message)s')
def __setDefaultLogger():
l = logging.getLogger()
for handler in l.handlers: #Do not add a duplicate handler unless needed
if handler.stream == sys.stderr:
return l
handler = logging.StreamHandler(sys.stderr)
l.addHandler(handler)
l.setLevel(logging.CRITICAL)
return l
logger = __setDefaultLogger()
logLevelString = "CRITICAL"
def redirectLoggerStreamHandlers(oldStream, newStream):
"""Redirect the stream of a stream handler to a different stream
"""
for handler in list(logger.handlers): #Remove old handlers
if handler.stream == oldStream:
handler.close()
logger.removeHandler(handler)
for handler in logger.handlers: #Do not add a duplicate handler
if handler.stream == newStream:
return
logger.addHandler(logging.StreamHandler(newStream))
def getLogLevelString():
return logLevelString
__loggingFiles = []
def addLoggingFileHandler(fileName, rotatingLogging=False):
if fileName in __loggingFiles:
return
__loggingFiles.append(fileName)
if rotatingLogging:
handler = logging.handlers.RotatingFileHandler(fileName, maxBytes=1000000, backupCount=1)
else:
handler = logging.FileHandler(fileName)
logger.addHandler(handler)
return handler
def setLogLevel(logLevel):
logLevel = logLevel.upper()
assert logLevel in [ "OFF", "CRITICAL", "INFO", "DEBUG" ] #Log level must be one of these strings.
global logLevelString
logLevelString = logLevel
if logLevel == "OFF":
logger.setLevel(logging.FATAL)
elif logLevel == "INFO":
logger.setLevel(logging.INFO)
elif logLevel == "DEBUG":
logger.setLevel(logging.DEBUG)
elif logLevel == "CRITICAL":
logger.setLevel(logging.CRITICAL)
def logFile(fileName, printFunction=logger.info):
"""Writes out a formatted version of the given log file
"""
printFunction("Reporting file: %s" % fileName)
shortName = fileName.split("/")[-1]
fileHandle = open(fileName, 'r')
line = fileHandle.readline()
while line != '':
if line[-1] == '\n':
line = line[:-1]
printFunction("%s:\t%s" % (shortName, line))
line = fileHandle.readline()
fileHandle.close()
def addLoggingOptions(parser):
# Wrapper function that allows jobTree to be used with both the optparse and
# argparse option parsing modules
if isinstance(parser, OptionContainer):
group = OptionGroup(parser, "Logging options",
"Options that control logging")
_addLoggingOptions(group.add_option)
parser.add_option_group(group)
elif isinstance(parser, ArgumentParser):
group = parser.add_argument_group("Logging Options",
"Options that control logging")
_addLoggingOptions(group.add_argument)
else:
raise RuntimeError("Unanticipated class passed to "
"addLoggingOptions(), %s. Expecting "
"Either optparse.OptionParser or "
"argparse.ArgumentParser" % parser.__class__)
def _addLoggingOptions(addOptionFn):
"""Adds logging options
"""
##################################################
# BEFORE YOU ADD OR REMOVE OPTIONS TO THIS FUNCTION, KNOW THAT
# YOU MAY ONLY USE VARIABLES ACCEPTED BY BOTH optparse AND argparse
# FOR EXAMPLE, YOU MAY NOT USE default=%default OR default=%(default)s
##################################################
addOptionFn("--logOff", dest="logOff", action="store_true", default=False,
help="Turn off logging. (default is CRITICAL)")
addOptionFn(
"--logInfo", dest="logInfo", action="store_true", default=False,
help="Turn on logging at INFO level. (default is CRITICAL)")
addOptionFn(
"--logDebug", dest="logDebug", action="store_true", default=False,
help="Turn on logging at DEBUG level. (default is CRITICAL)")
addOptionFn(
"--logLevel", dest="logLevel", default='CRITICAL',
help=("Log at level (may be either OFF/INFO/DEBUG/CRITICAL). "
"(default is CRITICAL)"))
addOptionFn("--logFile", dest="logFile", help="File to log in")
addOptionFn(
"--rotatingLogging", dest="logRotating", action="store_true",
default=False, help=("Turn on rotating logging, which prevents log "
"files getting too big."))
def setLoggingFromOptions(options):
"""Sets the logging from a dictionary of name/value options.
"""
#We can now set up the logging info.
if options.logLevel is not None:
setLogLevel(options.logLevel) #Use log level, unless flags are set..
if options.logOff:
setLogLevel("OFF")
elif options.logInfo:
setLogLevel("INFO")
elif options.logDebug:
setLogLevel("DEBUG")
logger.info("Logging set at level: %s" % logLevelString)
if options.logFile is not None:
addLoggingFileHandler(options.logFile, options.logRotating)
logger.info("Logging to file: %s" % options.logFile)
#########################################################
#########################################################
#########################################################
#system wrapper command
#########################################################
#########################################################
#########################################################
def system(command):
logger.debug("Running the command: %s" % command)
sts = subprocess.call(command, shell=True, bufsize=-1)
if sts != 0:
raise RuntimeError("Command: %s exited with non-zero status %i" % (command, sts))
return sts
def popen(command, tempFile):
"""Runs a command and captures standard out in the given temp file.
"""
fileHandle = open(tempFile, 'w')
logger.debug("Running the command: %s" % command)
sts = subprocess.call(command, shell=True, stdout=fileHandle, bufsize=-1)
fileHandle.close()
if sts != 0:
raise RuntimeError("Command: %s exited with non-zero status %i" % (command, sts))
return sts
def popenCatch(command, stdinString=None):
"""Runs a command and return standard out.
"""
logger.debug("Running the command: %s" % command)
if stdinString != None:
process = subprocess.Popen(command, shell=True,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=-1)
output, nothing = process.communicate(stdinString)
else:
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=sys.stderr, bufsize=-1)
output, nothing = process.communicate() #process.stdout.read().strip()
sts = process.wait()
if sts != 0:
raise RuntimeError("Command: %s with stdin string '%s' exited with non-zero status %i" % (command, stdinString, sts))
return output #process.stdout.read().strip()
def popenPush(command, stdinString=None):
if stdinString == None:
system(command)
else:
process = subprocess.Popen(command, shell=True,
stdin=subprocess.PIPE, bufsize=-1)
process.communicate(stdinString)
sts = process.wait()
if sts != 0:
raise RuntimeError("Command: %s with stdin string '%s' exited with non-zero status %i" % (command, stdinString, sts))
def spawnDaemon(command):
"""Launches a command as a daemon. It will need to be explicitly killed
"""
return system("sonLib_daemonize.py \'%s\'" % command)
def getTotalCpuTimeAndMemoryUsage():
"""Gives the total cpu time and memory usage of itself and its children.
"""
me = resource.getrusage(resource.RUSAGE_SELF)
childs = resource.getrusage(resource.RUSAGE_CHILDREN)
totalCpuTime = me.ru_utime+me.ru_stime+childs.ru_utime+childs.ru_stime
totalMemoryUsage = me.ru_maxrss+ me.ru_maxrss
return totalCpuTime, totalMemoryUsage
def getTotalCpuTime():
"""Gives the total cpu time, including the children.
"""
return getTotalCpuTimeAndMemoryUsage()[0]
def getTotalMemoryUsage():
"""Gets the amount of memory used by the process and its children.
"""
return getTotalCpuTimeAndMemoryUsage()[1]
def absSymPath(path):
"""like os.path.abspath except it doesn't dereference symlinks
"""
curr_path = os.getcwd()
return os.path.normpath(os.path.join(curr_path, path))
#########################################################
#########################################################
#########################################################
#testing settings
#########################################################
#########################################################
#########################################################
class TestStatus:
###Global variables used by testing framework to run tests.
TEST_SHORT = 0
TEST_MEDIUM = 1
TEST_LONG = 2
TEST_VERY_LONG = 3
TEST_STATUS = TEST_SHORT
SAVE_ERROR_LOCATION = None
def getTestStatus():
return TestStatus.TEST_STATUS
getTestStatus = staticmethod(getTestStatus)
def setTestStatus(status):
assert status in (TestStatus.TEST_SHORT, TestStatus.TEST_MEDIUM, TestStatus.TEST_LONG, TestStatus.TEST_VERY_LONG)
TestStatus.TEST_STATUS = status
setTestStatus = staticmethod(setTestStatus)
def getSaveErrorLocation():
"""Location to in which to write inputs which created test error.
"""
return TestStatus.SAVE_ERROR_LOCATION
getSaveErrorLocation = staticmethod(getSaveErrorLocation)
def setSaveErrorLocation(dir):
"""Set location in which to write inputs which created test error.
"""
logger.info("Location to save error files in: %s" % dir)
assert os.path.isdir(dir)
TestStatus.SAVE_ERROR_LOCATION = dir
setSaveErrorLocation = staticmethod(setSaveErrorLocation)
def getTestSetup(shortTestNo=1, mediumTestNo=5, longTestNo=100, veryLongTestNo=0):
if TestStatus.TEST_STATUS == TestStatus.TEST_SHORT:
return shortTestNo
elif TestStatus.TEST_STATUS == TestStatus.TEST_MEDIUM:
return mediumTestNo
elif TestStatus.TEST_STATUS == TestStatus.TEST_LONG:
return longTestNo
else: #Used for long example tests
return veryLongTestNo
getTestSetup = staticmethod(getTestSetup)
def getPathToDataSets():
"""This method is used to store the location of
the path where all the data sets used by tests for analysis are kept.
These are not kept in the distrbution itself for reasons of size.
"""
assert "SON_TRACE_DATASETS" in os.environ
return os.environ["SON_TRACE_DATASETS"]
getPathToDataSets = staticmethod(getPathToDataSets)
def saveInputs(savedInputsDir, listOfFilesAndDirsToSave):
"""Copies the list of files to a directory created in the save inputs dir,
and returns the name of this directory.
"""
logger.info("Saving the inputs: %s to the directory: %s" % (" ".join(listOfFilesAndDirsToSave), savedInputsDir))
assert os.path.isdir(savedInputsDir)
#savedInputsDir = getTempDirectory(saveInputsDir)
createdFiles = []
for fileName in listOfFilesAndDirsToSave:
if os.path.isfile(fileName):
copiedFileName = os.path.join(savedInputsDir, os.path.split(fileName)[-1])
system("cp %s %s" % (fileName, copiedFileName))
else:
copiedFileName = os.path.join(savedInputsDir, os.path.split(fileName)[-1]) + ".tar"
system("tar -cf %s %s" % (copiedFileName, fileName))
createdFiles.append(copiedFileName)
return createdFiles
#########################################################
#########################################################
#########################################################
#options parser functions
#########################################################
#########################################################
#########################################################
def getBasicOptionParser(usage="usage: %prog [options]", version="%prog 0.1", parser=None):
if parser is None:
parser = OptionParser(usage=usage, version=version)
addLoggingOptions(parser)
parser.add_option("--tempDirRoot", dest="tempDirRoot", type="string",
help="Path to where temporary directory containing all temp files are created, by default uses the current working directory as the base.",
default=os.getcwd())
return parser
def parseBasicOptions(parser):
"""Setups the standard things from things added by getBasicOptionParser.
"""
(options, args) = parser.parse_args()
setLoggingFromOptions(options)
#Set up the temp dir root
if options.tempDirRoot == "None":
options.tempDirRoot = os.getcwd()
return options, args
def parseSuiteTestOptions(parser=None):
if parser is None:
parser = getBasicOptionParser()
parser.add_option("--testLength", dest="testLength", type="string",
help="Control the length of the tests either SHORT/MEDIUM/LONG/VERY_LONG. default=%default",
default="SHORT")
parser.add_option("--saveError", dest="saveError", type="string",
help="Directory in which to store the inputs of failed tests")
options, args = parseBasicOptions(parser)
logger.info("Parsed arguments")
if options.testLength == "SHORT":
TestStatus.setTestStatus(TestStatus.TEST_SHORT)
elif options.testLength == "MEDIUM":
TestStatus.setTestStatus(TestStatus.TEST_MEDIUM)
elif options.testLength == "LONG":
TestStatus.setTestStatus(TestStatus.TEST_LONG)
elif options.testLength == "VERY_LONG":
TestStatus.setTestStatus(TestStatus.TEST_VERY_LONG)
else:
parser.error('Unrecognised option for --testLength, %s. Options are SHORT, MEDIUM, LONG, VERY_LONG.' %
options.testLength)
if options.saveError is not None:
TestStatus.setSaveErrorLocation(options.saveError)
return options, args
def nameValue(name, value, valueType=str, quotes=False):
"""Little function to make it easier to make name value strings for commands.
"""
if valueType == bool:
if value:
return "--%s" % name
return ""
if value is None:
return ""
if quotes:
return "--%s '%s'" % (name, valueType(value))
return "--%s %s" % (name, valueType(value))
#########################################################
#########################################################
#########################################################
#temp files
#########################################################
#########################################################
#########################################################
def getRandomAlphaNumericString(length=10):
"""Returns a random alpha numeric string of the given length.
"""
return "".join([ random.choice('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz') for i in xrange(0, length) ])
def makeSubDir(dirName):
"""Makes a given subdirectory if it doesn't already exist, making sure it us public.
"""
if not os.path.exists(dirName):
os.mkdir(dirName)
os.chmod(dirName, 0777)
return dirName
def getTempFile(suffix="", rootDir=None):
"""Returns a string representing a temporary file, that must be manually deleted
"""
if rootDir is None:
handle, tmpFile = tempfile.mkstemp(suffix)
os.close(handle)
return tmpFile
else:
tmpFile = os.path.join(rootDir, "tmp_" + getRandomAlphaNumericString() + suffix)
open(tmpFile, 'w').close()
os.chmod(tmpFile, 0777) #Ensure everyone has access to the file.
return tmpFile
def getTempDirectory(rootDir=None):
"""
returns a temporary directory that must be manually deleted. rootDir will be
created if it does not exist.
"""
if rootDir is None:
return tempfile.mkdtemp()
else:
if not os.path.exists(rootDir):
try:
os.makedirs(rootDir)
except OSError:
# Maybe it got created between the test and the makedirs call?
pass
while True:
# Keep trying names until we find one that doesn't exist. If one
# does exist, don't nest inside it, because someone else may be
# using it for something.
tmpDir = os.path.join(rootDir, "tmp_" + getRandomAlphaNumericString())
if not os.path.exists(tmpDir):
break
os.mkdir(tmpDir)
os.chmod(tmpDir, 0777) #Ensure everyone has access to the file.
return tmpDir
class TempFileTree:
"""A hierarchical tree structure for storing directories of files/dirs/
The total number of legal files is equal to filesPerDir**levels.
filesPerDer and levels must both be greater than zero.
The rootDir may or may not yet exist (and may or may not be empty), though
if files exist in the dirs of levels 0 ... level-1 then they must be dirs,
which will be indexed the by tempfile tree.
"""
def __init__(self, rootDir, filesPerDir=500, levels=3):
#Do basic checks of input
assert(filesPerDir) >= 1
assert(levels) >= 1
if not os.path.isdir(rootDir):
#Make the root dir
os.mkdir(rootDir)
open(os.path.join(rootDir, "lock"), 'w').close() #Add the lock file
#Basic attributes of system at start up.
self.levelNo = levels
self.filesPerDir = filesPerDir
self.rootDir = rootDir
#Dynamic variables
self.tempDir = rootDir
self.level = 0
self.filesInDir = 1
#These two variables will only refer to the existance of this class instance.
self.tempFilesCreated = 0
self.tempFilesDestroyed = 0
currentFiles = self.listFiles()
logger.info("We have setup the temp file tree, it contains %s files currently, \
%s of the possible total" % \
(len(currentFiles), len(currentFiles)/math.pow(filesPerDir, levels)))
def getTempFile(self, suffix="", makeDir=False):
while 1:
#Basic checks for start of loop
assert self.level >= 0
assert self.level < self.levelNo
assert os.path.isdir(self.tempDir)
#If tempDir contains max file number then:
if self.filesInDir > self.filesPerDir:
#if level number is already 0 raise an exception
if self.level == 0:
raise RuntimeError("We ran out of space to make temp files")
#Remove the lock file
os.remove(os.path.join(self.tempDir, "lock"))
#reduce level number by one, chop off top of tempDir.
self.level -= 1
self.tempDir = os.path.split(self.tempDir)[0]
self.filesInDir = len(os.listdir(self.tempDir))
else:
if self.level == self.levelNo-1:
self.filesInDir += 1
#make temporary file in dir and return it.
if makeDir:
return getTempDirectory(rootDir=self.tempDir)
else:
return getTempFile(suffix=suffix, rootDir=self.tempDir)
else:
#mk new dir, and add to tempDir path, inc the level buy one.
self.tempDir = getTempDirectory(rootDir=self.tempDir)
open(os.path.join(self.tempDir, "lock"), 'w').close() #Add the lock file
self.level += 1
self.filesInDir = 1
def getTempDirectory(self):
return self.getTempFile(makeDir=True)
def __destroyFile(self, tempFile):
#If not part of the current tempDir, from which files are being created.
baseDir = os.path.split(tempFile)[0]
if baseDir != self.tempDir:
while True: #Now remove any parent dirs that are empty.
try:
os.rmdir(baseDir)
except OSError:
break
baseDir = os.path.split(baseDir)[0]
if baseDir == self.rootDir:
break
def destroyTempFile(self, tempFile):
"""Removes the temporary file in the temp file dir, checking its in the temp file tree.
"""
#Do basic assertions for goodness of the function
assert os.path.isfile(tempFile)
assert os.path.commonprefix((self.rootDir, tempFile)) == self.rootDir #Checks file is part of tree
#Update stats.
self.tempFilesDestroyed += 1
#Do the actual removal
os.remove(tempFile)
self.__destroyFile(tempFile)
def destroyTempDir(self, tempDir):
"""Removes a temporary directory in the temp file dir, checking its in the temp file tree.
The dir will be removed regardless of if it is empty.
"""
#Do basic assertions for goodness of the function
assert os.path.isdir(tempDir)
assert os.path.commonprefix((self.rootDir, tempDir)) == self.rootDir #Checks file is part of tree
#Update stats.
self.tempFilesDestroyed += 1
#Do the actual removal
try:
os.rmdir(tempDir)
except OSError:
shutil.rmtree(tempDir)
#system("rm -rf %s" % tempDir)
self.__destroyFile(tempDir)
def listFiles(self):
"""Gets all files in the temp file tree (which may be dirs).
"""
def fn(dirName, level, files):
if level == self.levelNo-1:
for fileName in os.listdir(dirName):
if fileName != "lock":
absFileName = os.path.join(dirName, fileName)
files.append(absFileName)
else:
for subDir in os.listdir(dirName):
if subDir != "lock":
absDirName = os.path.join(dirName, subDir)
assert os.path.isdir(absDirName)
fn(absDirName, level+1, files)
files = []
fn(self.rootDir, 0, files)
return files
def destroyTempFiles(self):
"""Destroys all temp temp file hierarchy, getting rid of all files.
"""
os.system("rm -rf %s" % self.rootDir)
logger.debug("Temp files created: %s, temp files actively destroyed: %s" % (self.tempFilesCreated, self.tempFilesDestroyed))
#########################################################
#########################################################
#########################################################
#misc input/output functions
#########################################################
#########################################################
#########################################################
def getNextNonCommentLine(file):
line = file.readline()
while line != '' and line[0] == '#':
line = file.readline()
return line
def removeNewLine(line):
if line != '' and line[-1] == '\n':
return line[:-1]
return line
def readFirstLine(inputFile):
i = open(inputFile, 'r')
j = removeNewLine(i.readline())
i.close()
return j
def padWord(word, length=25):
if len(word) > length:
return word[:length]
if len(word) < length:
return word + " "*(length-len(word))
return word
#########################################################
#########################################################
#########################################################
#Generic file functions
#########################################################
#########################################################
#########################################################
def catFiles(filesToCat, catFile):
"""Cats a bunch of files into one file. Ensures a no more than maxCat files
are concatenated at each step.
"""
if len(filesToCat) == 0: #We must handle this case or the cat call will hang waiting for input
open(catFile, 'w').close()
return
maxCat = 25
system("cat %s > %s" % (" ".join(filesToCat[:maxCat]), catFile))
filesToCat = filesToCat[maxCat:]
while len(filesToCat) > 0:
system("cat %s >> %s" % (" ".join(filesToCat[:maxCat]), catFile))
filesToCat = filesToCat[maxCat:]
def prettyXml(elem):
""" Return a pretty-printed XML string for the ElementTree Element.
"""
roughString = ET.tostring(elem, "utf-8")
reparsed = minidom.parseString(roughString)
return reparsed.toprettyxml(indent=" ")
def isNewer(firstFile, secondFile):
"""Returns True if the first file was modified more recently than the second file (used os.path.getctime)
"""
assert os.path.exists(firstFile)
assert os.path.exists(secondFile)
return os.path.getctime(firstFile) > os.path.getctime(secondFile)
#########################################################
#########################################################
#########################################################
#fasta/fastq functions
#########################################################
#########################################################
#########################################################
def fastaNormaliseHeader(fastaHeader):
"""Removes white space which is treated weirdly by many programs.
"""
i = fastaHeader.split()
if len(i) > 0:
return i[0]
return ""
def fastaDecodeHeader(fastaHeader):
"""Decodes the fasta header
"""
return fastaHeader.split("|")
def fastaEncodeHeader(attributes):
"""Decodes the fasta header
"""
for i in attributes:
assert len(str(i).split()) == 1
return "|".join([ str(i) for i in attributes ])
def _getFileHandle(fileHandleOrFile, mode="r"):
if isinstance(fileHandleOrFile, "".__class__):
return open(fileHandleOrFile, mode)
else:
return fileHandleOrFile
def fastaRead(fileHandleOrFile):
"""iteratively yields a sequence for each '>' it encounters, ignores '#' lines
"""
fileHandle = _getFileHandle(fileHandleOrFile)
line = fileHandle.readline()
chars_to_remove = "\n "
valid_chars = {x for x in string.ascii_letters + "-"}
while line != '':
if line[0] == '>':
name = line[1:-1]
line = fileHandle.readline()
seq = array.array('c')
while line != '' and line[0] != '>':
line = line.translate(None, chars_to_remove)
if len(line) > 0 and line[0] != '#':
seq.extend(line)
line = fileHandle.readline()
try:
assert all(x in valid_chars for x in seq)
except AssertionError:
bad_chars = {x for x in seq if x not in valid_chars}
raise RuntimeError("Invalid FASTA character(s) see in fasta sequence: {}".format(bad_chars))
yield name, seq.tostring()
else:
line = fileHandle.readline()
if isinstance(fileHandleOrFile, "".__class__):
fileHandle.close()
def fastaWrite(fileHandleOrFile, name, seq, mode="w"):
"""Writes out fasta file
"""
fileHandle = _getFileHandle(fileHandleOrFile, mode)
valid_chars = {x for x in string.ascii_letters + "-"}
try:
assert any([isinstance(seq, unicode), isinstance(seq, str)])
except AssertionError:
raise RuntimeError("Sequence is not unicode or string")
try:
assert all(x in valid_chars for x in seq)
except AssertionError:
bad_chars = {x for x in seq if x not in valid_chars}
raise RuntimeError("Invalid FASTA character(s) see in fasta sequence: {}".format(bad_chars))
fileHandle.write(">%s\n" % name)
chunkSize = 100
for i in xrange(0, len(seq), chunkSize):
fileHandle.write("%s\n" % seq[i:i+chunkSize])
if isinstance(fileHandleOrFile, "".__class__):
fileHandle.close()
def fastqRead(fileHandleOrFile):
"""Reads a fastq file iteratively
"""
fileHandle = _getFileHandle(fileHandleOrFile)
line = fileHandle.readline()
while line != '':
if line[0] == '@':
name = line[1:-1]
seq = fileHandle.readline()[:-1]
plus = fileHandle.readline()
if plus[0] != '+':
raise RuntimeError("Got unexpected line: %s" % plus)
qualValues = [ ord(i) for i in fileHandle.readline()[:-1] ]
if len(seq) != len(qualValues):
logger.critical("Got a mismatch between the number of sequence characters (%s) and number of qual values (%s) for sequence: %s, ignoring returning None" % (len(seq), len(qualValues), name))
qualValues = None
else:
for i in qualValues:
if i < 33 or i > 126:
raise RuntimeError("Got a qual value out of range %s (range is 33 to 126)" % i)
for i in seq:
#For safety and sanity I only allows roman alphabet characters in fasta sequences.
if not ((i >= 'A' and i <= 'Z') or (i >= 'a' and i <= 'z') or i == '-'):
raise RuntimeError("Invalid FASTQ character, ASCII code = \'%d\', found in input sequence %s" % (ord(i), name))
yield name, seq, qualValues
line = fileHandle.readline()
if isinstance(fileHandleOrFile, "".__class__):
fileHandle.close()
def fastqWrite(fileHandleOrFile, name, seq, qualValues, mode="w"):
"""Writes out fastq file. If qualValues is None or '*' then prints a '*' instead.
"""
fileHandle = _getFileHandle(fileHandleOrFile, mode)
assert seq.__class__ == "".__class__
for i in seq:
if not ((i >= 'A' and i <= 'Z') or (i >= 'a' and i <= 'z') or i == '-'): #For safety and sanity I only allows roman alphabet characters in fasta sequences.
raise RuntimeError("Invalid FASTQ character, ASCII code = \'%d\', char = '%s' found in input sequence %s" % (ord(i), i, name))
if qualValues != None and qualValues != '*':
if len(seq) != len(qualValues):
raise RuntimeError("Got a mismatch between the number of sequence characters (%s) and number of qual values (%s) for sequence: %s " % (len(seq), len(qualValues), name))
for i in qualValues:
if i < 33 or i > 126:
raise RuntimeError("Got a qual value out of range %s (range is 33 to 126)" % i)
fileHandle.write("@%s\n%s\n+\n%s\n" % (name, seq, "".join([ chr(i) for i in qualValues ])))
else:
fileHandle.write("@%s\n%s\n+\n*\n" % (name, seq))
if isinstance(fileHandleOrFile, "".__class__):
fileHandle.close()
def _getMultiFastaOffsets(fasta):
"""Reads in columns of multiple alignment and returns them iteratively
"""
f = open(fasta, 'r')
i = 0
j = f.read(1)
l = []
while j != '':
i += 1
if j == '>':
i += 1
while f.read(1) != '\n':
i += 1
l.append(i)
j = f.read(1)
f.close()
return l
def fastaReadHeaders(fasta):
"""Returns a list of fasta header lines, excluding
"""
headers = []
fileHandle = open(fasta, 'r')
line = fileHandle.readline()
while line != '':
assert line[-1] == '\n'
if line[0] == '>':
headers.append(line[1:-1])
line = fileHandle.readline()
fileHandle.close()
return headers
def fastaAlignmentRead(fasta, mapFn=(lambda x : x), l=None):
"""
reads in columns of multiple alignment and returns them iteratively
"""
if l is None:
l = _getMultiFastaOffsets(fasta)
else:
l = l[:]
seqNo = len(l)
for i in xrange(0, seqNo):
j = open(fasta, 'r')
j.seek(l[i])
l[i] = j
column = [sys.maxint]*seqNo
if seqNo != 0:
while True:
for j in xrange(0, seqNo):
i = l[j].read(1)
while i == '\n':
i = l[j].read(1)
column[j] = i
if column[0] == '>' or column[0] == '':
for j in xrange(1, seqNo):
assert column[j] == '>' or column[j] == ''
break
for j in xrange(1, seqNo):
assert column[j] != '>' and column[j] != ''
column[j] = mapFn(column[j])
yield column[:]
for i in l:
i.close()
def fastaAlignmentWrite(columnAlignment, names, seqNo, fastaFile,
filter=lambda x : True):
"""
Writes out column alignment to given file multi-fasta format
"""
fastaFile = open(fastaFile, 'w')
columnAlignment = [ i for i in columnAlignment if filter(i) ]
for seq in xrange(0, seqNo):
fastaFile.write(">%s\n" % names[seq])
for column in columnAlignment:
fastaFile.write(column[seq])
fastaFile.write("\n")
fastaFile.close()
def getRandomSequence(length=500):
"""Generates a random name and sequence.
"""
fastaHeader = ""
for i in xrange(int(random.random()*100)):
fastaHeader = fastaHeader + random.choice([ 'A', 'C', '0', '9', ' ', '\t' ])
return (fastaHeader, \
"".join([ random.choice([ 'A', 'C', 'T', 'G', 'A', 'C', 'T', 'G', 'A', 'C', 'T', 'G', 'A', 'C', 'T', 'G', 'A', 'C', 'T', 'G', 'N' ]) for i in xrange((int)(random.random() * length))]))
def _expLength(i=0, prob=0.95):
if random.random() >= prob:
return _expLength(i+1)
return i
def mutateSequence(seq, distance):
"""Mutates the DNA sequence for use in testing.
"""
subProb=distance
inProb=0.05*distance
deProb=0.05*distance
contProb=0.9
l = []
bases = [ 'A', 'C', 'T', 'G' ]
i=0
while i < len(seq):
if random.random() < subProb:
l.append(random.choice(bases))
else:
l.append(seq[i])
if random.random() < inProb:
l += getRandomSequence(_expLength(0, contProb))[1]
if random.random() < deProb:
i += int(_expLength(0, contProb))
i += 1
return "".join(l)
def reverseComplement(seq):
seq = list(seq)
seq.reverse()
dNA = { 'A':'T', 'T':'A', 'C':'G', 'G':'C', 'a':'t', 't':'a', 'c':'g', 'g':'c' }
def fn(i):
if i in dNA:
return dNA[i]
return i
return "".join([ fn(i) for i in seq ])
#########################################################
#########################################################
#########################################################
#newick tree functions
#########################################################
#########################################################
#########################################################
def newickTreeParser(newickTree, defaultDistance=DEFAULT_DISTANCE, \
sortNonBinaryNodes=False, reportUnaryNodes=False):
"""
lax newick tree parser
"""
newickTree = newickTree.replace("(", " ( ")
newickTree = newickTree.replace(")", " ) ")
newickTree = newickTree.replace(":", " : ")
newickTree = newickTree.replace(";", "")
newickTree = newickTree.replace(",", " , ")
newickTree = re.compile("[\s]*").split(newickTree)
while "" in newickTree:
newickTree.remove("")
def fn(newickTree, i):
if i[0] < len(newickTree):
if newickTree[i[0]] == ':':
d = float(newickTree[i[0]+1])
i[0] += 2
return d
return defaultDistance
def fn2(newickTree, i):
if i[0] < len(newickTree):
j = newickTree[i[0]]
if j != ':' and j != ')' and j != ',':
i[0] += 1
return j
return None
def fn3(newickTree, i):
if newickTree[i[0]] == '(':
#subTree1 = None
subTreeList = []
i[0] += 1
k = []
while newickTree[i[0]] != ')':
if newickTree[i[0]] == ',':
i[0] += 1
subTreeList.append(fn3(newickTree, i))
i[0] += 1
def cmp(i, j):
if i.distance < j.distance:
return -1
if i.distance > j.distance:
return 1
return 0
if sortNonBinaryNodes:
subTreeList.sort(cmp)
subTree1 = subTreeList[0]
if len(subTreeList) > 1:
for subTree2 in subTreeList[1:]:
subTree1 = BinaryTree(0.0, True, subTree1, subTree2, None)
subTree1.iD = fn2(newickTree, i)
subTree1.distance += fn(newickTree, i)
elif reportUnaryNodes:
subTree1 = BinaryTree(0.0, True, subTree1, None, None)
subTree1.iD = fn2(newickTree, i)
subTree1.distance += fn(newickTree, i)