Imported Upstream version 0.5
[pysam.git] / pysam / __init__.py
1 from csamtools import *
2 from ctabix import *
3 import csamtools
4 import ctabix
5 from cvcf import *
6 import cvcf
7 import Pileup
8 import sys
9 import os
10
11 class SamtoolsError( Exception ):
12     '''exception raised in case of an error incurred in the samtools library.'''
13
14     def __init__(self, value):
15         self.value = value
16     def __str__(self):
17         return repr(self.value)
18
19 class SamtoolsDispatcher(object):
20     '''samtools dispatcher. 
21
22     Emulates the samtools command line as module calls.
23     
24     Captures stdout and stderr. 
25
26     Raises a :class:`pysam.SamtoolsError` exception in case
27     samtools exits with an error code other than 0.
28
29     Some command line options are associated with parsers.
30     For example, the samtools command "pileup -c" creates
31     a tab-separated table on standard output. In order to 
32     associate parsers with options, an optional list of 
33     parsers can be supplied. The list will be processed
34     in order checking for the presence of each option.
35
36     If no parser is given or no appropriate parser is found, 
37     the stdout output of samtools commands will be returned.
38     '''
39     dispatch=None
40     parsers=None
41
42     def __init__(self,dispatch, parsers): 
43         self.dispatch = dispatch
44         self.parsers = parsers
45         self.stderr = []
46
47     def __call__(self, *args, **kwargs):
48         '''execute a samtools command
49         '''
50         retval, stderr, stdout = csamtools._samtools_dispatch( self.dispatch, args )
51         if retval: raise SamtoolsError( "\n".join( stderr ) )
52         self.stderr = stderr
53         # samtools commands do not propagate the return code correctly.
54         # I have thus added this patch to throw if there is output on stderr.
55         # Note that there is sometimes output on stderr that is not an error,
56         # for example: [sam_header_read2] 2 sequences loaded.
57         # Ignore messages like these
58         stderr = [ x for x in stderr \
59                        if not (x.startswith( "[sam_header_read2]" ) or \
60                                    x.startswith("[bam_index_load]") or \
61                                    x.startswith("[bam_sort_core]") or \
62                                    x.startswith("[samopen] SAM header is present") )
63                    ]
64         if stderr: raise SamtoolsError( "\n".join( stderr ) )
65
66         # call parser for stdout:
67         if not kwargs.get("raw") and stdout and self.parsers:
68             for options, parser in self.parsers:
69                 for option in options: 
70                     if option not in args: break
71                 else:
72                     return parser(stdout)
73
74         return stdout
75
76     def getMessages( self ):
77         return self.stderr
78
79     def usage(self):
80         '''return the samtools usage information for this command'''
81         retval, stderr, stdout = csamtools._samtools_dispatch( self.dispatch )
82         return "".join(stderr)
83
84 #
85 # samtools command line options to export in python
86 #
87 # import is a python reserved word.
88 SAMTOOLS_DISPATCH = { 
89     "view" : ( "view", None ),
90     "sort" : ( "sort", None),
91     "samimport": ( "import", None),
92     "pileup" : ( "pileup", ( (("-c",), Pileup.iterate ), ), ),
93     "faidx" : ("faidx", None),
94     "tview" : ("tview", None),
95     "index" : ("index", None),
96     "fixmate" : ("fixmate", None),
97     "glfview" : ("glfview", None),
98     "flagstat" : ("flagstat", None),
99     "calmd" : ("calmd", None),
100     "merge" : ("merge", None),  
101     "rmdup" : ("rmdup", None) }
102
103 # instantiate samtools commands as python functions
104 for key, options in SAMTOOLS_DISPATCH.iteritems():
105     cmd, parser = options
106     globals()[key] = SamtoolsDispatcher(cmd, parser)
107
108 # hack to export all the symbols from csamtools
109 __all__ = \
110     csamtools.__all__ + \
111     ctabix.__all__ + \
112     cvcf.__all__ +\
113     [ "SamtoolsError", "SamtoolsDispatcher" ] + list(SAMTOOLS_DISPATCH) +\
114     ["Pileup" ] 
115
116 from version import __version__, __samtools_version__