Biom.py 35.6 KB
Newer Older
Jerome Mariette's avatar
Jerome Mariette committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#
# Copyright (C) 2012 INRA
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

Penom Nom's avatar
Penom Nom committed
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
import time, json, random, copy, sys

def _bootstrap_remove_elts( OTU_count, nb_total_elts, nb_removed_elts ):
    """
    @summary : Randomly removes 'nb_removed_elts' elements in the OTU_count.
     @param OTU_count : [list] the number of elements by OTU. Example :
          [
            { 'id' : 'OTU_1', 'nb' : 10 },
            { 'id' : 'OTU_8', 'nb' : 0  }
          ]
     @param nb_total_elts : [int] the total number of elements in 'OTU_count'.
     @param nb_removed_elts : [int] the number of elements to remove.
    @return : [list, int] the new OTU_count and nb_total_elts.
    """
    if nb_total_elts <= nb_removed_elts :
        raise ValueError( "The Biom only contains " + str(nb_total_elts) + " elements. You cannot remove " + str(nb_removed_elts) + " elements." )
    new_OTU_count = copy.deepcopy( OTU_count )
    nb_curr_remaining_elts = nb_total_elts
    # For each element to remove
    for i in range(nb_removed_elts):
        elt_index = random.randint(1, nb_curr_remaining_elts)
        find = False
        OTU_idx = 0
        previous_elt = 0
        while not find:
            # If element to remove is an element of current OTU
            if elt_index <= (new_OTU_count[OTU_idx]["nb"] + previous_elt):
                find = True
                new_OTU_count[OTU_idx]["nb"] -= 1
            # Next OTU
            previous_elt += new_OTU_count[OTU_idx]["nb"]
            OTU_idx += 1
        nb_curr_remaining_elts -= 1
    return new_OTU_count, (nb_total_elts - nb_removed_elts)

def _bootstrap_selection( OTU_count, nb_total_elts, nb_selected_elts ):
    """
    @summary : Random sampling with replacement. Select 'nb_selected_elts' elements in the OTU_count.
     @param OTU_count : [list] the number of elements by OTU. Example :
          [
            { 'id' : 'OTU_1', 'nb' : 10 },
            { 'id' : 'OTU_8', 'nb' : 0  }
          ]
     @param nb_total_elts : [int] the total number of elements in 'OTU_count'.
     @param nb_selected_elts : [int] the number of elements to select.
    @return : [dict] the number of selected elements by OTU (the OTU with 0 selected elements are not in the dictionary).
    """
    if nb_selected_elts > nb_total_elts :
        sys.stderr.write( "[WARNING] The number of elements in the count is inferior at the number of selected elements.\n" )
    selected_OTU = dict()
    for i in range(nb_selected_elts):
        elt_index = random.randint(1, nb_total_elts)
        find = False
        OTU_idx = 0
        previous_elt = 0
        while not find:
            if elt_index <= (OTU_count[OTU_idx]["nb"] + previous_elt):
                find = True
                OTU_id = OTU_count[OTU_idx]["id"]
                if selected_OTU.has_key( OTU_id ):
                    selected_OTU[OTU_id] += 1
                else:
                    selected_OTU[OTU_id] = 1
            previous_elt += OTU_count[OTU_idx]["nb"]
            OTU_idx += 1
    return selected_OTU

Penom Nom's avatar
Penom Nom committed
85

Penom Nom's avatar
Penom Nom committed
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
class DenseData( list ):
    def get_matrix_type( self ):
        """
        @summary : Retruns the type of matrix.
        @return : [str] The matrix type.
        """
        return "dense"

    def remove_col( self, remove_idx ):
        for row_idx in range(len(self)):
            del self.data[row_idx][remove_idx]
    
    def remove_row( self, remove_idx ):
        del self.data[remove_idx]
        
    def nb_at( self, row_idx, col_idx ):
        return self[row_idx][col_idx]

    def merge_col( self, sum_idx, added_idx ):
        for row in self:
            row[sum_idx] += row[added_idx]
        self.remove_col( added_idx )

    def get_col_sum( self, col_idx ):
        """
        @todo test
        """
        total = 0
        for current_row in self:
            total += current_row[col_idx]
        return total

    def get_row_sum( self, row_idx ):
        """
        @todo test
        """
        total = 0
        for current_col in self[row_idx]:
            total += current_col
        return total

    def clear( self ):
        """
        @summary : Clear data.
        """
        self = DenseData()

