obiselect.py 9.7 KB
Newer Older
1
#!/usr/local/bin/python
2
"""
Aurélie Bonin committed
3
:py:mod:`obiselect` : selects representative sequence records
4
=============================================================
5

6 7
.. codeauthor:: Eric Coissac <eric.coissac@metabarcoding.org>

8 9 10
:py:mod:`obiselect` command allows to select a subset of sequences records from a sequence
file by describing sequence record groups and defining how many and which sequence records
from each group must be retrieved.
Frédéric Boyer committed
11

12
"""
13
from obitools.format.options import addInOutputOption, sequenceWriterGenerator
14
from obitools.options import getOptionManager
15 16
from obitools.ecopcr.options import addTaxonomyDBOptions, loadTaxonomyDatabase
from random import random
17
from obitools.utils import progressBar
18
import math
19
import sys
20
from obitools.utils.bioseq import mergeTaxonomyClassification
21 22 23 24 25

def minimum(seqs):
    return min(s['select'] for s in seqs)

def maximum(seqs):
26 27 28 29 30
    try:
        return max(s['select'] for s in seqs)
    except TypeError, e:
        print >>sys.stderr, seqs
        raise e
31 32 33 34 35 36 37 38 39 40
def mean(seqs):
    ss= reduce(lambda x,y: x + y,(s['select'] for s in seqs),0)
    return float(ss) / len(seqs)

def median(seqs):
    ss = [s['select'] for s in seqs]
    ss.sort()
    return ss[len(ss)/2]

    
41 42 43

def addSelectOptions(optionManager):
    
44 45 46 47
    group = optionManager.add_option_group('obiselect specific options')

    
    group.add_option('-c','--category-attribute',
48 49 50 51
                             action="append", dest="categories",
                             metavar="<Attribute Name>",
                             default=[],
                             help="Add one attribute to the list of"
52
                                  " attribute used for categorizing sequence records")
53

54
    group.add_option('-n','--number',
55 56 57 58
                             action="store", dest="number",
                             metavar="",
                             type="int",
                             default=1,
59
                             help="number of sequence records to keep in each category")
60

61
    group.add_option('-f','--function',
62 63 64
                             action="store", dest="function",
                             metavar="",
                             default="random",
65
                             help="python code evaluated for each sequence record [default: random value]")
66 67

   
68
    group.add_option('-m','--min',
69 70 71 72
                             action="store_const", dest="method",
                             metavar="",
                             default=maximum,
                             const=minimum,
73 74
                             help="select sequence record in each group minimizing the function"
                                  " (exclusive with -M, -a, --median)")
75
    
76
    group.add_option('-M','--max',
77
                             action="store_const", dest="method",
78
                             metavar="",
79 80
                             default=maximum,
                             const=maximum,
81 82
                             help="select sequence record in each group maximizing the function"
                                  " (exclusive with -m, -a, --median)")
83

84
    group.add_option('-a','--mean',
85
                             action="store_const", dest="method",
86
                             metavar="",
87 88
                             default=maximum,
                             const=mean,
89 90
                             help="select sequence record in each group closest to the mean of the function"
                                  " (exclusive with -m, -M, --median)")
91

92
    group.add_option('--median',
93 94 95 96
                             action="store_const", dest="method",
                             metavar="<Attribute Name>",
                             default=maximum,
                             const=median,
97 98
                             help="select sequence record in each group closest to the median of the function"
                                  " (exclusive with -m, -M, -a)")
99

100
    group.add_option('--merge',
101 102
                             action="append", dest="merge",
                             metavar="<TAG NAME>",
103
                             type="string",
104
                             default=[],
105
                             help="attributes to merge within each group")
106

107 108 109 110 111 112 113
    group.add_option('-s','--sample',
                             action="store", dest="sample",
                             metavar="<TAGNAME>",
                             type="str",
                             default=None,
                             help="Tag containing sample descriptions, the default value is set to *merged_sample*")

114
    group.add_option('--merge-ids',
115
                             action="store_true", dest="mergeids",
Eric Coissac committed
116
                             default=False,
117 118
                             help="add the merged id data to output")
    
Eric Coissac committed
119

120

121 122 123 124 125 126
def sortclass(seqs,options):
    cible = float(options.method(seqs))
    for s in seqs:
        s['distance']=math.sqrt((float(s['select'])-cible)**2)
    seqs.sort(lambda s1,s2 : cmp(s1['distance'],s2['distance']))
                                                
127 128 129


if __name__ == '__main__':
130 131
    
    optionParser = getOptionManager([addSelectOptions,addInOutputOption,addTaxonomyDBOptions])
