Debian Codegraph @

lefsebiom/AbundanceTable.py

raw symbols ◀ ▶ SCIP
2 Debian patches touch this file
1 """
2 Author: Timothy Tickle
3 Description: Class to abstract an abundance table and methods to run on such a table.
4 """
5
6 #####################################################################################
•7 # Copyright (C) <2012>
8 #
•9 # Permission is hereby granted, free of charge, to any person obtaining a copy of
10 # this software and associated documentation files (the "Software"), to deal in the
11 # Software without restriction, including without limitation the rights to use, copy,
12 # modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
13 # and to permit persons to whom the Software is furnished to do so, subject to
14 # the following conditions:
15 #
•16 # The above copyright notice and this permission notice shall be included in all copies
17 # or substantial portions of the Software.
18 #
•19 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
20 # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
21 # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
22 # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23 # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
24 # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25 #####################################################################################
26
27 __author__ = "Timothy Tickle"
28 __copyright__ = "Copyright 2012"
29 __credits__ = ["Timothy Tickle"]
30 __license__ = "MIT"
31 __maintainer__ = "Timothy Tickle"
32 __email__ = "[email protected]"
33 __status__ = "Development"
34
35 import csv
36 import sys
37 from .CClade import CClade
38 from .ConstantsBreadCrumbs import ConstantsBreadCrumbs
39 import copy
40 from datetime import date
41 import numpy as np
42 import os
43 import re
44 import scipy.stats
45 import string
46 from .ValidateData import ValidateData
47
48
49 #*************************************************************
50 #* import biom *
51 #* If not found - abnormally exit *
52 #*************************************************************
53 try:
54 from biom.parse import *
55 from biom.table import *
56 except ImportError:
57 sys.stderr.write("************************************************************************************************************ \n")
58 sys.stderr.write("* Error: biom environment required to process biom files - Not found - run abnormally terminated * \n")
59 sys.stderr.write("* See http://http://biom-format.org/ * \n")
60 sys.stderr.write("************************************************************************************************************ \n")
61 exit(1)
62
63 from biom.parse import *
64 from biom.table import *
65
66 c_dTarget = 1.0
67 c_fRound = False
68 c_iSumAllCladeLevels = -1
69 c_fOutputLeavesOnly = False
70
71 class RowMetadata:
72 """
73 Holds the row (feature) metadata and associated functions.
74 """
75
76 def __init__(self, dictRowMetadata, iLongestMetadataEntry=None, lsRowMetadataIDs=None):
77 """ Constructor requires a dictionary or row metadata.
78 :param dictRowMetadata: The row metadata values with the ids as the keys, must be stable (keep order)
79 :type: {string feature id: {'metadata': {'taxonomy': [list of metadata values]}}}
80 """
81
82 self.dictRowMetadata = dictRowMetadata
83 self.iLongestMetadataEntry = iLongestMetadataEntry
84 self.lsRowMetadataIDs = lsRowMetadataIDs
85
86 self.dictMetadataIDs = {}
87 # Get the ids for the metadata
88 if self.dictRowMetadata:
•89 for dictMetadata in list(self.dictRowMetadata.values()):
90 dictMetadata = dictMetadata.get(ConstantsBreadCrumbs.c_metadata_lowercase, None)
91
92 if dictMetadata:
•93 for key,value in list(dictMetadata.items()):
94 if self.dictMetadataIDs.get(key, None):
95 self.dictMetadataIDs[key] = max(self.dictMetadataIDs[key],len(dictMetadata[key]))
96 else:
97 self.dictMetadataIDs[key] = len(dictMetadata[key])
98
99 def funcMakeIDs(self):
100 """ There should be a one to one mapping of row metadata ids and the values associated here with a feature ID.
101 If not make ids from the key by appending numbers.
102 """
103
104 # If there exists a ids list already return (this allows ID order to be given and preserved)
105 # Else make a list of IDs
106 if self.lsRowMetadataIDs:
107 return self.lsRowMetadataIDs
108
109 lsIDs = []
110 lsKeys = []
111
•112 for key, value in list(self.dictMetadataIDs.items()):
113 lsKeys.append( key )
114 if value > 1:
115 lsIDs.extend( [ "_".join( [ key, str( iIndex ) ] ) for iIndex in range( value ) ] )
116 else:
117 lsIDs.append( key )
118 return [ lsIDs, lsKeys ]
119
120 def funGetFeatureMetadata(self, sFeature, sMetadata):
121 """
122 Returns a list of values in the order of row metadta ids for a microbial feature given an id.
123
124 :param sFeature: Feature id to get metadata
125 :type: string
126 :param sMetadata: Metadata to get
127 :type: string
128 :return: list of metadata associated with the metadata
129 """
130 lsMetadata = []
131 if self.dictRowMetadata:
132 dictFeature = self.dictRowMetadata.get( sFeature, None )
133 if dictFeature:
134 dictFeatureMetadata = dictFeature.get(ConstantsBreadCrumbs.c_metadata_lowercase, None)
135 if dictFeatureMetadata:
136 lsMetadata = dictFeatureMetadata.get(sMetadata, None)
137 return lsMetadata
138
139
140 class AbundanceTable:
141 """
142 Represents an abundance table and contains common function to perform on the object.
143
144 This class is made from an abundance data file. What is expected is a text file delimited by
145 a character (which is given to the object). The first column is expected to be the id column
146 for each of the rows. Metadata is expected before measurement data. Columns are samples and
147 rows are features (bugs).
148
149 This object is currently not hashable.
150 """
151
152 def __init__(self, npaAbundance, dictMetadata, strName, strLastMetadata, rwmtRowMetadata = None, dictFileMetadata = None, lOccurenceFilter = None, cFileDelimiter = ConstantsBreadCrumbs.c_cTab, cFeatureNameDelimiter = "|"):
153 """
154 Constructor for an abundance table.
155
156 :param npaAbundance: Structured Array of abundance data (Row=Features, Columns=Samples)
157 :type: Numpy Structured Array abundance data (Row=Features, Columns=Samples)
158 :param dictMetadata: Dictionary of metadata {"String ID":["strValue","strValue","strValue","strValue","strValue"]}
159 :type: Dictionary Dictionary
160 :param npaRowMetdata Structured Array of row (feature) metadata (optional)
161 :type: Numpy Structured Array abundance data (Row=Features, Columns=Feature metadata)
162 :param strName: The name of the metadata that serves as the ID for the columns (For example a sample ID)
163 :type: string
164 :param strLastMetadata: The string last metadata name
165 :type: string
166 :param lOccurenceFilter: List of integers used in an occurence filter. [Min abundance, Min sample]
167 :type: List of integers
168 :param cFileDelimiter: Character used as the delimiter of the file that is read in to create the abundance table.
169 Will also be used to write the abudance table file to a file to keep file consistency.
170 :type: Character delimiter for reading the data in (default = TAB)
171 :param cFeatureNameDelimiter: Character used as the delimiter of the feature names (column 1). This is useful if the name are complex, for instance consensus lineages in metagenomics.
172 :type: Character delimiter for feature names (default = |)
173 """
174
175 ### File Metadata
176
177 #Date
178 self.dateCreationDate = dictFileMetadata.get(ConstantsBreadCrumbs.c_strDateKey,None) if dictFileMetadata else None
179
180 #Indicates if the table has been filtered and how
181 self._strCurrentFilterState = ""
182
183 #The delimiter from the source file
184 self._cDelimiter = cFileDelimiter
185
186 #The feature name delimiter
187 self._cFeatureDelimiter = cFeatureNameDelimiter
188
189 #File type
190 self.strFileFormatType = dictFileMetadata.get(ConstantsBreadCrumbs.c_strFormatKey,None) if dictFileMetadata else None
191
192 #File generation source
193 self.strFileGenerationSource = dictFileMetadata.get(ConstantsBreadCrumbs.c_strSourceKey,None) if dictFileMetadata else None
194
195 #File type
196 self.strFileType = dictFileMetadata.get(ConstantsBreadCrumbs.c_strTypekey,None) if dictFileMetadata else None
197
198 #File url
199 self.strFileURL = dictFileMetadata.get(ConstantsBreadCrumbs.c_strURLKey,None) if dictFileMetadata else None
200
201 #The id of the file
202 self.strId = dictFileMetadata.get(ConstantsBreadCrumbs.c_strIDKey,None) if dictFileMetadata else None
203
204 #The lastmetadata name (which should be preserved when writing the file)
205 # Can be a None if biom file is read in.
206 self._strLastMetadataName = strLastMetadata
207
208 #The original number of features in the table
209 self._iOriginalFeatureCount = -1
210
211 #The name of the object relating to the file it was read from or would have been read from if it exists
212 #Keeps tract of changes to the file through the name
213 #Will be used to write out the object to a file as needed
214 self._strOriginalName = strName
215
216 #The original number of samples in the table
217 self._iOriginalSampleCount = -1
218
219 #Data sparsity type
220 self.fSparseMatrix = dictFileMetadata.get(ConstantsBreadCrumbs.c_strSparsityKey,False) if dictFileMetadata else False
221
222 ### Data metadata
223 #The column (sample) metdata
224 self._dictTableMetadata = dictMetadata
225
226 #The row (feature) metadata (Row Metadata object)
227 self.rwmtRowMetadata = rwmtRowMetadata
228
229 ### Data
230
231 #The abundance data
232 self._npaFeatureAbundance = npaAbundance
233
234
235 ### Logistical
236
237 #Clade prefixes for biological samples
238 self._lsCladePrefixes = ["k__","p__","c__","o__","f__","g__","s__"]
239
240 #This is not a hashable object
241 self.__hash__ = None
242
243
244 ### Prep the object
245
246 self._fIsNormalized = self._fIsSummed = None
247 #If contents is not a false then set contents to appropriate objects
248 # Checking to see if the data is normalized, summed and if we need to run a filter on it.
249 if len(self._npaFeatureAbundance) and self._dictTableMetadata:
250 self._iOriginalFeatureCount = self._npaFeatureAbundance.shape[0]
251 self._iOriginalSampleCount = len(self.funcGetSampleNames())
252
253 self._fIsNormalized = ( max( [max( list(a)[1:] or [0] ) for a in self._npaFeatureAbundance] or [0] ) <= 1 )
254
255 lsLeaves = AbundanceTable.funcGetTerminalNodesFromList( [a[0] for a in self._npaFeatureAbundance], self._cFeatureDelimiter )
256 self._fIsSummed = ( len( lsLeaves ) != len( self._npaFeatureAbundance ) )
257
258 #Occurence filtering
259 #Removes features that do not have a given level iLowestAbundance in a given amount of samples iLowestSampleOccurence
260 if ( not self._fIsNormalized ) and lOccurenceFilter:
261 iLowestAbundance, iLowestSampleOccurrence = lOccurenceFilter
262 self.funcFilterAbundanceBySequenceOccurence( iLowestAbundance, iLowestSampleOccurrence )
263 # else:
264 # sys.stderr.write( "Abundance or metadata was None, should be atleast an empty object\n" )
265
266 @staticmethod
267 def funcMakeFromFile(xInputFile, cDelimiter = ConstantsBreadCrumbs.c_cTab, sMetadataID = None, sLastMetadataRow = None, sLastMetadata = None,
268 lOccurenceFilter = None, cFeatureNameDelimiter="|", xOutputFile = None, strFormat = None):
269 """
270 Creates an abundance table from a table file.
271
272 :param xInputFile: Path to input file.
273 :type: String String path.
274 :param cDelimiter: Delimiter for parsing the input file.
275 :type: Character Character
276 :param sMetadataID: String ID that is a metadata row ID (found on the first column) and used as an ID for samples
277 :type: String String ID
278 :param sLastRowMetadata: The id of the last (most right column) row metadata
279 :type: String String ID
280 :param sLastMetadata: The ID of the metadata that is the last metadata before measurement or feature rows.
281 :type: String String ID
282 :param lOccurenceFilter: List of integers used in an occurence filter. [Min abundance, Min sample]
283 :type: List of integers
284 :param cFeatureNameDelimiter: Used to parse feature (bug) names if they are complex.
285 For example if they are consensus lineages and contain parent clade information.
286 :type: Character Delimiting letter
287 :param xOutputFile: File to output the abundance table which was read in.
288 :type: FileStream or String file path
289 :return AbundanceTable: Will return an AbundanceTable object on no error. Returns False on error.
290 """
291
292 #Get output file and remove if existing
293 outputFile = open( xOutputFile, "w" ) if isinstance(xOutputFile, str) else xOutputFile
294
295 #################################################################################
296 # Check if file is a biom file - if so invoke the biom routine #
297 #################################################################################
298 strFileName = xInputFile if isinstance(xInputFile, str) else xInputFile.name
299
300 # Determine the file read function by file extension
301 if strFileName.endswith(ConstantsBreadCrumbs.c_strBiomFile) or (strFormat == ConstantsBreadCrumbs.c_strBiomFile):
302 BiomCommonArea = AbundanceTable._funcBiomToStructuredArray(xInputFile)
303 if BiomCommonArea:
304 lContents = [BiomCommonArea[ConstantsBreadCrumbs.c_BiomTaxData],
305 BiomCommonArea[ConstantsBreadCrumbs.c_Metadata],
306 BiomCommonArea[ ConstantsBreadCrumbs.c_dRowsMetadata],
307 BiomCommonArea[ConstantsBreadCrumbs.c_BiomFileInfo]
308 ]
309
310 # Update last metadata and id if given
311 if not sLastMetadata:
312 strLastMetadata = BiomCommonArea[ConstantsBreadCrumbs.c_sLastMetadata]
313 else:
314 # return false on failure
315 lContents = False
316 elif( strFileName.endswith(ConstantsBreadCrumbs.c_strPCLFile) or (strFormat == ConstantsBreadCrumbs.c_strPCLFile) ):
317 #Read in from text file to create the abundance and metadata structures
318 lContents = AbundanceTable._funcTextToStructuredArray(xInputFile=xInputFile, cDelimiter=cDelimiter,
319 sMetadataID = sMetadataID, sLastMetadataRow = sLastMetadataRow, sLastMetadata = sLastMetadata, ostmOutputFile = outputFile)
320 else:
321 print("I do not understand the format to read and write the data as, please use the correct file extension or indicate a type.")
322 return( false )
323
324 #If contents is not a false then set contents to appropriate objects
325 return AbundanceTable(npaAbundance=lContents[0], dictMetadata=lContents[1], strName=str(xInputFile), strLastMetadata=sLastMetadata, rwmtRowMetadata = lContents[2],
326 dictFileMetadata = lContents[3], lOccurenceFilter = lOccurenceFilter, cFileDelimiter=cDelimiter, cFeatureNameDelimiter=cFeatureNameDelimiter) if lContents else False
327
328 #Testing Status: Light happy path testing
329 @staticmethod
330 def funcCheckRawDataFile(strReadDataFileName, iFirstDataIndex = -1, sLastMetadataName = None, lOccurenceFilter = None, strOutputFileName = "", cDelimiter = ConstantsBreadCrumbs.c_cTab):
331 """
332 Check the input abundance table.
333 Currently reduces the features that have no occurence.
334 Also inserts a NA for blank metadata and a 0 for blank abundance data.
335 Gives the option to filter features through an occurence filter (a feature must have a level of abundance in a minimal number of samples to be included).
336 Either iFirstDataIndex or sLastMetadataName must be given
337
338 :param strReadDataFileName: File path of file to read and check.
339 :type: String File path.
340 :param iFirstDataIndex: First (row) index of data not metadata in the abundance file.
341 :type: Integer Index starting at 0.
342 :param sLastMetadataName: The ID of the last metadata in the file. Rows of measurements should follow this metadata.
343 :type: String
344 :param lOccurenceFilter: The lowest number of occurences in the lowest number of samples needed for a feature to be kept
345 :type: List[2] List length 2 [lowest abundance (not normalized), lowest number of samples to occur in] (eg. [2.0,2.0])
346 :param strOutputFileName: File path of out put file.
347 :type: String File path.
348 :param cDelimiter: Character delimiter for reading and writing files.
349 :type: Character Delimiter.
350 :return Output Path: Output path for written checked file.
351 """
352
353 #Validate parameters
354 if (iFirstDataIndex == -1) and (sLastMetadataName == None):
355 print("AbundanceTable:checkRawDataFile::Error, either iFirstDataIndex or sLastMetadataNamemust be given.")
356 return False
357
358 #Get output file and remove if existing
359 outputFile = strOutputFileName
360 if not strOutputFileName:
361 outputFile = os.path.splitext(strReadDataFileName)[0]+ConstantsBreadCrumbs.OUTPUT_SUFFIX
362
363 #Read input file lines
364 #Drop blank lines
365 readData = ""
366 with open(strReadDataFileName,'rU') as f:
367 readData = f.read()
•368 readData = list([_f for _f in readData.split(ConstantsBreadCrumbs.c_strEndline) if _f])
369
370 #Read the length of each line and make sure there is no jagged data
371 #Also hold row count for the metadata
372 iLongestLength = len(readData[0].split(cDelimiter))
373 iMetadataRow = -1
374 if not sLastMetadataName:
375 sLastMetadataName = "None"
376 for iIndex, strLine in enumerate(readData):
377 sLineElements = strLine.split(cDelimiter)
378 if sLineElements[0] == sLastMetadataName:
379 iMetadataRow = iIndex
380 iLongestLength = max(iLongestLength, len(sLineElements))
381
382 #If not already set, set iFirstDataIndex
383 if iFirstDataIndex < 0:
384 iFirstDataIndex = iMetadataRow + 1
385
386 #Used to substitute . to -
•387 reSubPeriod = re.compile(r'\.')
388
389 #File writer
390 with open(outputFile,'w') as f:
391
392 #Write metadata
393 #Empty data is changed to a default
394 #Jagged ends are filled with a default
395 for strDataLine in readData[:iFirstDataIndex]:
396 lsLineElements = strDataLine.split(cDelimiter)
397 for iindex, sElement in enumerate(lsLineElements):
398 if not sElement.strip():
399 lsLineElements[iindex] = ConstantsBreadCrumbs.c_strEmptyDataMetadata
400 if len(lsLineElements) < iLongestLength:
401 lsLineElements = lsLineElements + ([ConstantsBreadCrumbs.c_strEmptyDataMetadata]*(iLongestLength-len(lsLineElements)))
402 f.write(cDelimiter.join(lsLineElements)+ConstantsBreadCrumbs.c_strEndline)
403
404 #For each data line in the table
405 for line in readData[iFirstDataIndex:]:
406 writeToFile = False
407 cleanLine = list()
408 #Break line into delimited elements
409 lineElements = line.split(cDelimiter)
410
411 #Clean feature name
412 sCleanFeatureName = reSubPeriod.sub("-",lineElements[0])
413
414 #For each element but the first (taxa name)
415 #Element check to see if not == zero
416 #If so add to output
417 for element in lineElements[1:]:
418 if(element.strip() in string.whitespace):
419 cleanLine.append(ConstantsBreadCrumbs.c_strEmptyAbundanceData)
420 #Set abundance of 0 but do not indicate the line should be saved
421 elif(element == "0"):
422 cleanLine.append(element)
423 #If an abundance is found set the line to be saved.
424 else:
425 cleanLine.append(element)
426 writeToFile = True
427
428 #Occurence filtering
429 #Removes features that do not have a given level iLowestAbundance in a given amount of samples iLowestSampleOccurence
430 if lOccurenceFilter:
431 iLowestAbundance, iLowestSampleOccurence = lOccurenceFilter
432 if iLowestSampleOccurence > sum([1 if float(sEntry) >= iLowestAbundance else 0 for sEntry in cleanLine]):
433 writeToFile = False
434
435 #Write to file
436 if writeToFile:
437 f.write(sCleanFeatureName+cDelimiter+cDelimiter.join(cleanLine)+ConstantsBreadCrumbs.c_strEndline)
438 return outputFile
439
440 def __repr__(self):
441 """
442 Represent or print object.
443 """
444 return "AbundanceTable"
445
446 def __str__(self):
447 """
448 Create a string representation of the Abundance Table.
449 """
450
451 return "".join(["Sample count:", str(len(self._npaFeatureAbundance.dtype.names[1:])),
452 os.linesep+"Feature count:", str(len(self._npaFeatureAbundance[self._npaFeatureAbundance.dtype.names[0]])),
453 os.linesep+"Id Metadata:", self._npaFeatureAbundance.dtype.names[0],
454 os.linesep+"Metadata ids:", str(list(self._dictTableMetadata.keys())),
455 os.linesep+"Metadata count:", str(len(list(self._dictTableMetadata.keys()))),
456 os.linesep+"Originating source:",self._strOriginalName,
457 os.linesep+"Original feature count:", str(self._iOriginalFeatureCount),
458 os.linesep+"Original sample count:", str(self._iOriginalSampleCount),
459 os.linesep+"Is normalized:", str(self._fIsNormalized),
460 os.linesep+"Is summed:", str(self._fIsSummed),
461 os.linesep+"Current filtering state:", str(self._strCurrentFilterState),
462 os.linesep+"Feature delimiter:", self._cFeatureDelimiter,
463 os.linesep+"File delimiter:",self._cDelimiter])
464
465 def __eq__(self, objOther):
466 """
467 Check if an object is equivalent in data to this object
468 Check to make sure that objOther is not None
469 Check to make sure objOther is the correct class type
470 Check to make sure self and other internal data are the same (exclusing file name)
471 Check data and make sure the npa arrays are the same
472 Check the metdata to make sure the dicts are the same
473 (will need to sort the keys of the dicts before comparing, they do not guarentee any order.
474 """
475 # Check for none
476 if objOther is None:
477 return False
478
479 #Check for object type
480 if isinstance(objOther,AbundanceTable) != True:
481 return False
482
483 #Check feature delimiter
484 if self.funcGetFeatureDelimiter() != objOther.funcGetFeatureDelimiter():
485 return False
486
487 #Check file delimiter
488 if self.funcGetFileDelimiter() != objOther.funcGetFileDelimiter():
489 return False
490
491
492
493
494 #**************************************************
495 #* Commented out *
496 #**************************************************
497 #Check name - Commented out by GW on 2013/09/14 because
498 #If we import pcl file into biom file and then export to pcl, the file names might be different but the tables might be the same
499 #Check name
500 #if self.funcGetName() != objOther.funcGetName():
501 #return False
502
503
504 #Check sample metadata
505 #Go through the metadata
506 result1 = self.funcGetMetadataCopy()
507 result2 = objOther.funcGetMetadataCopy()
508 if sorted(result1.keys()) != sorted(result2.keys()):
509 return False
•510 for strKey in list(result1.keys()):
511 if strKey not in result2:
512 return False
513 if result1[strKey] != result2[strKey]:
514 return False
515
516 #TODO check the row (feature) metadata
517
518 #TODO check the file metadata
519 #Check the ID
520 if self.funcGetFileDelimiter() != objOther.funcGetFileDelimiter():
521 return False
522
523 #Check the date
524 if self.dateCreationDate != objOther.dateCreationDate:
525 return False
526
527 #Check the format
528 if self.strFileFormatType != objOther.strFileFormatType:
529 return False
530
531
532
533 #**************************************************
534 #* Commented out *
535 #**************************************************
536 #Check source - Commented out by GW on 2013/09/14 because
537 #If we import pcl file into biom file and then export to pcl, the file names might be different but the tables might be the same
538 #Check the source
539 #if self.strFileGenerationSource != objOther.strFileGenerationSource:
540 #return False
541
542 #Check the type
543 if self.strFileType != objOther.strFileType:
544 return False
545
546 #Check the URL
547 if self.strFileURL != objOther.strFileURL:
548 return False
549
550 #Check data
551 #TODO go through the data
552 #TODO also check the data type
553 result1 = self.funcGetAbundanceCopy()
554 result2 = objOther.funcGetAbundanceCopy()
555 if len(result1) != len(result2):
556 return False
557
558 sorted_result1 = sorted(result1, key=lambda tup: tup[0])
559 sorted_result2 = sorted(result2, key=lambda tup: tup[0])
560
561 if sorted_result1 != sorted_result2 :
562 return False
563
564
565 #**************************************************
566 #* Commented out *
567 #**************************************************
568 #Check AbundanceTable.__str__(self) - Commented out by GW on 2013/09/14 because
569 #If we import pcl file into biom file and then export to pcl, the file names might be different but the tables might be the same
570
571 #Check string representation
572 #if AbundanceTable.__str__(self) != AbundanceTable.__str__(objOther):
573 #return False
574
575 #Check if sample ids are the same and in the same order
576 if self.funcGetSampleNames() != objOther.funcGetSampleNames():
577 return False
578
579 return True
580
581
582 def __ne__(self, objOther):
583 return not self == objOther
584
585
586 #Testing Status: Light happy path testing
587 #TODO: Tim change static to class methods
588 @staticmethod
589 def _funcTextToStructuredArray(xInputFile = None, cDelimiter = ConstantsBreadCrumbs.c_cTab, sMetadataID = None, sLastMetadataRow = None, sLastMetadata = None, ostmOutputFile = None):
590
591 """
592 Private method
593 Used to read in a file that is samples (column) and taxa (rows) into a structured array.
594
595 :param xInputFile: File stream or path to input file.
596 :type: String File stream or string path.
597 :param cDelimiter: Delimiter for parsing the input file.
598 :type: Character Character.
599 :param sMetadataID: String ID that is a metadata row ID (found on the first column) and used as an ID for samples.
600 If not given it is assumed to be position 0
601 :type: String String ID
602 :param sLastMetadataRow: String ID that is the last row metadat id (id of the most right column with row/feature metadata)
603 :type: String String ID
604 :param sLastMetadata: The ID of the metadata that is the last metadata before measurement or feature rows.
605 :type: String String ID
606 :param ostmOutputFile: Output File to write to if needed. None does not write the file.
607 :type: FileStream or String
608 :return [taxData,metadata,rowmetadata]: Numpy Structured Array of abundance data and dictionary of metadata.
609 Metadata is a dictionary as such {"ID", [value,value,values...]}
610 Values are in the order thety are read in (and the order of the sample names).
611 ID is the first column in each metadata row.
612 - rowmetadata is a optional Numpy strucured array (can be None if not made)
613 + rowmetadata is a optional RowMetadata object (can be None if not made)
614 The rowmetadata and taxData row Ids should match
615 - [Numpy structured Array, Dictionary, Numpy structured array]
616 + The last dict is a collection of BIOM fielparameters when converting from a BIOM file
617 + [Numpy structured Array, Dictionary, Numpy structured array, dict]
618 """
619
620 # Open file from a stream or file path
621 istmInput = open( xInputFile, 'rU' ) if isinstance(xInputFile, str) else xInputFile
622 # Flag that when incremented will switch from metadata parsing to data parsing
623 iFirstDataRow = -1
624 # Sample id row
625 namesRow = None
626 # Row metadata names
627 lsRowMetadataIDs = None
628 # Index of the last row metadata
629 iIndexLastMetadataRow = None
630 # Holds metadata {ID:[list of values]}
631 metadata = dict()
632 # Holds the data measurements [(tuple fo values)]
633 dataMatrix = []
634 # Holds row metadata { sID : [ list of values ] }
635 dictRowMetadata = {}
636 # Positional index
637 iIndex = -1
638 # File handle
639 csvw = None
640
641 # Read in files
642 if ostmOutputFile:
643 csvw = csv.writer( open(ostmOutputFile,'w') if isinstance(ostmOutputFile, str) else ostmOutputFile, csv.excel_tab, delimiter = cDelimiter )
644 # For each line in the file, and assume the tax id is the first element and the data follows
645 for lsLineElements in csv.reader( istmInput, dialect = csv.excel_tab, delimiter = cDelimiter ):
646 iIndex += 1
647 taxId, sampleReads = lsLineElements[0], lsLineElements[1:]
648
649 # Read through data measurements
650 # Process them as a list of tuples (needed for structured array)
651 if iFirstDataRow > 0:
652 try:
653 # Parse the sample reads, removing row metadata and storing row metadata if it exists
654 if lsRowMetadataIDs:
655 # Build expected dict for row metadata dictionary {string feature id: {'metadata': {metadatakey: [list of metadata values]}}}
656 dictFeature = dict([ [sID, [sKey]] for sID, sKey in zip( lsRowMetadataIDs, sampleReads[ 0 : iIndexLastMetadataRow ]) ])
657 if len( dictFeature ):
658 dictRowMetadata[ taxId ] = { ConstantsBreadCrumbs.c_metadata_lowercase: dictFeature }
659 dataMatrix.append(tuple([taxId] + [( float(s) if s.strip( ) else 0 ) for s in sampleReads[ iIndexLastMetadataRow: ]]))
660 else:
661 dataMatrix.append(tuple([taxId] + [( float(s) if s.strip( ) else 0 ) for s in sampleReads]))
662 except ValueError:
663 sys.stderr.write( "AbundanceTable:textToStructuredArray::Error, non-numerical value on data row. File:" + str(xInputFile) +
664 " Row:" + str(lsLineElements) + "\n" )
665 return False
666 # Go through study measurements
667 else:
668 # Read in metadata values, if the entry is blank then give it the default empty metadata value.
669 for i, s in enumerate( sampleReads ):
670 if not s.strip( ):
671 sampleReads[i] = ConstantsBreadCrumbs.c_strEmptyDataMetadata
672
673 # If no id metadata (sample ids) is given then the first row is assumed to be the id row, otherwise look for the id for the metadata.
674 # Add the metadata to the containing dict
675 if ( ( not sMetadataID ) and ( iIndex == 0 ) ) or ( taxId == sMetadataID ):
676 namesRow = lsLineElements
677 # Remove the row metadata ids, these names are for the column ID and the samples ids
678 if sLastMetadataRow:
679 iIndexLastMetadataRow = lsLineElements.index(sLastMetadataRow)
680 lsRowMetadataIDs = namesRow[ 1 : iIndexLastMetadataRow + 1 ]
681 namesRow = [ namesRow[ 0 ] ] + namesRow[ iIndexLastMetadataRow + 1: ]
682
683 # If the sample metadata dictionary already has entries then remove the row metadata info from it.
684 if len( metadata ) and len( lsRowMetadataIDs ):
•685 for sKey, lsValues in list(metadata.items()):
686 metadata[ sKey ] = lsValues[ iIndexLastMetadataRow: ]
687
688 # Set the metadata without row metadata entries
689 metadata[taxId] = sampleReads[ iIndexLastMetadataRow: ] if (lsRowMetadataIDs and len( lsRowMetadataIDs )) else sampleReads
690
691 # If the last metadata was just processed switch to data processing
692 # If the last metadata name is not given it is assumed that there is only one metadata
693 if ( not sLastMetadata ) or ( taxId == sLastMetadata ):
694 iFirstDataRow = iIndex + 1
695
696 # If writing out the data write back out the line read in.
697 # This happens at the end so that the above cleaning is captured and written.
698 if csvw:
699 csvw.writerow( [taxId] + sampleReads )
700
701 if sLastMetadata and ( not dataMatrix ):
702 sys.stderr.write( "AbundanceTable:textToStructuredArray::Error, did not find the row for the last metadata ID. File:" + str(xInputFile) +
703 " Identifier:" + sLastMetadata + "\n" )
704 return False
705
706 # Make sure the names are found
707 if namesRow == None:
708 sys.stderr.write( "AbundanceTable:textToStructuredArray::Error, did not find the row for the unique sample/column. File:" + str(xInputFile) +
709 " Identifier:" + sMetadataID + "\n" )
710 return False
711
712 # Now we know the longest taxId we can define the first column holding the tax id
713 # Gross requirement of Numpy structured arrays, a = ASCII followed by max # of characters (as a string)
714 longestTaxId = max( len(a[0]) for a in dataMatrix )
715 dataTypeVector = [(namesRow[0],'a' + str(longestTaxId*2))] + [(s, "f4") for s in namesRow[1:]]
716 # Create structured array
717 taxData = np.array(dataMatrix,dtype=np.dtype(dataTypeVector))
718
719 # Returns a none currently because the PCL file specification this originally worked on did not have feature metadata
720 # Can be updated in the future.
721 # [Data (structured array), column metadata (dict), row metadata (structured array), file metadata (dict)]
722 return [taxData, metadata, RowMetadata(dictRowMetadata = dictRowMetadata, lsRowMetadataIDs = lsRowMetadataIDs), {
723 ConstantsBreadCrumbs.c_strIDKey:ConstantsBreadCrumbs.c_strDefaultPCLID,
724 ConstantsBreadCrumbs.c_strDateKey:str(date.today()),
725 ConstantsBreadCrumbs.c_strFormatKey:ConstantsBreadCrumbs.c_strDefaultPCLFileFormateType,
726 ConstantsBreadCrumbs.c_strSourceKey:ConstantsBreadCrumbs.c_strDefaultPCLGenerationSource,
727 ConstantsBreadCrumbs.c_strTypekey:ConstantsBreadCrumbs.c_strDefaultPCLFileTpe,
728 ConstantsBreadCrumbs.c_strURLKey:ConstantsBreadCrumbs.c_strDefaultPCLURL,
729 ConstantsBreadCrumbs.c_strSparsityKey:ConstantsBreadCrumbs. c_fDefaultPCLSparsity}]
730
731 # def funcAdd(self,abndTwo,strFileName=None):
732 # """
733 # Allows one to add an abundance table to an abundance table. They both must be the same state of normalization or summation
734 # or they will be summed or normalized if one of the two are.
735 #
736 # :param abndTwo: AbundanceTable object 2
737 # :type: AbundanceTable
738 # :return AbudanceTable:
739 # """
740 #
741 # #Check summation and normalization
742 # if(self.funcIsSummed() or abndTwo.funcIsSummed()):
743 # self.funcSum()
744 # abndTwo.funcSum()
745 # if(self.funcIsNormalized() or abndTwo.funcIsNormalized()):
746 # self.funcNormalize()
747 # abndTwo.funcNormalize()
748 #
749 # #Normalize Feature names
750 # #Get if the abundance tables have clades
751 # fAbndInputHasClades = self.funcHasFeatureHierarchy()
752 # fAbndCompareHasClades = abndTwo.funcHasFeatureHierarchy()
753 #
754 # if(fAbndInputHasClades or fAbndCompareHasClades):
755 # #If feature delimiters do not match, switch
756 # if not self.funcGetFeatureDelimiter() == abndTwo.funcGetFeatureDelimiter():
757 # abndTwo.funcSetFeatureDelimiter(self.funcGetFeatureDelimiter())
758 #
759 # #Add prefixes if needed.
760 # self.funcAddCladePrefixToFeatures()
761 # abndTwo.funcAddCladePrefixToFeatures()
762 #
763 # #Get feature Names
764 # lsFeatures1 = self.funcGetFeatureNames()
765 # lsFeatures2 = abndTwo.funcGetFeatureNames()
766 #
767 # #Make one feature name list
768 # lsFeaturesCombined = list(set(lsFeatures1+lsFeature2))
769 #
770 # #Add samples by features (Use 0.0 for empty data features, use NA for empty metadata features)
771 #
772 #
773 # #Combine metadata
774 # dictMetadata1 = self.funcGetMetadataCopy()
775 # dictMetadata2 = abndTwo.funcGetMetadataCopy()
776 #
777 # #Get first table metadata and add NA for metadata it is missing for the length of the current metadata
778 # lsMetadataOnlyInTwo = list(set(dictMetadata2.keys())-set(dictMetadata1.keys()))
779 # dictCombinedMetadata = dictMetadata1
780 # lsEmptyMetadata = ["NA" for i in range(self.funcGetSampleCount())]
781 # for sKey in lsMetadataOnlyInTwo:
782 # dictCombinedMetadata[sKey]=lsEmptyMetadata
783 # #Add in the other metadata dictionary
784 # lsCombinedKeys = dictCombinedMetadata.keys()
785 # lsEmptyMetadata = ["NA" for i in range(abndTwo.funcGetSampleCount())]
786 # for sKey in lsCombinedKeys():
787 # if sKey in dictMetadata2:
788 # dictCombinedMetadata[sKey] = dictCombinedMetadata[sKey]+dictMetadata2[sKey]
789 # else:
790 # dictCombinedMetadata[sKey] = dictCombinedMetadata[sKey]+lsEmptyMetadata
791 #
792 # #Make Abundance table
793 # return AbundanceTable(npaAbundance=npaAbundance,
794 # dictMetadata = dictCombinedMetadata,
795 # strName = strFileName if strFileName else os.path.splitext(self)[0]+"_combined_"+os.path.splitext(abndTwo)[0],
796 # strLastMetadata = self.funcGetLastMetadataName(),
797 # cFileDelimiter = self.funcGetFileDelimiter(), cFeatureNameDelimiter=self.funcGetFeatureDelimiter())
798
799 #TODO This does not adjust for sample ordering, needs to
800 def funcAddDataFeature(self, lsNames, npdData):
801 """
802 Adds a data or group of data to the underlying table.
803 Names should be in the order of the data
804 Each row is considered a feature (not sample).
805
806 :param lsNames: Names of the features being added to the data of the table
807 :type: List List of string names
808 :param npdData: Rows of features to add to the table
809 :type: Numpy array accessed by row.
810 """
811 if ( self._npaFeatureAbundance == None ):
812 return False
813
814 # Check number of input data rows
815 iDataRows = npdData.shape[0]
816 if (len(lsNames) != iDataRows):
817 print("Error:The names and the rows of data features to add must be of equal length")
818
819 # Grow the array by the neccessary amount and add the new rows
820 iTableRowCount = self.funcGetFeatureCount()
821 iRowElementCount = self.funcGetSampleCount()
822 self._npaFeatureAbundance.resize(iTableRowCount+iDataRows)
823 for iIndexData in range(iDataRows):
824 self._npaFeatureAbundance[iTableRowCount+iIndexData] = tuple([lsNames[iIndexData]]+list(npdData[iIndexData]))
825
826 return True
827
828 #TODO This does not adjust for sample ordering, needs to
829 def funcAddMetadataFeature(self,lsNames,llsMetadata):
830 """
831 Adds metadata feature to the underlying table.
832 Names should be in the order of the lists of metadata
833 Each internal list is considered a metadata and paired to a name
834 """
835 if ( self._dictTableMetadata == None ):
836 return False
837
838 # Check number of input data rows
839 iMetadataCount = len(llsMetadata)
840 if (len(lsNames) != iMetadataCount):
841 print("Error:The names and the rows of metadata features to add must be of equal length")
842
843 # Add the metadata
844 for tpleMetadata in zip(lsNames,llsMetadata):
845 self._dictTableMetadata[tpleMetadata[0]]=tpleMetadata[1]
846 return True
847
848 #2 test Cases
849 def funcSetFeatureDelimiter(self, cDelimiter):
850 """
851 Changes the feature delimiter to the one provided.
852 Updates the feature names.
853
854 :param cDelimiter: Character feature delimiter
855 :type: Character
856 :return Boolean: Indicator of success or not (false)
857 """
858 if ( self._npaFeatureAbundance == None ):
859 return False
860 cDelimiterCurrent = self.funcGetFeatureDelimiter()
861 if ( not cDelimiter or not cDelimiterCurrent):
862 return False
863
864 #Make new feature names
865 lsNewFeatureNames = [sFeatureName.replace(cDelimiterCurrent,cDelimiter) for sFeatureName in self.funcGetFeatureNames()]
866
867 #Update new feature names to abundance table
868 if (not self.funcGetIDMetadataName() == None):
869 self._npaFeatureAbundance[self.funcGetIDMetadataName()] = np.array(lsNewFeatureNames)
870
871 #Update delimiter
872 self._cFeatureDelimiter = cDelimiter
873 return True
874
875 #Happy path tested
876 def funcGetSampleNames(self):
877 """
878 Returns the sample names (IDs) contained in the abundance table.
879
880 :return Sample Name: A List of sample names indicated by the metadata associated with the sMetadataId given in table creation.
881 A list of string names or empty list on error as well as no underlying table.
882 """
883
884 return self._npaFeatureAbundance.dtype.names[1:] if ( len(self._npaFeatureAbundance) > 1 ) else []
885
886 #Happy Path Tested
887 def funcGetIDMetadataName(self):
888 """
889 Returns the metadata id.
890
891 :return ID: The metadata id (the sample Id).
892 Returns none on error.
893 """
894
895 return self._npaFeatureAbundance.dtype.names[0] if ( len(self._npaFeatureAbundance) > 1 ) else None
896
897 #Happy path tested
898 def funcGetAbundanceCopy(self):
899 """
900 Returns a deep copy of the abundance table.
901
902 :return Numpy Structured Array: The measurement data in the Abundance table. Can use sample names to access each column of measurements.
903 Returns none on error.
904 """
905
906 return self._npaFeatureAbundance.copy() if ( self._npaFeatureAbundance != None ) else None
907
908 #Happy path tested
909 def funcGetAverageAbundancePerSample(self, lsTargetedFeatures):
910 """
911 Averages feature abundance within a sample.
912
913 :param lsTargetedFeatures: String names of features to average
914 :type: List of string names of features which are measured
915 :return List: List of lists or boolean (False on error). One internal list per sample indicating the sample and the feature's average abudance
916 [[sample,average abundance of selected taxa]] or False on error
917 """
918
919 #Sample rank averages [[sample,average abundance of selected taxa]]
920 sampleAbundanceAverages = []
921
922 sampleNames = self.funcGetSampleNames()
923 allTaxaNames = self.funcGetFeatureNames()
924 #Get an abundance table compressed to features of interest
925 abndReducedTable = self.funcGetFeatureAbundanceTable(lsTargetedFeatures)
926 if abndReducedTable == None:
927 return False
928
929 #If the taxa to be selected are not in the list, Return nothing and log
930 lsMissing = []
931 for sFeature in lsTargetedFeatures:
932 if not sFeature in allTaxaNames:
933 lsMissing.append(sFeature)
934 else:
935 #Check to make sure the taxa of interest is not average abundance of 0
936 if not abndReducedTable.funcGetFeatureSumAcrossSamples(sFeature):
937 lsMissing.append(sFeature)
938 if len(lsMissing) > 0:
939 sys.stderr.write( "Could not find features for averaging: " + str(lsMissing) )
940 return False
941
942 #For each sample name get average abundance
943 for sName in sampleNames:
944 npaFeaturesSample = abndReducedTable.funcGetSample(sName)
945 sampleAbundanceAverages.append([sName,sum(npaFeaturesSample)/float(len(npaFeaturesSample))])
946
947 #Sort based on average
948 return sorted(sampleAbundanceAverages, key = lambda sampleData: sampleData[1], reverse = True)
949
950 #Happy path tested 1
951 def funcGetAverageSample(self):
952 """
953 Returns the average sample of the abundance table.
954 This average sample is made of the average of each feature.
955 :return list: A list of averages in the order of the feature names.
956 """
957
958 ldAverageSample = []
959 #If there are no samples then return empty list.
960 if len(self.funcGetSampleNames()) < 1:
961 return ldAverageSample
962
963 #If there are samples return the average of each feature in the order of the feature names.
964 for sFeature in self._npaFeatureAbundance:
965 npFeaturesAbundance = list(sFeature)[1:]
966 ldAverageSample.append(sum(npFeaturesAbundance)/float(len(npFeaturesAbundance)))
967
968 return ldAverageSample
969
970 #Tested 2 cases
971 def funcHasFeatureHierarchy(self):
972 """
973 Returns an indicator of having a hierarchy in the features indicated by the existance of the
974 feature delimiter.
975
976 :return Boolean: True (Has a hierarchy) or False (Does not have a hierarchy)
977 """
978
979 if ( self._npaFeatureAbundance == None ):
980 return None
981 cDelimiter = self.funcGetFeatureDelimiter()
982 if ( not cDelimiter ):
983 return False
984
985 #For each feature name, check to see if the delimiter is in the name
986 for sFeature in self.funcGetFeatureNames():
987 if cDelimiter in sFeature:
988 return True
989 return False
990
991 def funcGetCladePrefixes(self):
992 """
993 Returns the list of prefixes to use on biological sample hierarchy
994
995 :return List: List of strings
996 """
997 return self._lsCladePrefixes
998
999 #3 test cases
1000 def funcAddCladePrefixToFeatures(self):
1001 """
1002 As a standardized clade prefix to indicate biological clade given hierarchy.
1003 Will not add a prefix to already prefixes feature names.
1004 Will add prefix to feature names that do not have them or clades in a feature name that
1005 do not have them while leaving ones that do as is.
1006
1007 :return Boolean: True (Has a hierarchy) or False (Does not have a hierarchy)
1008 """
1009
1010 if ( self._npaFeatureAbundance == None ):
1011 return None
1012 cDelimiter = self.funcGetFeatureDelimiter()
1013 lsPrefixes = self.funcGetCladePrefixes()
1014 iPrefixLength = len(lsPrefixes)
1015 if ( not cDelimiter ):
1016 return False
1017
1018 #Append prefixes to feature names
1019 lsUpdatedFeatureNames = []
1020 lsFeatureNames = self.funcGetFeatureNames()
1021
1022 for sFeatureName in lsFeatureNames:
1023 lsClades = sFeatureName.split(cDelimiter)
1024 #If there are not enough then error
1025 if(len(lsClades) > iPrefixLength):
1026 print("Error:: Too many clades given to be biologically meaningful")
1027 return False
1028 lsUpdatedFeatureNames.append(cDelimiter.join([lsPrefixes[iClade]+lsClades[iClade] if not(lsClades[iClade][0:len(lsPrefixes[iClade])]==lsPrefixes[iClade]) else lsClades[iClade] for iClade in range(len(lsClades))]))
1029
1030 #Update new feature names to abundance table
1031 if not self.funcGetIDMetadataName() == None:
1032 self._npaFeatureAbundance[self.funcGetIDMetadataName()] = np.array(lsUpdatedFeatureNames)
1033
1034 return True
1035
1036 #Happy Path Tested
1037 def funcGetFeatureAbundanceTable(self, lsFeatures):
1038 """
1039 Returns a copy of the current abundance table with the abundance of just the given features.
1040
1041 :param lsFeatures: String Feature IDs that are kept in the compressed abundance table.
1042 :type: List of strings Feature IDs (found as the first entry of a filter in the input file.
1043 :return AbundanceTable: A compressed version of the abundance table.
1044 On an error None is returned.
1045 """
1046
1047 if ( self._npaFeatureAbundance == None ) or ( lsFeatures == None ):
1048 return None
1049
1050 #Get a list of boolean indicators that the row is from the features list
1051 lfFeatureData = [sRowID in lsFeatures for sRowID in self.funcGetFeatureNames()]
1052 #compressed version as an Abundance table
1053 lsNamePieces = os.path.splitext(self._strOriginalName)
1054 abndFeature = AbundanceTable(npaAbundance=np.compress(lfFeatureData, self._npaFeatureAbundance, axis = 0),
1055 dictMetadata = self.funcGetMetadataCopy(),
1056 strName = lsNamePieces[0] + "-" + str(len(lsFeatures)) +"-Features"+lsNamePieces[1],
1057 strLastMetadata=self.funcGetLastMetadataName(),
1058 cFileDelimiter = self.funcGetFileDelimiter(), cFeatureNameDelimiter= self.funcGetFeatureDelimiter())
1059 #Table is no longer normalized
1060 abndFeature._fIsNormalized = False
1061 return abndFeature
1062
1063 #Happy path tested
1064 def funcGetFeatureDelimiter(self):
1065 """
1066 The delimiter of the feature names (For example to use on concensus lineages).
1067
1068 :return Character: Delimiter for the feature name pieces if it is complex.
1069 """
1070
1071 return self._cFeatureDelimiter
1072
1073 #Happy path tested
1074 def funcGetFeatureCount(self):
1075 """
1076 Returns the current feature count.
1077
1078 :return Count: Returns the int count of features in the abundance table.
1079 Returns None on error.
1080 """
1081
1082 return self._npaFeatureAbundance.shape[0] if not self._npaFeatureAbundance is None else 0
1083
1084 #Happy path tested
1085 def funcGetFeatureSumAcrossSamples(self,sFeatureName):
1086 """
1087 Returns float sum of feature values across the samples.
1088
1089 :param sFeatureName: The feature ID to get the sum from.
1090 :type: String.
1091 :return Double: Sum of one feature across samples.
1092 """
1093 return sum(self.funcGetFeature(sFeatureName))
1094
1095 def funcGetFeature(self,sFeatureName):
1096 """
1097 Returns feature values across the samples.
1098
1099 :param sFeatureName: The feature ID to get the sum from.
1100 :type: String.
1101 :return Double: Feature across samples.
1102 """
1103
1104 for sFeature in self._npaFeatureAbundance:
1105 if sFeature[0] == sFeatureName:
1106 return list(sFeature)[1:]
1107 return None
1108
1109 #Happy path tested
1110 def funcGetFeatureNames(self):
1111 """
1112 Return the feature names as a list.
1113
1114 :return Feature Names: List of feature names (or IDs) as strings.
1115 As an error returns empty list.
1116 """
1117
1118 if (not self._npaFeatureAbundance == None):
1119 return self._npaFeatureAbundance[self.funcGetIDMetadataName()]
1120 return []
1121
1122 #Happy path tested
1123 def funcGetFileDelimiter(self):
1124 """
1125 The delimiter of the file the data was read from and which is also the delimiter which would be used to write the data to a file.
1126
1127 :return Character: Delimiter for the parsing and writing the file.
1128 """
1129
1130 return self._cDelimiter
1131
1132 def funcGetLastMetadataName(self):
1133 """
1134 Get the last metadata name that seperates abundance and metadata measurements.
1135
1136 :return string: Metadata name
1137 """
1138 return self._strLastMetadataName
1139
1140 #Happy path tested
1141 def funcGetSample(self,sSampleName):
1142 """
1143 Return a copy of the feature measurements of a sample.
1144
1145 :param sSampleName: Name of sample to return.
1146 :type: String
1147 :return Sample: Measurements Feature measurements of a sample.
1148 Empty numpy array returned on error.
1149 """
1150
1151 if (not self._npaFeatureAbundance == None):
1152 return self._npaFeatureAbundance[sSampleName].copy()
1153 return np.array([])
1154
1155 #Happy path tested
1156 def funcGetMetadata(self, strMetadataName):
1157 """
1158 Returns a list of metadata that is associated with the given metadata name (id).
1159
1160 :param strMetadataName: String metadata ID to be returned
1161 :type: String ID
1162 :return Metadata: List of metadata
1163 """
1164
1165 return copy.deepcopy( self._dictTableMetadata.get(strMetadataName) ) \
1166 if self._dictTableMetadata else None
1167
1168 #Happy path tested
1169 def funcGetMetadataCopy(self):
1170 """
1171 Returns a deep copy of the metadata.
1172
1173 :return Metadata copy: {"ID":[value,value...]}
1174 """
1175
1176 return copy.deepcopy(self._dictTableMetadata)
1177
1178 #Happy path tested
1179 def funcGetName(self):
1180 """
1181 Returns the name of the object which is the file name that generated it.
1182 If the object was generated from an Abundance Table (for instance through stratification)
1183 the name is still in the form of a file that could be written to which is informative
1184 of the changes that have occurred on the data set.
1185 :return string: Name
1186 """
1187 return self._strOriginalName
1188
1189 #Happy path tested. could do more
1190 def funcGetTerminalNodes(self):
1191 """
1192 Returns the terminal nodes given the current feature names in the abundance table. The
1193 features must contain a consensus lineage or all will be returned.
1194 :return List: List of strings of the terminal nodes given the abundance table.
1195 """
1196 return AbundanceTable.funcGetTerminalNodesFromList(lsNames=self.funcGetFeatureNames(),cNameDelimiter=self.funcGetFeatureDelimiter())
1197
1198 #Tested 2 test cases
1199 @staticmethod
1200 def funcGetTerminalNodesFromList(lsNames,cNameDelimiter):
1201 """
1202 Returns the terminal nodes given the current feature names in the abundance table. The
1203 features must contain a consensus lineage or all will be returned.
1204
1205 :param lsNames: The list of string names to parse and filter.
1206 :type: List of strings
1207 :param cNameDelimiter: The delimiter for the name of the features.
1208 :type: Character Delimiter
1209 :return list: A list of terminal elements in the list (given only the list).
1210 """
1211
1212 #Build hash
1213 dictCounts = dict()
1214 for strTaxaName in lsNames:
1215 #Split into the elements of the clades
•1216 lsClades = list([_f for _f in strTaxaName.split(cNameDelimiter) if _f])
1217 #Count clade levels
1218 iCladeLength = len(lsClades)
1219
1220 #Evaluate first element
1221 sClade = lsClades[0]
1222 dictCounts[sClade] = sClade not in dictCounts
1223
1224 #Evaluate the rest of the elements
1225 if iCladeLength < 2:
1226 continue
1227 for iIndex in range(1,iCladeLength):
1228 prevClade = sClade
1229 sClade = cNameDelimiter.join([sClade,lsClades[iIndex]])
1230 if sClade in dictCounts:
1231 dictCounts[sClade] = dictCounts[prevClade] = False
1232 else:
1233 dictCounts[sClade] = True
1234 dictCounts[prevClade] = False
1235
1236 #Return only the elements that were of count 1
•1237 return list([s for s in dictCounts if dictCounts[s] == True])
1238
1239 #Happy path tested
1240 def funcIsNormalized(self):
1241 """
1242 Returns if the data has been normalized.
1243
1244 :return Boolean: Indicates if the data is normalized.
1245 True indicates it the data is normalized.
1246 """
1247
1248 return self._fIsNormalized
1249
1250 #Happy path tested
1251 def funcIsPrimaryIdMetadata(self,sMetadataName):
1252 """
1253 Checks the metadata data associated with the sMetadatName and returns if the metadata is unique.
1254 This is important to some of the functions in the Abundance Table specifically when translating from one metadata to another.
1255
1256 :param sMetadataName: ID of metadata to check for uniqueness.
1257 :type: String Metadata ID.
1258 :return Boolean: Returns indicator of uniqueness.
1259 True indicates unique.
1260 """
1261
1262 lMetadata = self.funcGetMetadata(sMetadataName)
1263 if not lMetadata:
1264 return False
1265 return (len(lMetadata) == len(set(lMetadata)))
1266
1267 #Happy path tested
1268 def funcIsSummed(self):
1269 """
1270 Return is the data is summed.
1271
1272 :return Boolean: Indicator of being summed. True indicates summed.
1273 """
1274
1275 return self._fIsSummed
1276
1277 #Happy path tested
1278 def funcFilterAbundanceByPercentile(self, dPercentileCutOff = 95.0, dPercentageAbovePercentile=1.0):
1279 """
1280 Filter on features.
1281 A feature is removed if it's abundance is not found in the top X percentile a certain percentage of the samples.
1282
1283 :param dPercentileCutOff: The percentile used for filtering.
1284 :type: double A double between 0.0 and 100.0
1285 :param dPercentageAbovePercentile: The percentage above the given percentile (dPercentileCutOff) that must exist to keep the feature.
1286 :type: double Between 0.0 and 100.0
1287 :return Boolean: Indicator of filtering occuring without error. True indicates filtering occuring.
1288 """
1289
1290 #No need to do anything
1291 if(dPercentileCutOff==0.0) or (dPercentageAbovePercentile==0.0):
1292 return True
1293
1294 #Sample names
1295 lsSampleNames = self.funcGetSampleNames()
1296
1297 #Scale percentage out of 100
1298 dPercentageAbovePercentile = dPercentageAbovePercentile/100.0
1299
1300 #Sample count
1301 iSampleCount = len(lsSampleNames)
1302
1303 #Get a threshold score of the value at the specified percentile for each sample
1304 #In the order of the sample names
1305 ldScoreAtPercentile = [scipy.stats.scoreatpercentile(self._npaFeatureAbundance[lsSampleNames[iIndex]],dPercentileCutOff) for iIndex in range(iSampleCount)]
1306
1307 #Record how many entries for each feature have a value equal to or greater than the dPercentileCutOff
1308 #If the percentile of entries passing the criteria are above the dPercentageAbovePercentile put index in list to keep
1309 liKeepIndices = []
1310 iSampleCount = float(iSampleCount)
1311 for iRowIndex, npaRow in enumerate(self._npaFeatureAbundance):
1312 iCountPass = sum([1 if dValue >= ldScoreAtPercentile[iValueIndex] else 0 for iValueIndex, dValue in enumerate(list(npaRow)[1:])])
1313 if (iCountPass / iSampleCount) >= dPercentageAbovePercentile:
1314 liKeepIndices.append(iRowIndex)
1315
1316 #Compress array
1317 self._npaFeatureAbundance = self._npaFeatureAbundance[liKeepIndices,:]
1318
1319 #Update filter state
1320 self._strCurrentFilterState += ":dPercentileCutOff=" + str(dPercentileCutOff) + ",dPercentageAbovePercentile=" + str(dPercentageAbovePercentile)
1321
1322 #Table is no longer normalized
1323 self._fIsNormalized = False
1324
1325 return True
1326
1327 def funcFilterAbundanceByMinValue(self, dMinAbundance = 0.0001, iMinSamples = 3):
1328 """
1329 Filter abundance by requiring features to have a minimum relative abundance in a minimum number of samples.
1330 Will evaluate greater than or equal to the dMinAbundance and iMinSamples.
1331
1332 :param dMinAbundance: Minimum relative abundance.
1333 :type: Real Number Less than 1.
1334 :param iMinSamples: Minimum samples to have the relative abundnace or greater in.
1335 :type: Integer Number greater than 1.
1336 :return Boolean: Indicator of the filter running without error. False indicates error.
1337 """
1338
1339 #No need to do anything
1340 if(dMinAbundance==0) or (iMinSamples==0):
1341 return True
1342
1343 #This normalization requires the data to be relative abundance
1344 if not self._fIsNormalized:
1345 #sys.stderr.write( "Could not filter by sequence occurence because the data is already normalized.\n" )
1346 return False
1347
1348 #Holds which indexes are kept
1349 liKeepFeatures = []
1350 for iRowIndex, dataRow in enumerate( self._npaFeatureAbundance ):
1351 #See which rows meet the criteria and keep the index if needed.
•1352 if len( list( [d for d in list(dataRow)[1:] if d >= dMinAbundance] ) ) >= iMinSamples:
1353 liKeepFeatures.append(iRowIndex)
1354
1355 #Compress array
1356 self._npaFeatureAbundance = self._npaFeatureAbundance[liKeepFeatures,:]
1357 #Update filter state
1358 self._strCurrentFilterState += ":dMinAbundance=" + str(dMinAbundance) + ",iMinSamples=" + str(iMinSamples)
1359
1360 return True
1361
1362 #Happy path tested
1363 def funcFilterAbundanceBySequenceOccurence(self, iMinSequence = 2, iMinSamples = 2):
1364 """
1365 Filter occurence by requiring features to have a minimum sequence occurence in a minimum number of samples.
1366 Will evaluate greater than or equal to the iMinSequence and iMinSamples.
1367
1368 :param iMinSequence: Minimum sequence to occur.
1369 :type: Integer Number Greater than 1.
1370 :param iMinSamples: Minimum samples to occur in.
1371 :type: Integer Number greater than 1.
1372 :return Boolean: Indicator of the filter running without error. False indicates error.
1373 """
1374
1375 #No need to do anything
1376 if(iMinSequence==0) or (iMinSamples==0):
1377 return True
1378
1379 #This normalization requires the data to be reads
1380 if self._fIsNormalized:
1381 #sys.stderr.write( "Could not filter by sequence occurence because the data is already normalized.\n" )
1382 return False
1383
1384 #Holds which indexes are kept
1385 liKeepFeatures = []
1386 for iRowIndex, dataRow in enumerate( self._npaFeatureAbundance ):
1387 #See which rows meet the criteria and keep the index if needed.
•1388 if len( list( [d for d in list(dataRow)[1:] if d >= iMinSequence] ) ) >= iMinSamples:
1389 liKeepFeatures.append(iRowIndex)
1390
1391 #Compress array
1392 self._npaFeatureAbundance = self._npaFeatureAbundance[liKeepFeatures,:]
1393 #Update filter state
1394 self._strCurrentFilterState += ":iMinSequence=" + str(iMinSequence) + ",iMinSamples=" + str(iMinSamples)
1395
1396 return True
1397
1398 #1 Happy path test
1399 def funcFilterFeatureBySD(self, dMinSDCuttOff = 0.0):
1400 """
1401 A feature is removed if it's abundance is not found to have standard deviation more than the given dMinSDCutoff.
1402
1403 :param dMinSDCuttOff: Standard deviation threshold.
1404 :type: Double A double greater than 0.0.
1405 :return Boolean: Indicator of success. False indicates error.
1406 """
1407
1408 #No need to do anything
1409 if(dMinSDCuttOff==0.0):
1410 return True
1411
1412 #Holds which indexes are kept
1413 liKeepFeatures = []
1414
1415 #Evaluate each sample
1416 for iRowIndex, dataRow in enumerate(self._npaFeatureAbundance):
1417 if(np.std(list(dataRow)[1:])>=dMinSDCuttOff):
1418 liKeepFeatures.append(iRowIndex)
1419
1420 #Compress array
1421 self._npaFeatureAbundance = self._npaFeatureAbundance[liKeepFeatures,:]
1422
1423 #Update filter state
1424 self._strCurrentFilterState += ":dMinSDCuttOff=" + str(dMinSDCuttOff)
1425
1426 #Table is no longer normalized
1427 self._fIsNormalized = False
1428
1429 return True
1430
1431 #Happy path tested 2 tests
1432 def funcGetWithoutOTUs(self):
1433 """
1434 Remove features that are terminal otus. Terminal otus are identified as being an integer.
1435 """
1436
1437 #Get the feature names
1438 lsFeatures = self.funcGetFeatureNames()
1439
1440 #Reduce, filter the feature names
1441 lsFeatures = [sFeature for sFeature in lsFeatures if not (ValidateData.funcIsValidStringInt(sFeature.split(self.funcGetFeatureDelimiter())[-1]))]
1442
1443 return self.funcGetFeatureAbundanceTable(lsFeatures)
1444
1445 #Happy path tested
1446 def funcNormalize(self):
1447 """
1448 Convenience method which will call which ever normalization is approriate on the data.
1449 :return Boolean: Indicator of success (true).
1450 """
1451
1452 if self._fIsSummed:
1453 return self.funcNormalizeColumnsWithSummedClades()
1454 else:
1455 return self.funcNormalizeColumnsBySum()
1456
1457 #Testing Status: Light happy path testing
1458 def funcNormalizeColumnsBySum(self):
1459 """
1460 Normalize the data in a manner that is approrpiate for NOT summed data.
1461 Normalize the columns (samples) of the abundance table.
1462 Normalizes as a fraction of the total (number/(sum of all numbers in the column)).
1463 Will not act on summed tables.
1464
1465 :return Boolean: Indicator of success. False indicates error.
1466 """
1467
1468 if self._fIsNormalized:
1469 # sys.stderr.write( "This table is already normalized, did not perform new normalization request.\n" )
1470 return False
1471
1472 if self._fIsSummed:
1473 sys.stderr.write( "This table has clades summed, this normalization is not appropriate. Did not perform.\n" )
1474 return False
1475
1476 #Normalize
1477 for columnName in self.funcGetSampleNames():
1478 column = self._npaFeatureAbundance[columnName]
1479 columnTotal = sum(column)
1480 if(columnTotal > 0.0):
1481 column = column/columnTotal
1482 self._npaFeatureAbundance[columnName] = column
1483
1484 #Indicate normalization has occured
1485 self._fIsNormalized = True
1486
1487 return True
1488
1489 #Happy path tested
1490 def funcNormalizeColumnsWithSummedClades(self):
1491 """
1492 Normalizes a summed Abundance Table.
1493 If this is called on a dataset which is not summed and not normalized.
1494 The data will be summed first and then normalized.
1495 If already normalized, the current normalization is kept.
1496
1497 :return Boolean: Indicator of success. False indicates error.
1498 """
1499
1500 if self._fIsNormalized:
1501 # sys.stderr.write( "This table is already normalized, did not perform new summed normalization request.\n" )
1502 return False
1503
1504 if not self._fIsSummed:
1505 sys.stderr.write( "This table does not have clades summed, this normalization is not appropriate until the clades are summed. The clades are being summed now before normalization.\n" )
1506 self.funcSumClades()
1507
1508 #Load a hash table with root data {sKey: npaAbundances}
1509 hashRoots = {}
1510 for npaRow in self._npaFeatureAbundance:
1511
1512 curldAbundance = np.array(list(npaRow)[1:])
1513 curFeatureNameLength = len(npaRow[0].split(self._cFeatureDelimiter))
1514 curlRootData = hashRoots.get(npaRow[0].split(self._cFeatureDelimiter)[0])
1515
1516 if not curlRootData:
1517 hashRoots[npaRow[0].split(self._cFeatureDelimiter)[0]] = [curFeatureNameLength, curldAbundance]
1518 elif curlRootData[0] > curFeatureNameLength:
1519 hashRoots[npaRow[0].split(self._cFeatureDelimiter)[0]] = [curFeatureNameLength, curldAbundance]
1520
1521 #Normalize each feature by thier root feature
1522 dataMatrix = list()
1523 for npaRow in self._npaFeatureAbundance:
1524
1525 curHashRoot = list(hashRoots[npaRow[0].split(self._cFeatureDelimiter)[0]][1])
1526 dataMatrix.append(tuple([npaRow[0]]+[npaRow[i+1]/curHashRoot[i] if curHashRoot[i] > 0 else 0 for i in range(len(curHashRoot))]))
1527
1528 self._npaFeatureAbundance = np.array(dataMatrix,self._npaFeatureAbundance.dtype)
1529
1530 #Indicate normalization has occured
1531 self._fIsNormalized = True
1532
1533 return True
1534
1535 def _funcRankAbundanceHelper( self, aaTodo, iRank, lRankAbundance ):
1536 """
1537 Helper method for ranking abudance which are tied.
1538
1539 :params aaTodo: List of tied ranks to change to a rank.
1540 :type: List of Enumerates of samples.
1541 :params iRank: Current Rank
1542 :type: Integer
1543 :params lRankAbundance: Sample of abundance
1544 :type: List of integers
1545 """
1546
1547 # Subtract one from iRank (each time) to account for next loop iteration
1548 # Then average it with itself minus (the length of aaTodo + 1)
1549 dRank = ( iRank + iRank - len( aaTodo ) - 1 ) / 2.0
1550 for a in aaTodo:
1551 lRankAbundance[a[0]] = dRank
1552
1553 #1 Happy path test
1554 def funcRankAbundance(self):
1555 """
1556 Rank abundances of features with in a sample.
1557
1558 :return AbundanceTable: Abundance table data ranked (Features with in samples).
1559 None is returned on error.
1560 """
1561
1562 if self._npaFeatureAbundance == None:
1563 return None
1564
1565 lsSampleNames = self.funcGetSampleNames()
1566 npRankAbundance = self.funcGetAbundanceCopy()
1567 liRanks = []
1568 #For each sample name get the ranks
1569 for sName in lsSampleNames:
1570 #Enumerate for order and sort abundances
1571 lfSample = list(enumerate(npRankAbundance[sName]))
1572 lfSample = sorted(lfSample, key = lambda a: a[1], reverse = True)
1573
1574 # Accumulate indices until a new value is encountered to detect + handle ties
1575 aaTodo = []
1576 for i, a in enumerate( lfSample ):
1577 if ( not aaTodo ) or ( a[1] == aaTodo[-1][1] ):
1578 aaTodo.append( a )
1579 else:
1580 # Make multiple tied ranks = average of first and last
1581 self._funcRankAbundanceHelper( aaTodo, i, npRankAbundance[sName] )
1582 aaTodo = [a]
1583 self._funcRankAbundanceHelper( aaTodo, i + 1, npRankAbundance[sName] )
1584
1585 abndRanked = AbundanceTable(npaAbundance=npRankAbundance, dictMetadata=self.funcGetMetadataCopy(),
1586 strName= self.funcGetName() + "-Ranked",
1587 strLastMetadata=self.funcGetLastMetadataName(),
1588 cFileDelimiter=self.funcGetFileDelimiter(),
1589 cFeatureNameDelimiter=self.funcGetFeatureDelimiter())
1590
1591 #Table is no longer normalized
1592 abndRanked._fIsNormalized = False
1593 return abndRanked
1594
1595 def funcGetSampleCount(self):
1596 """
1597 Returns the sample count of the abundance table.
1598 """
1599 return len(self.funcGetSampleNames())
1600
1601 #Happy Path Tested
1602 def funcReduceFeaturesToCladeLevel(self, iCladeLevel):
1603 """
1604 Reduce the current table to a certain clade level.
1605
1606 :param iCladeLevel: The level of the clade to trim the features to.
1607 :type: Integer The higher the number the more clades are presevered in the consensus lineage contained in the feature name.
1608 :return Boolean: Indicator of success. False indicates error.
1609 """
1610
1611 if iCladeLevel < 1: return False
1612 if not self._npaFeatureAbundance == None:
1613 liFeatureKeep = []
1614 [liFeatureKeep.append(tplFeature[0]) if (len(tplFeature[1][0].split(self.funcGetFeatureDelimiter())) <= iCladeLevel) else 0
1615 for tplFeature in enumerate(self._npaFeatureAbundance)]
1616 #Compress array
1617 self._npaFeatureAbundance = self._npaFeatureAbundance[liFeatureKeep,:]
1618
1619 #Update filter state
1620 self._strCurrentFilterState += ":iCladeLevel=" + str(iCladeLevel)
1621 return True
1622 else:
1623 return False
1624
1625 #Happy path tested
1626 def funcRemoveSamples(self,lsSampleNames):
1627 """
1628 Removes the samples given in the list.
1629
1630 :param lsSampleNames: A list of string names of samples to remove.
1631 :type: List of strings Unique values
1632 :return Boolean: Indicator of success (True = success, no error)
1633 """
1634
1635 #Samples to remove
1636 setSamples = set(lsSampleNames)
1637
1638 #Get orignal sample count
1639 iOriginalCount = self._iOriginalSampleCount
1640
1641 #The samples to keep
1642 lsKeepSamples = [sSample for sSample in self.funcGetSampleNames() if not sSample in setSamples]
1643 #The sample to keep as boolean flags for compressing the metadata
1644 lfKeepSamples = [not sSample in setSamples for sSample in self.funcGetSampleNames()]
1645
1646 #Reduce the abundance data and update
1647 self._npaFeatureAbundance = self._npaFeatureAbundance[[self.funcGetIDMetadataName()]+lsKeepSamples]
1648
1649 #Reduce the metadata and update
1650 for sKey in self._dictTableMetadata:
1651 self._dictTableMetadata[sKey] = [value for iindex, value in enumerate(self._dictTableMetadata[sKey]) if lfKeepSamples[iindex]]
1652
1653 #Update sample number count
1654 self._iOriginalSampleCount = len(self.funcGetSampleNames())
1655
1656 return self._iOriginalSampleCount == (iOriginalCount-len(setSamples))
1657
1658 #Happy path tested
1659 def funcRemoveSamplesByMetadata(self, sMetadata, lValuesToRemove):
1660 """
1661 Removes samples from the abundance table based on values of a metadata.
1662 If a metadata has any value given the associated sample is removed.
1663
1664 :param sMetadata: ID of the metdata to check the given values.
1665 :type: String Metadata ID
1666 :param lValuesToRemove: A list of values which if equal to a metadata entry indicate to remove the associated sample.
1667 :type: List of values: List
1668 :return Boolean: Indicator of success (True = success, no error)
1669 """
1670
1671 lsSampleNames = self.funcGetSampleNames()
1672 return self.funcRemoveSamples([lsSampleNames[iindex] for iindex, sValue in enumerate(self.funcGetMetadata(sMetadata)) if sValue in lValuesToRemove])
1673
1674 #Happy path testing
1675 def funcSumClades(self):
1676 """
1677 Sums abundance data by clades indicated in the feature name (as consensus lineages).
1678
1679 :return Boolean: Indicator of success.
1680 False indicates an error.
1681 """
1682
1683 if not self.funcIsSummed():
1684
1685 #Read in the data
1686 #Find the header column (iCol) assumed to be 1 or 2 depending on the location of "NAME"
1687 #Create a list (adSeq) that will eventually hold the sum of the columns of data
1688 astrHeaders = iCol = None
1689 adSeqs = np.array([0] * len(self.funcGetSampleNames()))
1690 pTree = CClade( )
1691 aastrRaw = []
1692
1693 #For each row in the npaAbundance
1694 #Get the feature name, feature abundances, and sum up the abudance columns
1695 #Keep the sum for later normalization
1696 #Give a tree the feature name and abundance
1697 for dataRow in self._npaFeatureAbundance:
1698
1699 sFeatureName = dataRow[0]
1700 ldAbundances = list(dataRow)[1:]
1701
1702 #Add to the sum of the columns (samples)
1703 adSeqs = adSeqs + np.array(list(dataRow)[1:])
1704
1705 #Build tree
1706 pTree.get( sFeatureName.split(self._cFeatureDelimiter) ).set( ldAbundances )
1707
1708 #Create tree of data
1709 #Input missing data
1710 #Fill hashFeatures with the clade name (key) and a blist of values (value) of the specified level interested.
1711 pTree.impute( )
1712 hashFeatures = {}
1713 pTree.freeze( hashFeatures, c_iSumAllCladeLevels, c_fOutputLeavesOnly )
1714 setstrFeatures = list(hashFeatures.keys( ))
1715
1716 #Remove parent clades that are identical to child clades
•1717 for strFeature, adCounts in list(hashFeatures.items( )):
1718 astrFeature = strFeature.strip( ).split( "|" )
1719 while len( astrFeature ) > 1:
1720 astrFeature = astrFeature[:-1]
1721 strParent = "|".join( astrFeature )
1722 adParent = hashFeatures.get( strParent )
1723 if adParent == adCounts:
1724 del hashFeatures[strParent]
1725 setstrFeatures.remove( strParent )
1726
1727 #Sort features to be nice
1728 astrFeatures = sorted( setstrFeatures )
1729
1730 #Change the hash table to an array
1731 dataMatrix = list()
1732 for sFeature in astrFeatures:
1733 dataMatrix.append(tuple([sFeature]+list(hashFeatures[sFeature])))
1734 self._npaFeatureAbundance=np.array(dataMatrix,self._npaFeatureAbundance.dtype)
1735
1736 #Indicate summation has occured
1737 self._fIsSummed = True
1738
1739 return True
1740
1741 #Happy path tested
1742 def funcStratifyByMetadata(self, strMetadata, fWriteToFile=False):
1743 """
1744 Stratifies the AbundanceTable by the given metadata.
1745 Will write each stratified abundance table to file
1746 if fWriteToFile is True the object will used it's internally stored name as a file to write to
1747 if fWriteToFile is a string then it should be a directory and end with "." This will rebase the file
1748 and store it in a different directory but with an otherwise unchanged name.
1749 Note: If the metadata used for stratification has NAs, they will be segregated to thier own table and returned.
1750
1751 :param strMetadata: Metadata ID to stratify data with.
1752 :type: String ID for a metadata.
1753 :param fWriteToFile: Indicator to write to file.
1754 :type: Boolean True indicates to write to file.
1755 :return List: List of AbundanceTables which are deep copies of the original.
1756 Empty list on error.
1757 """
1758
1759 if self._npaFeatureAbundance is None or self._dictTableMetadata is None:
1760 return []
1761
1762 #Get unique metadata values to stratify by
1763 lsMetadata = self._dictTableMetadata.get(strMetadata,[])
1764 setValues = set(lsMetadata)
1765 #If there is only one metadata value then no need to stratify so return the original in the list (and write if needed)
1766 if len(setValues) == 0:
1767 return []
1768
1769 retlAbundanceTables = []
1770 dictAbundanceBlocks = dict()
1771 #Given here there are multiple metadata values, continue to stratify
1772 lsNames = self.funcGetSampleNames()
1773 #Get index of values to break up
1774 for value in setValues:
1775 lfDataIndex = [sData==value for sData in lsMetadata]
1776 #Get abundance data for the metadata value
1777 #The true is added to keep the first column which should be the feature id
1778 npaStratfiedAbundance = self._npaFeatureAbundance[[self.funcGetIDMetadataName()]+list(np.compress(lfDataIndex,lsNames))]
1779
1780 #Get metadata for the metadata value
1781 dictStratifiedMetadata = dict()
1782 for metadataType in self._dictTableMetadata:
1783 dictValues = self.funcGetMetadata(metadataType)
1784 dictStratifiedMetadata[metadataType] = np.compress(lfDataIndex,dictValues).tolist()
1785
1786 #Make abundance table
1787 #Add abundance table to the list
1788 lsNamePieces = os.path.splitext(self._strOriginalName)
1789 objStratifiedAbundanceTable = AbundanceTable(npaAbundance=npaStratfiedAbundance, dictMetadata=dictStratifiedMetadata,
1790 strName=lsNamePieces[0] + "-StratBy-" + value+lsNamePieces[1],
1791 strLastMetadata=self.funcGetLastMetadataName(),
1792 cFeatureNameDelimiter=self._cFeatureDelimiter, cFileDelimiter = self._cDelimiter)
1793 if fWriteToFile:
1794 objStratifiedAbundanceTable.funcWriteToFile(lsNamePieces[0] + "-StratBy-" + value+lsNamePieces[1])
1795 #Append abundance table to returning list
1796 retlAbundanceTables.append(objStratifiedAbundanceTable)
1797
1798 return retlAbundanceTables
1799
1800 #Happy Path Tested
1801 def funcTranslateIntoMetadata(self, lsValues, sMetadataFrom, sMetadataTo, fFromPrimaryIds=True):
1802 """
1803 Takes the given data values in one metadata and translates it to values in another
1804 metadata of the sample samples holding the values of the first metadata
1805 FPrimaryIds, if true the sMetadataFrom are checked for unique values,
1806 If FPrimaryIds is not true, duplicate values can stop the preservation of order
1807 Or may cause duplication in the "to" group. This is not advised.
1808 if the sMetadataFrom has any duplicates the function fails and return false.
1809
1810 :param lsValues: Values to translate.
1811 :type: List List of values.
1812 :param sMetadataFrom: The metadata the lsValues come from.
1813 :type: String ID for the metadata.
1814 :param sMetadataTo: The metadata the lsValues will be translated into keeping the samples the same.
1815 :type: String ID for the metadata.
1816 :param fFromPrimaryIds: The metadata that are in the from metadata list must be unique in each sample.
1817 :type: Boolean True indicates the metadata list should be unique in each sample. Otherwise a false will return.
1818 :return List: List of new values or False on error.
1819 """
1820
1821 #Get metadata
1822 lFromMetadata = self.funcGetMetadata(sMetadataFrom)
1823 if not lFromMetadata:
1824 sys.stderr.write( "Abundancetable::funcTranlateIntoMetadata. Did not receive lFromMetadata.\n" )
1825 return False
1826
1827 lToMetadata = self.funcGetMetadata(sMetadataTo)
1828 if not lToMetadata:
1829 sys.stderr.write( "Abundancetable::funcTranlateIntoMetadata. Did not receive lToMetadata.\n" )
1830 return False
1831
1832 #Check to see if the values are unique if indicated to do so
1833 if fFromPrimaryIds:
1834 if not len(lFromMetadata) == len(set(lFromMetadata)):
1835 sys.stderr.write( "Abundancetable::funcTranlateIntoMetadata. sMetadataFrom did not have unique values.\n" )
1836 return False
1837
1838 #Translate over
1839 if lFromMetadata and lToMetadata:
1840 return [lToMetadata[iIndex] for iIndex in [lFromMetadata.index(value) for value in lsValues]]
1841
1842 return False
1843
1844 #Happy path tested
1845 def funcToArray(self):
1846 """
1847 Returns a numpy array of the current Abundance Table.
1848 Removes the first ID head column and the numpy array is
1849 Made of lists, not tuples.
1850
1851 :return Numpy Array: np.array([[float,float,...],[float,float,...],[float,float,...]])
1852 None is returned on error.
1853 """
1854
1855 if not self._npaFeatureAbundance == None:
1856 return np.array([list(tplRow)[1:] for tplRow in self._npaFeatureAbundance],'float')
1857 return None
1858
1859 #Happy Path tested
1860 def funcWriteToFile(self, xOutputFile, cDelimiter=None, cFileType=ConstantsBreadCrumbs.c_strPCLFile):
1861 """
1862 Writes the AbundanceTable to a file strOutputFile.
1863 Will rewrite over a file as needed.
1864 Will use the cDelimiter to delimit columns if provided.
1865
1866 :param xOutputFile: File stream or File path to write the file to.
1867 :type: String File Path
1868 :param cDelimiter: Delimiter for the output file.
1869 :type: Character If cDlimiter is not specified, the internally stored file delimiter is used.
1870 """
1871
1872 if not xOutputFile:
1873 return
1874 # Check delimiter argument
1875 if not cDelimiter:
1876 cDelimiter = self._cDelimiter
1877
1878 # Check file type: If pcl: Write pcl file; If biom: write biom file; If None - write pcl file
1879 if(cFileType == None):
1880 cFileType == ConstantsBreadCrumbs.c_strPCLFile
1881
1882 if(cFileType == ConstantsBreadCrumbs.c_strPCLFile):
1883 # Write as a pcl file
1884 self._funcWritePCLFile(xOutputFile, cDelimiter=cDelimiter)
1885 elif(cFileType == ConstantsBreadCrumbs.c_strBiomFile):
1886 #Write as a biom file
1887 self._funcWriteBiomFile(xOutputFile)
1888 return
1889
1890 def _funcWritePCLFile(self, xOutputFile, cDelimiter=None):
1891 """
1892 Write an abundance table object as a PCL file.
1893
1894 :param xOutputFile: File stream or File path to write the file to.
1895 :type: String File Path
1896 :param cDelimiter: Delimiter for the output file.
1897 :type: Character If cDlimiter is not specified, the internally stored file delimiter is used.
1898 """
1899
1900 f = csv.writer(open( xOutputFile, "w" ) if isinstance(xOutputFile, str) else xOutputFile, csv.excel_tab, delimiter=cDelimiter)
1901
1902 # Get Row metadata id info (IDs for column header, keys that line up with the ids)
1903 lsRowMetadataIDs, lsRowMetadataIDKeys = self.rwmtRowMetadata.funcMakeIDs() if self.rwmtRowMetadata else [[],[]]
1904
1905 #Write Ids
1906 f.writerows([[self.funcGetIDMetadataName()]+lsRowMetadataIDs+list(self.funcGetSampleNames())])
1907
1908 #Write column metadata
1909 lsKeys = list(set(self._dictTableMetadata.keys())-set([self.funcGetIDMetadataName(),self.funcGetLastMetadataName()]))
1910 lMetadataIterations = list(set(lsKeys+[self.funcGetLastMetadataName()] ))
1911
1912 f.writerows([[sMetaKey]+([ConstantsBreadCrumbs.c_strEmptyDataMetadata]*len(lsRowMetadataIDs))+self.funcGetMetadata(sMetaKey) for sMetaKey in lMetadataIterations if sMetaKey != self.funcGetIDMetadataName() and not sMetaKey is None])
1913
1914 #Write abundance
1915 lsOutput = list()
1916 curAbundance = self._npaFeatureAbundance.tolist()
1917
1918 for curAbundanceRow in curAbundance:
1919 # Make feature metadata, padding with NA as needed
1920 lsMetadata = []
1921 for sMetadataId in lsRowMetadataIDKeys:
1922 lsMetadata = lsMetadata + self.rwmtRowMetadata.funGetFeatureMetadata( curAbundanceRow[0], sMetadataId )
1923 lsMetadata = lsMetadata + ( [ ConstantsBreadCrumbs.c_strEmptyDataMetadata ] *
1924 ( self.rwmtRowMetadata.dictMetadataIDs.get( sMetadataId, 0 ) - len( lsMetadata ) ) )
1925 f.writerows([[curAbundanceRow[0]]+lsMetadata+[str(curAbundanceElement) for curAbundanceElement in curAbundanceRow[1:]]])
1926 return
1927
1928 def _funcWriteBiomFile(self, xOutputFile):
1929 """
1930 Write an abundance table object as a Biom file.
1931 :param xOutputFile: File stream or File path to write the file to.
1932 :type: String File Path
1933 """
1934
1935 #**************************
1936 # Get Sample Names *
1937 #**************************
1938 lSampNames = list(self.funcGetSampleNames())
1939
1940 #**************************
1941 # Metadata Names *
1942 #**************************
1943
1944 dictMetadataCopy = self.funcGetMetadataCopy()
1945 lMetaData = list()
1946 iKeysCounter = 0
•1947 for lMetadataCopyEntry in list(dictMetadataCopy.items()):
1948 iKeysCounter +=1
1949 sMetadataName = lMetadataCopyEntry[0]
1950 lMetadataEntries = lMetadataCopyEntry[1]
1951 iMetadataEntryCounter = -1
1952 for sMetadataEntry in lMetadataEntries:
1953 iMetadataEntryCounter+=1
1954 dictMetadataNames = dict()
1955 dictMetadataNames[sMetadataName ] = sMetadataEntry
1956 if iKeysCounter == 1:
1957 lMetaData.append(dictMetadataNames)
1958 else:
1959 lMetaData[iMetadataEntryCounter][sMetadataName ] = sMetadataEntry
1960
1961
1962 #**************************
1963 # Observation Ids *
1964 # and row metadata *
1965 #**************************
1966 bTaxonomyInRowsFlag = False
1967 if self.rwmtRowMetadata.dictRowMetadata is not None:
1968 bTaxonomyInRowsFlag = True
1969
1970 lObservationMetadataTable = list()
1971
1972 lObservationIds = list()
1973 lFeatureNamesResultArray = self.funcGetFeatureNames()
1974 for sFeatureName in lFeatureNamesResultArray:
1975 lObservationIds.append(sFeatureName)
1976
1977 if self.rwmtRowMetadata and self.rwmtRowMetadata.dictRowMetadata:
1978 RowMetadataEntry = self.rwmtRowMetadata.dictRowMetadata[sFeatureName][ConstantsBreadCrumbs.c_metadata_lowercase]
1979 lObservationMetadataTable.append( RowMetadataEntry )
1980
1981 #**************************
1982 # Data *
1983 #**************************
1984
1985 lData = list()
1986 lAbundanceCopyResultArray = self.funcGetAbundanceCopy()
1987
1988 for r in lAbundanceCopyResultArray:
1989 lr = list(r)
1990 lr.pop(0) #Remove metadata
1991 lAbundanceValues = list()
1992 for AbundanceEntry in lr:
1993 flAbundanceEntry = float(AbundanceEntry)
1994 lAbundanceValues.append(flAbundanceEntry)
1995 lData.append(lAbundanceValues)
1996 arrData = array(lData) #Convert list to array
1997
1998
1999
2000 #**************************
2001 # Invoke the *
2002 # biom table factory *
2003 #**************************
2004 if bTaxonomyInRowsFlag == False:
2005 BiomTable = table_factory(arrData,
2006 lSampNames,
2007 lObservationIds,
2008 lMetaData,
2009 constructor=SparseOTUTable)
2010 else: #There was metadata in the rows
2011 BiomTable = table_factory(arrData,
2012 lSampNames,
2013 lObservationIds,
2014 lMetaData,
2015 lObservationMetadataTable if len(lObservationMetadataTable) > 0 else None,
2016 constructor=SparseOTUTable)
2017
2018 #**************************
2019 # Generate biom Output *
2020 #**************************
2021 f = open( xOutputFile, "w" ) if isinstance(xOutputFile, str) else xOutputFile
2022 f.write(BiomTable.getBiomFormatJsonString(ConstantsBreadCrumbs.c_biom_file_generated_by))
2023 f.close()
2024 return
2025
2026 #Testing Status: 1 Happy path test
2027 @staticmethod
2028 def funcPairTables(strFileOne, strFileTwo, strIdentifier, cDelimiter, strOutFileOne, strOutFileTwo, lsIgnoreValues=None):
2029 """
2030 This method will read in two files and abridge both files (saved as new files)
2031 to just the samples in common between the two files given a common identifier.
2032 ***If the identifier is not unique in each data set, the first sample with the pairing id is taken so make sure the ID is unique.
2033 Expects the files to have the sample delimiters.
2034
2035 :param strFileOne: Path to file one to be paired.
2036 :type: String File path.
2037 :param strFileTwo: Path to file two to be paired.
2038 :type: String File path.
2039 :param strIdentifier: Metadata ID that is used for pairing.
2040 :type: String Metadata ID.
2041 :param cDelimiter: Character delimiter to read the files.
2042 :type: Character Delimiter.
2043 :param strOutFileOne: The output file for the paired version of the first file.
2044 :type: String File path.
2045 :param strOutFileTwo: The output file for the paired version of the second file.
2046 :type: String File path.
2047 :param lsIgnoreValues: These values are ignored even if common IDs between the two files.
2048 :type: List List of strings.
2049 :return Boolean: Indicator of no errors.
2050 False indicates errors.
2051 """
2052
2053 #Validate parameters
2054 if(not ValidateData.funcIsValidFileName(strFileOne)):
2055 sys.stderr.write( "AbundanceTable:checkRawDataFile::Error, file not valid. File:" + strFileOne + "\n" )
2056 return False
2057 #Validate parameters
2058 if(not ValidateData.funcIsValidFileName(strFileTwo)):
2059 sys.stderr.write( "AbundanceTable:checkRawDataFile::Error, file not valid. File:"+ strFileTwo + "\n" )
2060 return False
2061
2062 #Make file one
2063 #Read in file
2064 istm = csv.reader(open(strFileOne,'rU'), csv.excel_tab, delimiter=cDelimiter)
2065 lsContentsOne = [lsRow for lsRow in istm]
2066
2067 #Get the file identifier for file one
2068 fileOneIdentifier = None
2069 for sLine in lsContentsOne:
2070 if sLine[0] == strIdentifier:
2071 fileOneIdentifier = sLine
2072 break
2073
2074 #Make file two
2075 #Read in file
2076 istm = csv.reader(open(strFileTwo,'rU'), csv.excel_tab, delimiter=cDelimiter)
2077 lsContentsTwo = [lsRow for lsRow in istm]
2078
2079 #Get the file identifier for file two
2080 fileTwoIdentifier = None
2081 for sLine in lsContentsTwo:
2082 if sLine[0] == strIdentifier:
2083 fileTwoIdentifier = sLine
2084 break
2085
2086 #Get what is in common between the identifiers
2087 #And find which columns to keep in the tables based on the common elements
2088 setsCommonIdentifiers = set(fileOneIdentifier) & set(fileTwoIdentifier)
2089 if lsIgnoreValues:
2090 setsCommonIdentifiers = setsCommonIdentifiers - set(lsIgnoreValues)
2091
2092 #Get positions of common identifiers in each data set, if the identifier is not unique in a date set just take the first index
2093 lfFileOneIDIndexes = [fileOneIdentifier.index(sCommonID) for sCommonID in setsCommonIdentifiers]
2094 lfFileTwoIDIndexes = [fileTwoIdentifier.index(sCommonID) for sCommonID in setsCommonIdentifiers]
2095
2096 #Convert index list to list of boolean
2097 lfFileOneElements = [iIndex in lfFileOneIDIndexes for iIndex, sIdentifier in enumerate(fileOneIdentifier)]
2098 lfFileTwoElements = [iIndex in lfFileTwoIDIndexes for iIndex, sIdentifier in enumerate(fileTwoIdentifier)]
2099
2100 #Write out file one
2101 ostm = csv.writer(open(strOutFileOne,'w'), csv.excel_tab, delimiter=cDelimiter)
2102 (ostm.writerows([np.compress(lfFileOneElements,sLine) for sLine in lsContentsOne]))
2103
2104 #Write out file two
2105 ostm = csv.writer(open(strOutFileTwo,'w'), csv.excel_tab, delimiter=cDelimiter)
2106 (ostm.writerows([np.compress(lfFileTwoElements,sLine) for sLine in lsContentsTwo]))
2107
2108 return True
2109
2110 #Testing Status: Light happy path testing
2111 @staticmethod
2112 def funcStratifyAbundanceTableByMetadata(strInputFile = None, strDirectory = "", cDelimiter = ConstantsBreadCrumbs.c_cTab, iStratifyByRow = 1, llsGroupings = []):
2113 """
2114 Splits an abundance table into multiple abundance tables stratified by the metadata
2115
2116 :param strInputFile: String file path to read in and stratify.
2117 :type: String File path.
2118 :param strDirectory: Output directory to write stratified files.
2119 :type: String Output directory path.
2120 :param cDelimiter: The delimiter used in the adundance file.
2121 :type: Character Delimiter.
2122 :param iStratifyByRow: The row which contains the metadata to use in stratification.
2123 :type: Integer Positive integer index.
2124 :param llsGroupings: A list of string lists where each string list holds values that are equal and should be grouped together.
2125 So for example, if you wanted to group metadata "1", "2", and "3" seperately but "4" and "5" together you would
2126 Give the following [["4","5"]].
2127 If you know what "1" and "3" also together you would give [["1","3"],["4","5"]]
2128 :type List List of list of strings
2129 :return Boolean: Indicator of NO error.
2130 False indicates an error.
2131 """
2132
2133 #Validate parameters
2134 if(not ValidateData.funcIsValidFileName(strInputFile)):
2135 sys.stderr.write( "AbundanceTable:stratifyAbundanceTableByMetadata::Error, file not valid. File:" + strInputFile + "\n" )
2136 return False
2137 if(not ValidateData.funcIsValidStringType(cDelimiter)):
2138 sys.stderr.write( "AbundanceTable:stratifyAbundanceTableByMetadata::Error, Delimiter is not a valid string/char type. Delimiter =" + cDelimiter + "\n" )
2139 return False
2140 if(not ValidateData.funcIsValidPositiveInteger(iStratifyByRow, tempZero = True) and (not ValidateData.funcIsValidString(iStratifyByRow))):
2141 sys.stderr.write( "AbundanceTable:stratifyAbundanceTableByMetadata::Error, Stratify by row is not a positive integer or string keyword. Row =" +
2142 str(iStratifyByRow) + ".\n" )
2143 return False
2144
2145 #Get the base of the file path
2146 #This is dependent on the given output directory and the prefix of the file name of the input file
2147 #If no output file is given then the input file directory is used.
2148 baseFilePath = strDirectory
2149 lsFilePiecesExt = os.path.splitext(strInputFile)
2150 if baseFilePath:
2151 baseFilePath = baseFilePath + os.path.splitext(os.path.split(strInputFile)[1])[0]
2152 else:
2153 baseFilePath = lsFilePiecesExt[0]
2154
2155 #Read in file
2156 istm = csv.reader(open(strInputFile,'rU'), csv.excel_tab, delimiter=cDelimiter)
2157 sFileContents = [lsRow for lsRow in istm]
2158
2159 #Collect metadata
2160 metadataInformation = dict()
2161
2162 #If the tempStratifyRow is by key word than find the index
2163 if ValidateData.funcIsValidString(iStratifyByRow):
2164 for iLineIndex, strLine in enumerate(sFileContents):
2165 if strLine[0].strip("\"") == iStratifyByRow:
2166 iStratifyByRow = iLineIndex
2167 break
2168
2169 #Stratify by metadata row
2170 #Split metadata row into metadata entries
2171 #And put in a dictionary containing {"variable":[1,2,3,4 column index]}
2172 stratifyByRow = sFileContents[iStratifyByRow]
2173 for metaDataIndex in range(1,len(stratifyByRow)):
2174 metadata = stratifyByRow[metaDataIndex]
2175 #Put all wierd categories, none, whitespace, blank space metadata cases into one bin
2176 if not metadata or metadata in string.whitespace:
2177 metadata = "Blank"
2178 #Remove any extraneous formatting
2179 metadata = metadata.strip(string.whitespace)
2180 #Store processed metadata with column occurence in dictionary
2181 if(not metadata in metadataInformation):
2182 metadataInformation[metadata] = []
2183 metadataInformation[metadata].append(metaDataIndex)
2184
2185 #For each of the groupings
2186 #Use the first value as the primary value which the rest of the values in the list are placed into
2187 #Go through the dict holding the indices and extend the list for the primary value with the secondary values
2188 #Then set the secondary value list to empty so that it will be ignored.
2189 if llsGroupings:
2190 for lSKeyGroups in llsGroupings:
2191 if len(lSKeyGroups) > 1:
2192 for sGroup in lSKeyGroups[1:]:
2193 if sGroup in metadataInformation:
2194 metadataInformation[lSKeyGroups[0]].extend(metadataInformation[sGroup])
2195 metadataInformation[sGroup] = []
2196
2197 #Stratify data
2198 stratifiedAbundanceTables = dict()
2199 for tableRow in sFileContents:
2200 if(len(tableRow)> 1):
2201 for metadata in metadataInformation:
2202 #[0] includes the taxa line
2203 columns = metadataInformation[metadata]
2204 if columns:
2205 columns = [0] + columns
2206 lineList = list()
2207 for column in columns:
2208 lineList.append(tableRow[column])
2209 stratifiedAbundanceTables.setdefault(metadata,[]).append(lineList)
2210
2211 #Write to file
2212 lsFilesWritten = []
2213 for metadata in stratifiedAbundanceTables:
2214 sOutputFile = baseFilePath+"-by-"+metadata.strip("\"")+lsFilePiecesExt[1]
2215 f = csv.writer(open(sOutputFile,'w'), csv.excel_tab, delimiter = cDelimiter )
2216 f.writerows(stratifiedAbundanceTables[metadata])
2217 lsFilesWritten.append(sOutputFile)
2218
2219 return lsFilesWritten
2220
2221
2222
2223 #*******************************************
2224 #* biom interface functions: *
2225 #* 1. _funcBiomToStructuredArray *
2226 #* 2. _funcDecodeBiomMetadata *
2227 #*******************************************
2228 @staticmethod
2229 def _funcBiomToStructuredArray(xInputFile = None):
2230 """
2231 Reads the biom input file and builds a "BiomCommonArea" that contains:
2232 1.BiomCommonArea['sLastMetadata'] - This is the name of the last Metadata (String)
2233 2.BiomCommonArea['BiomTaxData']- dict() - going to be used as lcontents[0]==TaxData
2234 3.BiomCommonArea['Metadata'] - dict() - going to be used as lcontents[1]==MetaData
2235 4.BiomCommonArea['BiomFileInfo'] - dict() - going to be used as lcontents[2]==FileInfo (id, format:eg. Biological Observation Matrix 0.9.1) etc.
2236 5.BiomCommonArea['column_metadata_id'] - This is a string which is the name of the column id
2237 :param xInputFile: File path of biom file to read.
2238 :type: String File path.
2239 :return: BiomCommonArea (See description above)
2240 :type: dict()
2241 """
2242
2243 #*******************************************
2244 #* Build the metadata *
2245 #*******************************************
2246 try:
2247
2248 BiomTable = load_table(xInputFile) if isinstance(xInputFile, str) else xInputFile #Import the biom file
2249 except:
2250 print("Failure decoding biom file - please check your input biom file and rerun")
2251 BiomCommonArea = None
2252 return BiomCommonArea
2253
2254 BiomCommonArea = dict()
2255 dBugNames = list() #Bug Names Table
2256 dRowsMetadata = None #Initialize the np.array of the Rows metadata
2257 BiomElements = json.loads(BiomTable.to_json(''))
•2258 for BiomKey, BiomValue in list(BiomElements.items()):
2259 #****************************************************
2260 #* Checking the different keys: format, *
2261 #* rows, columns, date, generated_by *
2262 #****************************************************
2263 if (BiomKey == ConstantsBreadCrumbs.c_strFormatKey
2264 or BiomKey == ConstantsBreadCrumbs.c_strFormatUrl
2265 or BiomKey == ConstantsBreadCrumbs.c_MatrixTtype
2266 or BiomKey == ConstantsBreadCrumbs.c_strTypekey
2267 or BiomKey == ConstantsBreadCrumbs.c_strIDKey #Same as below
2268 or BiomKey == ConstantsBreadCrumbs.c_GeneratedBy #<---Need to follow up with Biom as always BiomValue = "" even though in the file has a value
2269 or BiomKey == ConstantsBreadCrumbs.c_strDateKey): #Same as above
2270 BiomCommonArea = AbundanceTable._funcInsertKeyToCommonArea(BiomCommonArea, BiomKey, BiomValue)
2271
2272
2273 if BiomKey == ConstantsBreadCrumbs.c_rows:
2274 iMaxIdLen = 0
2275 for iIndexRowMetaData in range(0, len(BiomValue)):
2276 if ConstantsBreadCrumbs.c_id_lowercase in BiomValue[iIndexRowMetaData]:
2277 sBugName = BiomValue[iIndexRowMetaData][ConstantsBreadCrumbs.c_id_lowercase]
2278 dBugNames.append(sBugName) #Post to the bug table
2279 if len(sBugName) > iMaxIdLen: #We are calculating dynamically the length of the ID
2280 iMaxIdLen = len(sBugName)
2281
2282 if ConstantsBreadCrumbs.c_metadata_lowercase in BiomValue[0] and BiomValue[0][ConstantsBreadCrumbs.c_metadata_lowercase] != None :
2283 dRowsMetadata = AbundanceTable._funcBiomBuildRowMetadata(BiomValue, iMaxIdLen )
2284
2285
2286 if BiomKey == ConstantsBreadCrumbs.c_columns:
2287 BiomCommonArea = AbundanceTable._funcDecodeBiomMetadata(BiomCommonArea, BiomValue, iMaxIdLen) #Call the subroutine to Build the metadata
2288
2289
2290 #*******************************************
2291 #* Build the TaxData *
2292 #*******************************************
2293
2294 BiomTaxDataWork = list() #Initlialize TaxData
2295 BiomObservations = BiomTable.iter(axis='observation') #Invoke biom method to fetch data from the biom file
2296 for BiomObservationData in BiomObservations:
2297 sBugName = BiomObservationData[1]
2298 BiomTaxDataEntry = [sBugName]
2299 BiomObservationsValues = BiomObservationData[0]
2300 BiomTaxDataEntry.extend(BiomObservationsValues.tolist())
2301 BiomTaxDataWork.append(tuple(BiomTaxDataEntry))
2302
2303 BiomCommonArea[ConstantsBreadCrumbs.c_BiomTaxData] = np.array(BiomTaxDataWork,dtype=np.dtype(BiomCommonArea[ConstantsBreadCrumbs.c_Dtype]))
2304 BiomCommonArea[ConstantsBreadCrumbs.c_dRowsMetadata] = RowMetadata(dRowsMetadata)
2305 del(BiomCommonArea[ConstantsBreadCrumbs.c_Dtype]) #Not needed anymore
2306
2307 return BiomCommonArea
2308
2309
2310 @staticmethod
2311 def _funcDecodeBiomMetadata(BiomCommonArea, BiomValue = None, iMaxIdLen=0 ):
2312 """
2313 Decode the Biom Metadata and build:
2314 1. BiomCommonArea['Metadata']
2315 2. BiomCommonArea['Dtype']
2316 3. BiomCommonArea['sLastMetadata']
2317 4. BiomCommonArea['column_metadata_id'] - This is a string which is the name of the column id
2318 These elements will be formatted and passed down the line to build the AbundanceTable
2319 :param BiomValue: The "columns" Metadata from the biom file (Contains the Metadata information)
2320 :type: dict()
2321 :param iMaxIdLen: The maximum length of a row ID
2322 :type: Integer
2323 :return: BiomCommonArea
2324 :type: dict()
2325 """
2326
2327 BiomCommonArea[ConstantsBreadCrumbs.c_sLastMetadata] = None #Initialize the LastMetadata element
2328 BiomCommonArea['dRowsMetadata'] = None #Initialize for cases that there is no metadata in the rows
2329
2330 strLastMetadata = None
2331 strIDMetadata = None
2332
2333 lenBiomValue = len(BiomValue)
2334 BiomMetadata = dict()
2335 for cntMetadata in range(0, lenBiomValue):
2336 BiomMetadataEntry = BiomValue[cntMetadata]
2337
•2338 for key, value in list(BiomMetadataEntry.items()): #Loop on the entries
2339 if key == ConstantsBreadCrumbs.c_id_lowercase: #If id - process it
2340 strIDMetadata = ConstantsBreadCrumbs.c_ID
2341 if ConstantsBreadCrumbs.c_ID not in BiomMetadata: #If ID not in the common area - initalize it
2342 BiomMetadata[ConstantsBreadCrumbs.c_ID] = [None] * lenBiomValue #Initialize a list
2343 BiomMetadata[ConstantsBreadCrumbs.c_ID][cntMetadata] = value
2344
2345 if key == ConstantsBreadCrumbs.c_metadata_lowercase: #If key = metadata
2346 if not value is None: #And value is not empty
2347 MetadataDict = value #Initialize a dictionary and post the values
•2348 for MDkey, MDvalue in list(MetadataDict.items()):
2349 MDkey = MDkey
2350 MDvalue = MDvalue
2351
2352 if len(MDkey) > 0: #Search for the last metadata
2353 if not strIDMetadata:
2354 strIDMetadata = MDkey
2355 BiomCommonArea[ConstantsBreadCrumbs.c_sLastMetadata] = MDkey #Set the last Metadata
2356 if MDkey not in BiomMetadata:
2357 BiomMetadata[MDkey] = [None] * lenBiomValue
2358 BiomMetadata[MDkey][cntMetadata] = MDvalue
2359
2360
2361 BiomCommonArea[ConstantsBreadCrumbs.c_Metadata] = BiomMetadata
2362 BiomCommonArea[ConstantsBreadCrumbs.c_MetadataID] = strIDMetadata
2363
2364 #**********************************************
2365 #* Build dtype *
2366 #**********************************************
2367
2368 BiomDtype = list()
2369 iMaxIdLen+=10 #Increase it by 10
2370 FirstValue = ConstantsBreadCrumbs.c_ID
2371 SecondValue = "U" + str(iMaxIdLen)
2372 BiomDtypeEntry = tuple([FirstValue, SecondValue])
2373 BiomDtype.append(BiomDtypeEntry)
2374
2375 BiomDtype.extend([tuple( [a, ConstantsBreadCrumbs.c_f4] ) for a in BiomMetadata[ConstantsBreadCrumbs.c_ID]])
2376
2377 BiomCommonArea[ConstantsBreadCrumbs.c_Dtype] = BiomDtype
2378 return BiomCommonArea
2379
2380 @staticmethod
2381 def _funcBiomBuildRowMetadata( BiomValue, iMaxIdLen ):
2382 """
2383 Builds the row metadata from a BIOM value
2384
2385 :param BiomValue: BIOM Value from the BIOM JSON parsing
2386 :type: Complex dict of string pairs and dicts
2387 :param iMaxIdLen: Maximum length of all the IDs
2388 :type: int
2389 :return: dictRowsMetadata - np Array containing the rows metadata
2390 :type: {string feature id: {'metadata': {'taxonomy': [list of metadata values]}}}
2391 """
2392 # Build the input dict for RowMetadata from a dict of dicts from a BIOM file
2393 dictRowsMetadata = dict()
2394 for iIndexRowMetaData in range(0, len(BiomValue)):
2395 dictRowsMetadata[str(BiomValue[iIndexRowMetaData][ConstantsBreadCrumbs.c_id_lowercase])] = dict()
2396 RowMetadataEntryFromTable = BiomValue[iIndexRowMetaData][ConstantsBreadCrumbs.c_metadata_lowercase]
2397 dMetadataTempDict = dict()
•2398 for key, value in list(RowMetadataEntryFromTable.items()):
2399 dMetadataTempDict[key] = value
2400 dictRowsMetadata[str(BiomValue[iIndexRowMetaData][ConstantsBreadCrumbs.c_id_lowercase])][ConstantsBreadCrumbs.c_metadata_lowercase] = dMetadataTempDict
2401 return dictRowsMetadata
2402
2403 @staticmethod
2404 def _funcInsertKeyToCommonArea(BiomCommonArea, BiomKey, BiomValue):
2405 """
2406 Inserts the keys into the BiomCommonArea["BiomFileInfo"]
2407 :param BiomCommonArea - The common area that has been built before
2408 :type: dict()
2409 :param BiomKey - The current key (eg. format, date, generated by)
2410 :type: str
2411 :param BiomValue - The current value of the key (eg. for format: "Biological Observation Matrix 0.9.1")
2412 :type: str
2413 :return: BiomCommonArea - The updated common area
2414 :type: dict()
2415 """
2416
2417 if ConstantsBreadCrumbs.c_BiomFileInfo not in BiomCommonArea:
2418 BiomCommonArea[ConstantsBreadCrumbs.c_BiomFileInfo] = dict()
2419
2420 strInsertKey = BiomKey #Set Default - But it is now always the same... (eg. URL is not: format_url -->url and others)
2421 PostBiomValue = BiomValue #The default value to be posted
2422 if BiomKey == ConstantsBreadCrumbs.c_strFormatUrl:
2423 strInsertKey = ConstantsBreadCrumbs.c_strURLKey
2424
2425 if BiomKey == ConstantsBreadCrumbs.c_MatrixTtype:
2426 strInsertKey = ConstantsBreadCrumbs.c_strSparsityKey
2427
2428 if BiomKey == ConstantsBreadCrumbs.c_GeneratedBy:
2429 PostBiomValue = None
2430
2431 if BiomKey == ConstantsBreadCrumbs.c_strDateKey:
2432 PostBiomValue = None
2433
2434 BiomCommonArea[ConstantsBreadCrumbs.c_BiomFileInfo][strInsertKey] = PostBiomValue
2435 return BiomCommonArea
2436