133
134
135
136
137
138
    def _to_list( self ):
        """
        @todo test
        """
        return self

Penom Nom's avatar
Penom Nom committed
139

140
141
142
143
144
145
146
147
148
149
150
151
class SparseData( dict ):
    def __init__( self, list=list() ):
        for data in list:
            if not self.has_key( data[0] ):
                self[data[0]] = dict()
            self[data[0]][data[1]] = data[2]
     
    def _to_list( self ):
        """
        @todo test
        """
        sparse = list()
Penom Nom's avatar
Penom Nom committed
152
        for rows_idx in sorted(self.keys(), key=int):
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
            for columns_idx in sorted(self[rows_idx].keys()):
                sparse.append([ rows_idx, columns_idx, self[rows_idx][columns_idx] ])
        return sparse
    
    def get_matrix_type( self ):
        """
        @summary : Retruns the type of matrix.
        @return : [str] The matrix type.
        """
        return "sparse"

    def remove_col( self, remove_idx ):
        """
        @summary : Remove all the count for the column provided.
         @param remove_idx : [int] The real index of the column to remove.
        """
        for rows_idx in self.keys():
            # Remove data
            if self[rows_idx].has_key( remove_idx ):
                del self[rows_idx][remove_idx]
            # Change index
Penom Nom's avatar
Penom Nom committed
174
            row_columns_idx = sorted( self[rows_idx].keys(), key=int )
175
176
177
178
179
180
181
182
183
184
185
            for column_idx in row_columns_idx:
                if column_idx > remove_idx:
                    self[rows_idx][column_idx -1] = self[rows_idx][column_idx]
                    del self[rows_idx][column_idx]    
        
    def remove_row( self, remove_idx ):
        """
        @summary : Remove all the count for the row provided.
         @param remove_idx : [int] The real index of the row to remove.
        """
        # Remove data
Penom Nom's avatar
Penom Nom committed
186
187
        if self.has_key( remove_idx ):
            del self[remove_idx]
188
        # Change indexes
Penom Nom's avatar
Penom Nom committed
189
        all_rows_idx = sorted( self.keys(), key=int )
190
191
192
193
194
195
196
197
198
199
200
201
202
203
        for row_idx in all_rows_idx:
            if row_idx > remove_idx:
                self[row_idx - 1] = self[row_idx]
                del self[row_idx]
    
    def merge_col( self, sum_idx, added_idx ):
        """
        @summary : Merge two columns. The count of each row of the first column (sum_idx) becomes the sum of the values of the two columns ; the second column is deleted.
         @param sum_idx : [int] The index of the first column to merge. This column is replaced by the new merged column.
         @param added_idx : [int] The index of the second column to merge. This column is deleted after the process.
        """
        # Merge counts
        added_values = dict()
        for row_idx in self.keys():
Penom Nom's avatar
Penom Nom committed
204
            if self[row_idx].has_key( added_idx ):
205
206
207
208
209
210
                self.add( row_idx, sum_idx, self[row_idx][added_idx] )
        # Remove column
        self.remove_col( added_idx )
    
    def nb_at( self, row_idx, col_idx ):
        """
Penom Nom's avatar
Penom Nom committed
211
        @return : [int] The count for the column col_idx in row row_idx.
Penom Nom's avatar
Penom Nom committed
212
213
         @param row_idx : [int] The index of the row.
         @param col_idx : [int] The index of the column.
214
215
216
217
218
219
220
221
        """
        nb = 0
        if self.has_key(row_idx) and self[row_idx].has_key(col_idx):
            nb = self[row_idx][col_idx]
        return nb

    def get_col_sum( self, col_idx ):
        """
Penom Nom's avatar
Penom Nom committed
222
223
        @return : [int] The sum of count for the column col_idx.
         @param col_idx : [int] The index of the column.
224
225
226
227
228
229
230
231
232
        """
        total = 0
        for row_idx in self.keys():
            if self[row_idx].has_key( col_idx ):
                total += self[row_idx][col_idx]
        return total

    def get_row_sum( self, row_idx ):
        """
Penom Nom's avatar
Penom Nom committed
233
234
        @return : [int] The sum of count for the row row_idx.
         @param row_idx : [int] The index of the row.
235
236
237
238
239
240
241
242
243
        """
        total = 0
        if self.has_key( row_idx ):
            for column_idx in self[row_idx].keys():
                total += self[row_idx][column_idx]
        return total

    def row_to_array( self, row_idx, nb_col ):
        """
Penom Nom's avatar
Penom Nom committed
244
245
246
247
        @return : [list] The count for the row for each column.
                   Example : '[0, 2, 0, 0]' only the second column has this observation.
         @param row_idx : [int] The index of the row.
         @param nb_col : [int] The expected number of columns.
248
249
250
251
252
253
254
255
256
        """
        array = [0 for current in range(nb_col)]
        if self.has_key( row_idx ):
            for column_idx in sorted( self[row_idx].keys() ):
                array[column_idx] = self[row_idx][column_idx]
        return array

    def add( self, row_idx, col_idx, value ):
        """
Penom Nom's avatar
Penom Nom committed
257
258
259
260
        @summary : Add the 'value' to the count for the column col_idx in row row_idx.
         @param row_idx : [int] The index of the row.
         @param col_idx : [int] The index of the column.
         @param value : [int] The value to add.
261
262
263
264
265
266
        """
        if not self.has_key( row_idx ):
            self[row_idx] = { col_idx : 0 }
        elif not self[row_idx].has_key( col_idx ):
            self[row_idx][col_idx] = 0
        self[row_idx][col_idx] += value