132 133 134
    
    (options, entries) = optionParser()
    
135 136
    taxonomy=loadTaxonomyDatabase(options)

Eric Coissac committed
137 138
    writer = sequenceWriterGenerator(options)
    
139 140
    classes = {}
    
141
    print >>sys.stderr,"\nLoading sequences...\n"
142 143
    
    with_taxonomy=hasattr(options, 'taxonomy') and options.taxonomy is not None
144

145 146
    nbseq=0
    
147
    for s in entries:
148
        nbseq+=1
149
        category = []
150 151 152 153 154 155

        if with_taxonomy:
            environ = {'taxonomy' : options.taxonomy,'sequence':s,'random':random()}
        else:
            environ = {'sequence':s,'random':random()}

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
        for c in options.categories:
            try:
                v = eval(c,environ,s)
                category.append(v)
            except:
                category.append(None)

        category=tuple(category)
        group = classes.get(category,[])
        group.append(s)
        classes[category]= group
            
        try:    
            select =  eval(options.function,environ,s)
            s['select']=select
        except:
            s['select']=None
 
    mergedKey = options.merge
    mergeIds = options.mergeids 
          
    if mergedKey is not None:
        mergedKey=set(mergedKey)
    else:
        mergedKey=set() 
181
    
182 183 184 185
    if taxonomy is not None:
        mergedKey.add('taxid')
                
    
186 187 188 189 190
    print >>sys.stderr,"\nSelecting sequences...\n"
    
    lclasses=len(classes)
    progressBar(1,lclasses,True,'Selecting')
    i=0
191
    for c in classes:
192
        i+=1
193
        progressBar(i,lclasses,False,"%15s" % ("/".join(map(str,c)),))
194
        seqs = classes[c]
195 196 197 198 199 200 201 202 203
        if options.sample is not None:
            subsets = {}
            for s in seqs:
                for sid in s[options.sample]:
                    ss = subsets.get(sid,[])
                    ss.append(s)
                    subsets[sid]=ss
        else:
            subsets={"all":seqs}
204
            
205 206
        for seqs in subsets.values():
            sortclass(seqs, options)
207
            
208 209
            if len(c)==1:
                c=c[0]
210
                
211 212
            if options.number==1 and options.sample is None:
                s = seqs[0]
213 214 215
                
                for key in mergedKey:
                    if key=='taxid' and mergeIds:
216 217 218 219
                        if 'taxid_dist' not in s:
                            s["taxid_dist"]={}
                        if 'taxid' in s:
                            s["taxid_dist"][s.id]=s['taxid']
220
                    mkey = "merged_%s" % key 
221 222 223 224 225 226 227 228
                    if mkey not in s:
                        if key in s:
                            s[mkey]={s[key]:1}
                        else:
                            s[mkey]={}
    
                if 'count' not in s:
                    s['count']=1
229
                if mergeIds:        
230 231 232
                    s['merged']=[s.id]
    
                for seq in seqs[1:]:
233
                    
234 235 236 237 238
                    if 'count' in seq:
                        s['count']+=seq['count']
                    else:
                        s['count']+=1
                        
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
                    for key in mergedKey:
                        if key=='taxid' and mergeIds:
                            if 'taxid_dist' in seq:
                                s["taxid_dist"].update(seq["taxid_dist"])
                            if 'taxid' in seq:
                                s["taxid_dist"][seq.id]=seq['taxid']
                                
                        mkey = "merged_%s" % key 
                        if mkey in seq:
                            m = seq[mkey]
                        else:
                            if key in seq:
                                m={seq[key]:1}
                                
                        allmkey = set(m.keys()) | set(s[mkey].keys())
                        s[mkey] = dict((k,m.get(k,0)+s[mkey].get(k,0)) for k in allmkey)
                                                    
                    if mergeIds:        
                        s['merged'].append(seq.id)
     
                if taxonomy is not None:
                    mergeTaxonomyClassification(seqs, taxonomy)
                        
262
            
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
            for s in seqs[0:options.number]:
                s['class']=c
                s['__@TOWRITE@__']=True
     
    print >>sys.stderr,"\Writing sequences...\n"
    progressBar(1,nbseq,True,'Writing')
           
    i=0
    for c in classes:
        seqs = classes[c]
        for s in seqs:
            i+=1
            progressBar(i,nbseq,False,"Writing")
            if '__@TOWRITE@__' in s:
                del s['__@TOWRITE@__']
                del s['select']
                writer(s)
        
281
    print >>sys.stderr