Penom Nom's avatar
Penom Nom committed
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
        
    def change( self, row_idx, col_idx, value ):
        """
        @summary : Change the 'value' to the count for the column col_idx in row row_idx.
         @param row_idx : [int] The index of the row.
         @param col_idx : [int] The index of the column.
         @param value : [int] The new value.
        """
        if value != 0:
            if not self.has_key( row_idx ):
                self[row_idx] = { col_idx : value }
            else:
                self[row_idx][col_idx] = value
        else:
            if self.has_key( row_idx ) and self[row_idx].has_key( col_idx ) :
                del self[row_idx][col_idx]
283
284
285

    def add_row( self ):
        pass # Nothing to do
Penom Nom's avatar
Penom Nom committed
286

287
288
289
290
    def add_column( self ):
        pass # Nothing to do


Penom Nom's avatar
Penom Nom committed
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
class Biom:
    """
    @summary : Store biological sample by observation contingency tables.
    @see : https://github.com/biom-format
    """
    def __init__( self, id=None, format="Biological Observation Matrix 1.0.0-dev", 
                  format_url="http://biom-format.org", type="OTU table", generated_by=None, 
                  date=time.strftime('%y-%m-%dT%H:%M:%S',time.localtime()), rows=list(), 
                  columns=list(), matrix_type="dense", matrix_element_type="int", 
                  data=list() ):
        self.id = id
        self.format = format
        self.format_url = format_url
        self.type = type
        self.generated_by = generated_by
        self.date = date
        self.rows = rows
        self.columns = columns
        self.matrix_element_type = matrix_element_type
        if matrix_type == "dense":
            self.data = DenseData( data )
        else:
            self.data = SparseData( data )
    
    def __str__(self):
        return str( self.__dict__ )

    def __repr__(self):
        return str( self.__dict__ )
        
Penom Nom's avatar
Penom Nom committed
321
    def observations_counts(self):
322
        """
Penom Nom's avatar
Penom Nom committed
323
324
        @summary : Return the list of the observations counts.
        @return : [list] the observation ID and the observation count for each observation.
325
326
327
328
329
330
                  Example :
                  [
                    ["OTU_1", 128],
                    ["OTU_2", 8]
                  ]
        """
Penom Nom's avatar
Penom Nom committed
331
332
        for observation_idx in range(len(self.rows)):
            yield self.rows[observation_idx]['id'], self.data.get_row_sum(observation_idx)
333
    
Penom Nom's avatar
Penom Nom committed
334
    def remove_observations( self, observations_names ):
Penom Nom's avatar
Penom Nom committed
335
        """
Penom Nom's avatar
Penom Nom committed
336
337
        @summary : Removes the specified observations.
         @param observations_names : [list] The IDs of the observations to remove. 
Penom Nom's avatar
Penom Nom committed
338
        """
Penom Nom's avatar
Penom Nom committed
339
340
        for current_observation in observations_names :
            observation_idx = self.find_idx( self.rows, current_observation )
Penom Nom's avatar
Penom Nom committed
341
            # Remove OTU from the self.rows
Penom Nom's avatar
Penom Nom committed
342
            del self.rows[observation_idx]
Penom Nom's avatar
Penom Nom committed
343
            # Remove OTU from the self.data
Penom Nom's avatar
Penom Nom committed
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
            self.data.remove_row( observation_idx )
             
    def reset_count_by_replicates_evidence( self, samples_names, min_evidence_nb=2 ):
        """
        @summary : Puts to 0 the counts of an observation for all samples in a replicate if the 
                    number of samples with this observation is lower than 'min_evidence_nb' in 
                    the replicate.
                    example : with min_evidence_nb = 2 and 2 triplicates (A and B)
                       Before process
                             sample_A_1 sample_A_2 sample_A_3 sample_B_1 sample_B_2 sample_B_3
                         obs     1           1           0         0          0          2
                       After process
                             sample_A_1 sample_A_2 sample_A_3 sample_B_1 sample_B_2 sample_B_3
                         obs     1           1           0         0          0          0
        @param samples_names : [list] The names of the replicates.
        @param min_evidence_nb : [int] The minimun number of replicates with the observation.
        """
        samples_idx = [self.find_idx(self.columns, sample) for sample in samples_names]
        # For each observation
        for row_idx in range( len(self.rows) ):
            obs_evidence = 0
            # Process evidence number
            for col_idx in samples_idx:
                if self.data.nb_at(row_idx, col_idx) > 0: # if count > 0
                    obs_evidence += 1
            # If the evidence is insufficient
            if obs_evidence < min_evidence_nb and obs_evidence > 0:
                # for each sample
                for col_idx in samples_idx:
                    # Set observation count to 0                   
                    self.data.change( row_idx, col_idx, 0 )
Penom Nom's avatar
Penom Nom committed
375
376
377

    def filter_OTU_by_count( self, min_nb, max_nb=None ):
        """
Penom Nom's avatar
Penom Nom committed
378
379
380
        @summary : Filter observations on count value.
         @param min_nb : [int] The observations with a count inferior to 'min_nb' is removed.
         @param max_nb : [int] The observations with a count superior to 'min_nb' is removed.
Penom Nom's avatar
Penom Nom committed
381
        """
Penom Nom's avatar
Penom Nom committed
382
383
384
385
386
387
        removed_obs_names = list()
        for observation_idx in range( len(self.rows) ):
            observation_count = self.data.get_row_sum( observation_idx )
            if observation_count < min_nb or (max_nb is not None and observation_count > max_nb):
                removed_obs_names.append( self.rows[observation_idx]["id"] )
        self.remove_observations( removed_obs_names )
Penom Nom's avatar
Penom Nom committed
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

    def merge_samples( self, samples, merged_sample_id=None ):
        """
        @summary : Merge data and metadata of a list of samples.
         @param samples : [list] Samples to merge.
         @param merged_sample_id : [str] Name for the new meta-sample.
        """
        # Preprocess final_sample
        final_idx = self.find_idx(self.columns, samples[0])
        final_sample = self.columns[final_idx]
        if final_sample['metadata'] is not None:
            metadata_names = final_sample['metadata'].keys()
            for metadata_name in metadata_names:
                final_sample['metadata'][final_sample['id'] + ":" + metadata_name] = final_sample['metadata'][metadata_name]
                del final_sample['metadata'][metadata_name]
        else:
            final_sample['metadata'] = dict()
        # Merge
        for current_name in samples[1:]:
            final_idx = self.find_idx(self.columns, samples[0])
            # Find sample
            current_idx = self.find_idx(self.columns, current_name)
            current_sample = self.columns[current_idx]
            # Update metadata history
            if final_sample['metadata'].has_key( "merge_history" ):
                final_sample['metadata']['merge_history'] += " AND " + current_sample['id']
            else:
                final_sample['metadata']['merge_history'] = final_sample['id'] + " AND " + current_sample['id']
            # Merge metadata
            if current_sample['metadata'] is not None:
                for metadata_name in current_sample['metadata']:
                    final_sample['metadata'][current_sample['id'] + ":" + metadata_name] = current_sample['metadata'][metadata_name]
            # Merge data
            self.data.merge_col( final_idx, current_idx )
            # Remove sample from the self.columns
            del self.columns[current_idx]
        # If rename final sample
        if merged_sample_id is not None:
            final_sample['id'] = merged_sample_id
    
    def find_idx( self, subject, query_name ):
        """
        @summary : Returns the index of the query.
         @param subject : [list] The Biom.rows or Biom.columns where query is seach.
         @param query_name : [str] The id of the element (ex : "OTU_0012").
        @return : [int] The index of the element.
        @todo : Change 'subject' by 'subject_type'.
        """
        find_idx = None
        idx = 0
        while idx < len(subject) and find_idx is None:
            if subject[idx]['id'] == query_name:
                find_idx = idx
            idx += 1
        if find_idx is None:
            raise ValueError( "'" + query_name + "' doesn't exist." )
        return find_idx
        
    def _count_by_OTU( self ):
        """
        @summary : Count the number of elements by OTU.
        @return : [list, int] the number of elements by OTU and the total number of elements.
              Example for the number of elements by OTU :
              [
                { 'id' : 'OTU_1', 'nb' : 10 },
                { 'id' : 'OTU_8', 'nb' : 0  }
              ]
        """
        nb_total_elt = 0
        OTU_count = list()
Penom Nom's avatar
Penom Nom committed
458
        for row_idx in range( len(self.rows) ):
Penom Nom's avatar
Penom Nom committed
459
            OTU_count.append( { "id" : self.rows[row_idx]["id"],
Penom Nom's avatar
Penom Nom committed
460
                                "nb" : self.get_row_sum( row_idx ) } )
Penom Nom's avatar
Penom Nom committed
461
462
463
464
465
            nb_total_elt += nb_elt_for_OTU
        return OTU_count, nb_total_elt

    def add_metadata( self, subject_name, metadata_name, metadata_value, subject_type="sample"):
        """
466
467
        @summary : Add a metadata on subject (a sample or an observation).
         @param subject_name : [str] Metadata is added to the sample/observation with this name. 
Penom Nom's avatar
Penom Nom committed
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
         @param metadata_name : [str] The metadata category (ex : 'taxonomy').
         @param metadata_name : [str] The value of metadata (ex : 'Bacteria').
         @param subject_type : [str] The type of subject : "sample" or "observation".
        """
        # Select subject container
        if subject_type == "sample":
            subject_list = self.columns
        elif subject_type == "observation":
            subject_list = self.rows
        else:
            raise ValueError( "'" + subject_type + "' is an invalid subject type for metadata. Metadata must be add to 'observation' or 'sample'." )
        # Find subject
        try:
            subject_idx = self.find_idx( subject_list, subject_name )
        # Subject does not exist
        except ValueError:
            sys.stderr.write("[WARNING] The metadata named '" + metadata_name + "' can't be added to sample '" + subject_name + "' because it does not exist.\n")
        # Subject exists
        else:
            if subject_list[subject_idx]['metadata'] is None:
                subject_list[subject_idx]['metadata'] = dict()
            elif subject_list[subject_idx]['metadata'].has_key( metadata_name ):
                sys.stderr.write("[WARNING] You erase previous value of the metadata named '" + metadata_name + "' in " + subject_name + " (OLD:'" + str(subject_list[subject_idx]['metadata'][metadata_name]) + "' => NEW:'" + str(metadata_value) + "').\n")
            subject_list[subject_idx]['metadata'][metadata_name] = metadata_value

    def to_JSON( self ):
        """
        @summary : Return a json format for the data store in the Biom object.
        @return : [str] The json.
        """
        self.shape = [
                       len(self.rows),
                       len(self.columns)
        ]
        self.matrix_type = self.data.get_matrix_type()
503
504
        save_data = self.data
        self.data = save_data._to_list()
Penom Nom's avatar
Penom Nom committed
505
        json_str = json.dumps( self, default=lambda o: o.__dict__, sort_keys=False, indent=4 )
506
        self.data = save_data
Penom Nom's avatar
Penom Nom committed
507
508
509
510
511
512
        del self.shape
        del self.matrix_type
        return json_str
    
    def remove_samples( self, samples_names ):
        """
513
514
        @summary : Removes sample(s) from biom.
         @param samples_names : [str] The name of the sample to rename.
Penom Nom's avatar
Penom Nom committed
515
516
517
518
519
520
521
        """
        for current_sample in samples_names :
            sample_idx = self.find_idx( self.columns, current_sample )
            # Remove sample from the self.columns
            del self.columns[sample_idx]
            # Remove sample from the self.data
            self.data.remove_col( sample_idx )
522
523
    
    def add_count( self, observation_name, sample_name, value ):
524
525
526
527
528
529
        """
        @summary : Add a value to the count for one observation of one sample.
         @param observation_name : [str] The observation name.
         @param sample_name : [str] The sample name.
         @param value : [int] The value to add.
        """
530
531
532
533
534
        row_idx = self.find_idx( self.rows, observation_name )
        col_idx = self.find_idx( self.columns, sample_name )
        self.data.add( row_idx, col_idx, value )
        
    def add_observation( self, observation_name, metadata=dict() ):
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
        """
        @summary : Add one observation in biom.
         @param observation_name : [str] The observation name.
         @param metadata : [dict] The metadata (keys : metadata names ; values : metadata values).
        """
        try:
            self.find_idx( self.rows, observation_name )
        # Observation doesn't exist
        except ValueError:
            self.rows.append( {'id':observation_name, 'metadata':None } )
            self.data.add_row()
            for metadata_name in metadata.keys():
                self.add_metadata( observation_name, metadata_name, metadata[metadata_name], "observation" )
        # Observation already exists
        else:
            raise ValueError( "The observation '" + observation_name + "' already exists." )
551
552
            
    def add_sample( self, sample_name, metadata=dict() ):
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
        """
        @summary : Add one sample in biom.
         @param sample_name : [str] The sample name.
         @param metadata : [dict] The metadata (keys : metadata names ; values : metadata values).
        """
        try:
            self.find_idx( self.columns, sample_name )
        # Sample doesn't exist
        except ValueError:
            self.columns.append( {'id':sample_name, 'metadata':None } )
            self.data.add_column()
            for metadata_name in metadata.keys():
                self.add_metadata( sample_name, metadata_name, metadata[metadata_name], "sample" )
        # Sample already exists
        else:
            raise ValueError( "The sample '" + sample_name + "' already exists." )

    def get_samples_names( self ):
        """
        @summary : Returns a generator to iterate on samples names.
        @return : [generator] the generator to iterate on samples names.
        """
        for col in self.columns:
            yield col["id"]
Penom Nom's avatar
Penom Nom committed
577
578
579
580
581
582
583
584
    
    def get_observations_names( self ):
        """
        @summary : Returns a generator to iterate on observations names.
        @return : [generator] the generator to iterate on observations names.
        """
        for col in self.rows:
            yield col["id"]
Penom Nom's avatar
Penom Nom committed
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607

    def _hash_OTU_by_sample( self ):
        """
        @summary : Count the number of elements by OTU.
        @return : [list, int] the number of elements by OTU and the total number of elements.
              Example for the number of elements by OTU :
              [
                { 'id' : 'OTU_1', 'nb' : 10 },
                { 'id' : 'OTU_8', 'nb' : 0  }
              ]
        """
        nb_OTU_by_sample = { col['id']:list() for col in self.columns }
        sum_by_sample = { col['id']:0 for col in self.columns }
        for row_idx in range(len(self.rows)):
            for columns_idx in range(len(self.columns)):
                nb = self.data.nb_at( row_idx, columns_idx )
                sample_id = self.columns[columns_idx]['id']
                sum_by_sample[sample_id] += nb
                nb_OTU_by_sample[sample_id].append( { "id" : self.rows[row_idx]["id"],
                                                      "nb" : nb } )
        return nb_OTU_by_sample, sum_by_sample

    def bootstrap_by_sample( self, nb_selected_elts, nb_removed_elts, nb_selection_round=1000 ):
608
609
        """
        """
Penom Nom's avatar
Penom Nom committed
610
611
        nb_OTU_by_sample, sum_by_sample = self._hash_OTU_by_sample()
        self.data.clear()
Penom Nom's avatar
Penom Nom committed
612
613
614
615
616
        if self.generated_by is None:
            self.generated_by = ""
        else:
            self.generated_by += ' | '
        self.generated_by += "sampling[delete : " + str(nb_removed_elts) + "; select : " + str(nb_selected_elts) + "; round : " + str(nb_selection_round) + "]" 
Penom Nom's avatar
Penom Nom committed
617
618
619
620
621
622
623
624
625
626
627
628
        for i in range(nb_selection_round):
            for current_sample in self.columns:
                sample_id = current_sample['id']
                # Random remove
                remaining_OTU_count, nb_elts = _bootstrap_remove_elts( nb_OTU_by_sample[sample_id], sum_by_sample[sample_id], nb_removed_elts )
                # Random selection 
                selected = _bootstrap_selection( remaining_OTU_count, nb_elts, nb_selected_elts )
                # Add to new_data
                for OTU_id in selected.keys():
                    OTU_idx = self.find_idx( self.rows, OTU_id )
                    sample_idx = self.find_idx( self.columns, current_sample['id'] )
                    self.data.add( OTU_idx, sample_idx, selected[OTU_id] )
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

    def to_count( self ):
        """
        @summary : Returns the count of observations by sample.
        @return : [generator] The generator to iterate on observations. Each observation is a list of count 
                  by sample.
                  Example : [1, 0] # Iteration 1 : sample_1 has one observation_1, sample_2 has zero observation_1
                            [1, 8] # Iteration 2 : sample_1 has one observation_2, sample_2 has eight observation_2
        """
        nb_rows = len(self.rows)
        nb_columns = len(self.columns)
        for row_idx in range(nb_rows):
            yield self.data.row_to_array( row_idx, nb_columns )

    def to_count_table( self ):
        """
        @summary : Returns the count of observations by sample with titles.
        @return : [generator] The generator to iterate on observations. First line is a title.
                  Example : ['#Observation', 'Sample1', 'Sample2'] # Iteration 1 : title
                            ['GG_OTU_1', 1, 0] # Iteration 2 : Sample1 has one GG_OTU_1, Sample1 has zero GG_OTU_1
                            ['GG_OTU_2', 1, 8] # Iteration 3 : Sample2 has one GG_OTU_2, Sample2 has eight GG_OTU_2
        """
        # Return Title
        yield ["#Observation"] + [col['id'] for col in self.columns]
        # Return lines
        row_idx = 0
        for row in self.to_count():
            OTU_name = self.rows[row_idx]['id']
            row_idx += 1
            yield [OTU_name] + row
Penom Nom's avatar
Penom Nom committed
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


class BiomIO:
    """
    Reader/Writer for the Biom format.
    The BIOM file format is a json format designed to be a general-use format for representing biological sample by observation contingency tables.
    BIOM is a recognized standard for the Earth Microbiome Project and is a Genomics Standards Consortium candidate project.
    @see : https://github.com/biom-format
    """ 
    @staticmethod
    def from_count_table( count_file, generated_by=None ):
        """
        @summary : Return an object 'Biom' from a count table.
         @param count_file : [str] The path of the count file.
                             Format :
                              #Cluster_ID<TAB>sample1<TAB>sample2
                              OTU1<TAB>8<TAB>10
                              ...
         @param generated_by : [str] The method/software used to generate data.
        @return [Biom] The Biom object.
        """
        biom = Biom()
        biom.data = SparseData()
        biom.generated_by = generated_by
        
        count_fh = open( count_file )
        row_idx = 0
        for line in count_fh:
            line = line.strip()
            line_fields = line.split()
            # Title line
            if line.startswith('#'):
                for sample in line_fields[1:]:
                    # Load sample (biom.columns)
                    biom.columns.append( { 
                                     'id':sample,
                                     'metadata':None
                    })
            # OTU line
            else:
                # Load OTU (biom.rows)
                biom.rows.append( {
                                    'id':line_fields[0],
                                    'metadata':None
                })
                # Load count (biom.data)
                col_idx = 0
                for count in line_fields[1:]:
                    if int(count) != 0:
Penom Nom's avatar
Penom Nom committed
708
                        biom.data.add( row_idx, col_idx, int(count) )
Penom Nom's avatar
Penom Nom committed
709
710
711
712
713
714
715
                    col_idx += 1
                row_idx += 1
        count_fh.close()
              
        return biom
    
    @staticmethod
716
    def from_json( path ):
Penom Nom's avatar
Penom Nom committed
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
        """
        @summary : Return an object 'Biom' from a biom file.
         @param path : [str] The path of the biom file.
        @return [Biom] The Biom object.
        """
        json_data = open( path )
        python_dict = json.load( json_data )
        json_data.close()
        
        return Biom( python_dict["id"], 
                     python_dict["format"], 
                     python_dict["format_url"],
                     python_dict["type"], 
                     python_dict["generated_by"],
                     python_dict["date"],
                     python_dict["rows"],
                     python_dict["columns"],
                     python_dict["matrix_type"],
                     python_dict["matrix_element_type"],
                     python_dict["data"] )

    @staticmethod
    def write( path, biom ):
        """
        @summary : Write a biom file from a 'Biom'.
         @param path : [str] The path of the biom file.
         @param biom : [Biom] The Biom object to write.
        """
        out_fh = open( path, "w" )
        out_fh.write( biom.to_JSON() )
        out_fh.close()

    @staticmethod
    def write_count_table( path, biom ):
        """
        @summary : Write count table from an object 'Biom'.
         @param path : [str] The path of the biom file.
         @param biom : [Biom] The Biom object to write.
        """
        out_fh = open( path, "w" )
        for line in biom.to_count_table():
            out_fh.write( "\t".join(map(str, line)) + "\n" )
        out_fh.close()
Penom Nom's avatar
Penom Nom committed
760
761
762
763
764
765
766
767
    
    @staticmethod
    def write_krona_table( path, biom ):
        """
        @todo test
        """
        out_fh = open( path, "w" )
        for idx in range(len(biom.rows)):
768
            count = biom.data.get_row_sum( idx )
Penom Nom's avatar
Penom Nom committed
769
            tax = biom.rows[idx]["metadata"]["taxonomy"]
Penom Nom's avatar
Penom Nom committed
770
771
772
773
774
775
            if isinstance(tax, list) or isinstance(tax, tuple):
                tax = "\t".join( map(str, tax) )
            else:
                tax = str( tax )
            tax = "\t".join( map(str.strip, tax.split(";")) ) # Replace space separator between ranks by tabulation
            out_fh.write( str(count) + "\t" + tax + "\n" )
Penom Nom's avatar
Penom Nom committed
776
        out_fh.close()      
777
778
779
780
781
782
783
784
785
786
787
        
    @staticmethod
    def write_krona_table_by_sample( path, biom, sample ):
        """
        @todo test
        """
        out_fh = open( path, "w" )
        col_idx = biom.find_idx( biom.columns, sample )
        for row_idx in range(len(biom.rows)):
            count = biom.data.nb_at( row_idx, col_idx )
            if count > 0:
Penom Nom's avatar
Penom Nom committed
788
                tax = biom.rows[row_idx]["metadata"]["taxonomy"]
789
790
791
792
793
794
795
                if isinstance(tax, list) or isinstance(tax, tuple):
                    tax = "\t".join( map(str, tax) )
                else:
                    tax = str( tax )
                tax = "\t".join( map(str.strip, tax.split(";")) ) # Replace space separator between ranks by tabulation
                out_fh.write( str(count) + "\t" + tax + "\n" )
        out_fh.close()  
Penom Nom's avatar
Penom Nom committed
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

    @staticmethod
    def load_metadata( biom, metadata_file, subject_type="sample", types={}, list_sep={} ):
        """
        @summary : Add to biom several metadata from metadata file.
         @param biom : [Biom] The Biom object to update.
         @param metadata_file : [str] The path of the metadata file.
                                Format :
                                #TITLE<TAB>Metadata_1_name<TAB>Metadata_2_name
                                Subject_name<TAB>Metadata_1_value<TAB>Metadata_2_value
                                ...
         @param subject_type : [str] The type of subject : "sample" or "observation".
         @param types : [dict] Types for of the metadata values ("str", "int", "float").
                        Example :
                        { 
                          'confidence' : 'float',
                          'rank'       : 'int'
                        }
         @param list_sep : [dict] Separator if the metadata is a list.
                        Example :
                        {
                          'taxonomy'      : ';', # Bacteria;Proteobacteria
                          'environnement' : '/'  # Sea/Ocean
                        } 
        """
        metadata_fh = open( metadata_file )
        metadata = list()
        # Names and type of metadata
        title_line = metadata_fh.readline().strip()
        title_fields = title_line.split()
        for metadata_name in title_fields[1:]:
            metadata_type = "str"
            if types.has_key( metadata_name ):
                metadata_type = types[metadata_name]
            metadata_list_sep = None
            if list_sep.has_key( metadata_name ):
                metadata_list_sep = list_sep[metadata_name]
            metadata.append( {
                              'name'     : metadata_name,
                              'type'     : metadata_type,
                              'list_sep' : metadata_list_sep
            })
        # Values of metadata
        for line in metadata_fh:
            line = line.strip()
            if not line.startswith('#'):
                line_fields = line.split()
                metadata_subject = line_fields[0]
                title_idx = 0
                for metadata_value in line_fields[1:]:
                    # Manage cast metadata value
                    if metadata[title_idx]['type'] == "str":
                        cast = str
                    elif metadata[title_idx]['type'] == "int":
                        cast = int
                    elif metadata[title_idx]['type'] == "float":
                        cast = float
                    else:
                        raise ValueError( "'" + metadata[title_idx]['type'] + "' is an invalid type for metadata. Metadata must be 'str' or 'int' or 'float'." )
                    # Manage split
                    if metadata[title_idx]['list_sep'] is None:
                        metadata_value = cast( metadata_value )
                    else:
                        metadata_value = [cast(value) for value in metadata_value.split(metadata[title_idx]['list_sep'])]
                    # Add metadata
                    biom.add_metadata( metadata_subject, metadata[title_idx]['name'], metadata_value, subject_type)
                    # Next medata title
                    title_idx += 1