| 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 |
|
| 8 |
|
| •9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| •16 |
|
| 17 |
|
| 18 |
|
| •19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 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 |
|
| 51 |
|
| 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 |
|
| 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 |
|
| 105 |
|
| 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 |
|
| 176 |
|
| 177 |
|
| 178 |
self.dateCreationDate = dictFileMetadata.get(ConstantsBreadCrumbs.c_strDateKey,None) if dictFileMetadata else None |
| 179 |
|
| 180 |
|
| 181 |
self._strCurrentFilterState = "" |
| 182 |
|
| 183 |
|
| 184 |
self._cDelimiter = cFileDelimiter |
| 185 |
|
| 186 |
|
| 187 |
self._cFeatureDelimiter = cFeatureNameDelimiter |
| 188 |
|
| 189 |
|
| 190 |
self.strFileFormatType = dictFileMetadata.get(ConstantsBreadCrumbs.c_strFormatKey,None) if dictFileMetadata else None |
| 191 |
|
| 192 |
|
| 193 |
self.strFileGenerationSource = dictFileMetadata.get(ConstantsBreadCrumbs.c_strSourceKey,None) if dictFileMetadata else None |
| 194 |
|
| 195 |
|
| 196 |
self.strFileType = dictFileMetadata.get(ConstantsBreadCrumbs.c_strTypekey,None) if dictFileMetadata else None |
| 197 |
|
| 198 |
|
| 199 |
self.strFileURL = dictFileMetadata.get(ConstantsBreadCrumbs.c_strURLKey,None) if dictFileMetadata else None |
| 200 |
|
| 201 |
|
| 202 |
self.strId = dictFileMetadata.get(ConstantsBreadCrumbs.c_strIDKey,None) if dictFileMetadata else None |
| 203 |
|
| 204 |
|
| 205 |
|
| 206 |
self._strLastMetadataName = strLastMetadata |
| 207 |
|
| 208 |
|
| 209 |
self._iOriginalFeatureCount = -1 |
| 210 |
|
| 211 |
|
| 212 |
|
| 213 |
|
| 214 |
self._strOriginalName = strName |
| 215 |
|
| 216 |
|
| 217 |
self._iOriginalSampleCount = -1 |
| 218 |
|
| 219 |
|
| 220 |
self.fSparseMatrix = dictFileMetadata.get(ConstantsBreadCrumbs.c_strSparsityKey,False) if dictFileMetadata else False |
| 221 |
|
| 222 |
|
| 223 |
|
| 224 |
self._dictTableMetadata = dictMetadata |
| 225 |
|
| 226 |
|
| 227 |
self.rwmtRowMetadata = rwmtRowMetadata |
| 228 |
|
| 229 |
|
| 230 |
|
| 231 |
|
| 232 |
self._npaFeatureAbundance = npaAbundance |
| 233 |
|
| 234 |
|
| 235 |
|
| 236 |
|
| 237 |
|
| 238 |
self._lsCladePrefixes = ["k__","p__","c__","o__","f__","g__","s__"] |
| 239 |
|
| 240 |
|
| 241 |
self.__hash__ = None |
| 242 |
|
| 243 |
|
| 244 |
|
| 245 |
|
| 246 |
self._fIsNormalized = self._fIsSummed = None |
| 247 |
|
| 248 |
|
| 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 |
|
| 259 |
|
| 260 |
if ( not self._fIsNormalized ) and lOccurenceFilter: |
| 261 |
iLowestAbundance, iLowestSampleOccurrence = lOccurenceFilter |
| 262 |
self.funcFilterAbundanceBySequenceOccurence( iLowestAbundance, iLowestSampleOccurrence ) |
| 263 |
|
| 264 |
|
| 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 |
|
| 293 |
outputFile = open( xOutputFile, "w" ) if isinstance(xOutputFile, str) else xOutputFile |
| 294 |
|
| 295 |
|
| 296 |
|
| 297 |
|
| 298 |
strFileName = xInputFile if isinstance(xInputFile, str) else xInputFile.name |
| 299 |
|
| 300 |
|
| 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 |
|
| 311 |
if not sLastMetadata: |
| 312 |
strLastMetadata = BiomCommonArea[ConstantsBreadCrumbs.c_sLastMetadata] |
| 313 |
else: |
| 314 |
|
| 315 |
lContents = False |
| 316 |
elif( strFileName.endswith(ConstantsBreadCrumbs.c_strPCLFile) or (strFormat == ConstantsBreadCrumbs.c_strPCLFile) ): |
| 317 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 354 |
if (iFirstDataIndex == -1) and (sLastMetadataName == None): |
| 355 |
print("AbundanceTable:checkRawDataFile::Error, either iFirstDataIndex or sLastMetadataNamemust be given.") |
| 356 |
return False |
| 357 |
|
| 358 |
|
| 359 |
outputFile = strOutputFileName |
| 360 |
if not strOutputFileName: |
| 361 |
outputFile = os.path.splitext(strReadDataFileName)[0]+ConstantsBreadCrumbs.OUTPUT_SUFFIX |
| 362 |
|
| 363 |
|
| 364 |
|
| 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 |
|
| 371 |
|
| 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 |
|
| 383 |
if iFirstDataIndex < 0: |
| 384 |
iFirstDataIndex = iMetadataRow + 1 |
| 385 |
|
| 386 |
|
| •387 |
reSubPeriod = re.compile(r'\.') |
| 388 |
|
| 389 |
|
| 390 |
with open(outputFile,'w') as f: |
| 391 |
|
| 392 |
|
| 393 |
|
| 394 |
|
| 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 |
|
| 405 |
for line in readData[iFirstDataIndex:]: |
| 406 |
writeToFile = False |
| 407 |
cleanLine = list() |
| 408 |
|
| 409 |
lineElements = line.split(cDelimiter) |
| 410 |
|
| 411 |
|
| 412 |
sCleanFeatureName = reSubPeriod.sub("-",lineElements[0]) |
| 413 |
|
| 414 |
|
| 415 |
|
| 416 |
|
| 417 |
for element in lineElements[1:]: |
| 418 |
if(element.strip() in string.whitespace): |
| 419 |
cleanLine.append(ConstantsBreadCrumbs.c_strEmptyAbundanceData) |
| 420 |
|
| 421 |
elif(element == "0"): |
| 422 |
cleanLine.append(element) |
| 423 |
|
| 424 |
else: |
| 425 |
cleanLine.append(element) |
| 426 |
writeToFile = True |
| 427 |
|
| 428 |
|
| 429 |
|
| 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 |
|
| 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 |
|
| 476 |
if objOther is None: |
| 477 |
return False |
| 478 |
|
| 479 |
|
| 480 |
if isinstance(objOther,AbundanceTable) != True: |
| 481 |
return False |
| 482 |
|
| 483 |
|
| 484 |
if self.funcGetFeatureDelimiter() != objOther.funcGetFeatureDelimiter(): |
| 485 |
return False |
| 486 |
|
| 487 |
|
| 488 |
if self.funcGetFileDelimiter() != objOther.funcGetFileDelimiter(): |
| 489 |
return False |
| 490 |
|
| 491 |
|
| 492 |
|
| 493 |
|
| 494 |
|
| 495 |
|
| 496 |
|
| 497 |
|
| 498 |
|
| 499 |
|
| 500 |
|
| 501 |
|
| 502 |
|
| 503 |
|
| 504 |
|
| 505 |
|
| 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 |
|
| 517 |
|
| 518 |
|
| 519 |
|
| 520 |
if self.funcGetFileDelimiter() != objOther.funcGetFileDelimiter(): |
| 521 |
return False |
| 522 |
|
| 523 |
|
| 524 |
if self.dateCreationDate != objOther.dateCreationDate: |
| 525 |
return False |
| 526 |
|
| 527 |
|
| 528 |
if self.strFileFormatType != objOther.strFileFormatType: |
| 529 |
return False |
| 530 |
|
| 531 |
|
| 532 |
|
| 533 |
|
| 534 |
|
| 535 |
|
| 536 |
|
| 537 |
|
| 538 |
|
| 539 |
|
| 540 |
|
| 541 |
|
| 542 |
|
| 543 |
if self.strFileType != objOther.strFileType: |
| 544 |
return False |
| 545 |
|
| 546 |
|
| 547 |
if self.strFileURL != objOther.strFileURL: |
| 548 |
return False |
| 549 |
|
| 550 |
|
| 551 |
|
| 552 |
|
| 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 |
|
| 567 |
|
| 568 |
|
| 569 |
|
| 570 |
|
| 571 |
|
| 572 |
|
| 573 |
|
| 574 |
|
| 575 |
|
| 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 |
|
| 587 |
|
| 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 |
|
| 621 |
istmInput = open( xInputFile, 'rU' ) if isinstance(xInputFile, str) else xInputFile |
| 622 |
|
| 623 |
iFirstDataRow = -1 |
| 624 |
|
| 625 |
namesRow = None |
| 626 |
|
| 627 |
lsRowMetadataIDs = None |
| 628 |
|
| 629 |
iIndexLastMetadataRow = None |
| 630 |
|
| 631 |
metadata = dict() |
| 632 |
|
| 633 |
dataMatrix = [] |
| 634 |
|
| 635 |
dictRowMetadata = {} |
| 636 |
|
| 637 |
iIndex = -1 |
| 638 |
|
| 639 |
csvw = None |
| 640 |
|
| 641 |
|
| 642 |
if ostmOutputFile: |
| 643 |
csvw = csv.writer( open(ostmOutputFile,'w') if isinstance(ostmOutputFile, str) else ostmOutputFile, csv.excel_tab, delimiter = cDelimiter ) |
| 644 |
|
| 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 |
|
| 650 |
|
| 651 |
if iFirstDataRow > 0: |
| 652 |
try: |
| 653 |
|
| 654 |
if lsRowMetadataIDs: |
| 655 |
|
| 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 |
|
| 667 |
else: |
| 668 |
|
| 669 |
for i, s in enumerate( sampleReads ): |
| 670 |
if not s.strip( ): |
| 671 |
sampleReads[i] = ConstantsBreadCrumbs.c_strEmptyDataMetadata |
| 672 |
|
| 673 |
|
| 674 |
|
| 675 |
if ( ( not sMetadataID ) and ( iIndex == 0 ) ) or ( taxId == sMetadataID ): |
| 676 |
namesRow = lsLineElements |
| 677 |
|
| 678 |
if sLastMetadataRow: |
| 679 |
iIndexLastMetadataRow = lsLineElements.index(sLastMetadataRow) |
| 680 |
lsRowMetadataIDs = namesRow[ 1 : iIndexLastMetadataRow + 1 ] |
| 681 |
namesRow = [ namesRow[ 0 ] ] + namesRow[ iIndexLastMetadataRow + 1: ] |
| 682 |
|
| 683 |
|
| 684 |
if len( metadata ) and len( lsRowMetadataIDs ): |
| •685 |
for sKey, lsValues in list(metadata.items()): |
| 686 |
metadata[ sKey ] = lsValues[ iIndexLastMetadataRow: ] |
| 687 |
|
| 688 |
|
| 689 |
metadata[taxId] = sampleReads[ iIndexLastMetadataRow: ] if (lsRowMetadataIDs and len( lsRowMetadataIDs )) else sampleReads |
| 690 |
|
| 691 |
|
| 692 |
|
| 693 |
if ( not sLastMetadata ) or ( taxId == sLastMetadata ): |
| 694 |
iFirstDataRow = iIndex + 1 |
| 695 |
|
| 696 |
|
| 697 |
|
| 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 |
|
| 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 |
|
| 713 |
|
| 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 |
|
| 717 |
taxData = np.array(dataMatrix,dtype=np.dtype(dataTypeVector)) |
| 718 |
|
| 719 |
|
| 720 |
|
| 721 |
|
| 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 |
|
| 732 |
|
| 733 |
|
| 734 |
|
| 735 |
|
| 736 |
|
| 737 |
|
| 738 |
|
| 739 |
|
| 740 |
|
| 741 |
|
| 742 |
|
| 743 |
|
| 744 |
|
| 745 |
|
| 746 |
|
| 747 |
|
| 748 |
|
| 749 |
|
| 750 |
|
| 751 |
|
| 752 |
|
| 753 |
|
| 754 |
|
| 755 |
|
| 756 |
|
| 757 |
|
| 758 |
|
| 759 |
|
| 760 |
|
| 761 |
|
| 762 |
|
| 763 |
|
| 764 |
|
| 765 |
|
| 766 |
|
| 767 |
|
| 768 |
|
| 769 |
|
| 770 |
|
| 771 |
|
| 772 |
|
| 773 |
|
| 774 |
|
| 775 |
|
| 776 |
|
| 777 |
|
| 778 |
|
| 779 |
|
| 780 |
|
| 781 |
|
| 782 |
|
| 783 |
|
| 784 |
|
| 785 |
|
| 786 |
|
| 787 |
|
| 788 |
|
| 789 |
|
| 790 |
|
| 791 |
|
| 792 |
|
| 793 |
|
| 794 |
|
| 795 |
|
| 796 |
|
| 797 |
|
| 798 |
|
| 799 |
|
| 800 |
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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 844 |
for tpleMetadata in zip(lsNames,llsMetadata): |
| 845 |
self._dictTableMetadata[tpleMetadata[0]]=tpleMetadata[1] |
| 846 |
return True |
| 847 |
|
| 848 |
|
| 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 |
|
| 865 |
lsNewFeatureNames = [sFeatureName.replace(cDelimiterCurrent,cDelimiter) for sFeatureName in self.funcGetFeatureNames()] |
| 866 |
|
| 867 |
|
| 868 |
if (not self.funcGetIDMetadataName() == None): |
| 869 |
self._npaFeatureAbundance[self.funcGetIDMetadataName()] = np.array(lsNewFeatureNames) |
| 870 |
|
| 871 |
|
| 872 |
self._cFeatureDelimiter = cDelimiter |
| 873 |
return True |
| 874 |
|
| 875 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 920 |
sampleAbundanceAverages = [] |
| 921 |
|
| 922 |
sampleNames = self.funcGetSampleNames() |
| 923 |
allTaxaNames = self.funcGetFeatureNames() |
| 924 |
|
| 925 |
abndReducedTable = self.funcGetFeatureAbundanceTable(lsTargetedFeatures) |
| 926 |
if abndReducedTable == None: |
| 927 |
return False |
| 928 |
|
| 929 |
|
| 930 |
lsMissing = [] |
| 931 |
for sFeature in lsTargetedFeatures: |
| 932 |
if not sFeature in allTaxaNames: |
| 933 |
lsMissing.append(sFeature) |
| 934 |
else: |
| 935 |
|
| 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 |
|
| 943 |
for sName in sampleNames: |
| 944 |
npaFeaturesSample = abndReducedTable.funcGetSample(sName) |
| 945 |
sampleAbundanceAverages.append([sName,sum(npaFeaturesSample)/float(len(npaFeaturesSample))]) |
| 946 |
|
| 947 |
|
| 948 |
return sorted(sampleAbundanceAverages, key = lambda sampleData: sampleData[1], reverse = True) |
| 949 |
|
| 950 |
|
| 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 |
|
| 960 |
if len(self.funcGetSampleNames()) < 1: |
| 961 |
return ldAverageSample |
| 962 |
|
| 963 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 1019 |
lsUpdatedFeatureNames = [] |
| 1020 |
lsFeatureNames = self.funcGetFeatureNames() |
| 1021 |
|
| 1022 |
for sFeatureName in lsFeatureNames: |
| 1023 |
lsClades = sFeatureName.split(cDelimiter) |
| 1024 |
|
| 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 |
|
| 1031 |
if not self.funcGetIDMetadataName() == None: |
| 1032 |
self._npaFeatureAbundance[self.funcGetIDMetadataName()] = np.array(lsUpdatedFeatureNames) |
| 1033 |
|
| 1034 |
return True |
| 1035 |
|
| 1036 |
|
| 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 |
|
| 1051 |
lfFeatureData = [sRowID in lsFeatures for sRowID in self.funcGetFeatureNames()] |
| 1052 |
|
| 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 |
|
| 1060 |
abndFeature._fIsNormalized = False |
| 1061 |
return abndFeature |
| 1062 |
|
| 1063 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 1213 |
dictCounts = dict() |
| 1214 |
for strTaxaName in lsNames: |
| 1215 |
|
| •1216 |
lsClades = list([_f for _f in strTaxaName.split(cNameDelimiter) if _f]) |
| 1217 |
|
| 1218 |
iCladeLength = len(lsClades) |
| 1219 |
|
| 1220 |
|
| 1221 |
sClade = lsClades[0] |
| 1222 |
dictCounts[sClade] = sClade not in dictCounts |
| 1223 |
|
| 1224 |
|
| 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 |
|
| •1237 |
return list([s for s in dictCounts if dictCounts[s] == True]) |
| 1238 |
|
| 1239 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 1291 |
if(dPercentileCutOff==0.0) or (dPercentageAbovePercentile==0.0): |
| 1292 |
return True |
| 1293 |
|
| 1294 |
|
| 1295 |
lsSampleNames = self.funcGetSampleNames() |
| 1296 |
|
| 1297 |
|
| 1298 |
dPercentageAbovePercentile = dPercentageAbovePercentile/100.0 |
| 1299 |
|
| 1300 |
|
| 1301 |
iSampleCount = len(lsSampleNames) |
| 1302 |
|
| 1303 |
|
| 1304 |
|
| 1305 |
ldScoreAtPercentile = [scipy.stats.scoreatpercentile(self._npaFeatureAbundance[lsSampleNames[iIndex]],dPercentileCutOff) for iIndex in range(iSampleCount)] |
| 1306 |
|
| 1307 |
|
| 1308 |
|
| 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 |
|
| 1317 |
self._npaFeatureAbundance = self._npaFeatureAbundance[liKeepIndices,:] |
| 1318 |
|
| 1319 |
|
| 1320 |
self._strCurrentFilterState += ":dPercentileCutOff=" + str(dPercentileCutOff) + ",dPercentageAbovePercentile=" + str(dPercentageAbovePercentile) |
| 1321 |
|
| 1322 |
|
| 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 |
|
| 1340 |
if(dMinAbundance==0) or (iMinSamples==0): |
| 1341 |
return True |
| 1342 |
|
| 1343 |
|
| 1344 |
if not self._fIsNormalized: |
| 1345 |
|
| 1346 |
return False |
| 1347 |
|
| 1348 |
|
| 1349 |
liKeepFeatures = [] |
| 1350 |
for iRowIndex, dataRow in enumerate( self._npaFeatureAbundance ): |
| 1351 |
|
| •1352 |
if len( list( [d for d in list(dataRow)[1:] if d >= dMinAbundance] ) ) >= iMinSamples: |
| 1353 |
liKeepFeatures.append(iRowIndex) |
| 1354 |
|
| 1355 |
|
| 1356 |
self._npaFeatureAbundance = self._npaFeatureAbundance[liKeepFeatures,:] |
| 1357 |
|
| 1358 |
self._strCurrentFilterState += ":dMinAbundance=" + str(dMinAbundance) + ",iMinSamples=" + str(iMinSamples) |
| 1359 |
|
| 1360 |
return True |
| 1361 |
|
| 1362 |
|
| 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 |
|
| 1376 |
if(iMinSequence==0) or (iMinSamples==0): |
| 1377 |
return True |
| 1378 |
|
| 1379 |
|
| 1380 |
if self._fIsNormalized: |
| 1381 |
|
| 1382 |
return False |
| 1383 |
|
| 1384 |
|
| 1385 |
liKeepFeatures = [] |
| 1386 |
for iRowIndex, dataRow in enumerate( self._npaFeatureAbundance ): |
| 1387 |
|
| •1388 |
if len( list( [d for d in list(dataRow)[1:] if d >= iMinSequence] ) ) >= iMinSamples: |
| 1389 |
liKeepFeatures.append(iRowIndex) |
| 1390 |
|
| 1391 |
|
| 1392 |
self._npaFeatureAbundance = self._npaFeatureAbundance[liKeepFeatures,:] |
| 1393 |
|
| 1394 |
self._strCurrentFilterState += ":iMinSequence=" + str(iMinSequence) + ",iMinSamples=" + str(iMinSamples) |
| 1395 |
|
| 1396 |
return True |
| 1397 |
|
| 1398 |
|
| 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 |
|
| 1409 |
if(dMinSDCuttOff==0.0): |
| 1410 |
return True |
| 1411 |
|
| 1412 |
|
| 1413 |
liKeepFeatures = [] |
| 1414 |
|
| 1415 |
|
| 1416 |
for iRowIndex, dataRow in enumerate(self._npaFeatureAbundance): |
| 1417 |
if(np.std(list(dataRow)[1:])>=dMinSDCuttOff): |
| 1418 |
liKeepFeatures.append(iRowIndex) |
| 1419 |
|
| 1420 |
|
| 1421 |
self._npaFeatureAbundance = self._npaFeatureAbundance[liKeepFeatures,:] |
| 1422 |
|
| 1423 |
|
| 1424 |
self._strCurrentFilterState += ":dMinSDCuttOff=" + str(dMinSDCuttOff) |
| 1425 |
|
| 1426 |
|
| 1427 |
self._fIsNormalized = False |
| 1428 |
|
| 1429 |
return True |
| 1430 |
|
| 1431 |
|
| 1432 |
def funcGetWithoutOTUs(self): |
| 1433 |
""" |
| 1434 |
Remove features that are terminal otus. Terminal otus are identified as being an integer. |
| 1435 |
""" |
| 1436 |
|
| 1437 |
|
| 1438 |
lsFeatures = self.funcGetFeatureNames() |
| 1439 |
|
| 1440 |
|
| 1441 |
lsFeatures = [sFeature for sFeature in lsFeatures if not (ValidateData.funcIsValidStringInt(sFeature.split(self.funcGetFeatureDelimiter())[-1]))] |
| 1442 |
|
| 1443 |
return self.funcGetFeatureAbundanceTable(lsFeatures) |
| 1444 |
|
| 1445 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 1485 |
self._fIsNormalized = True |
| 1486 |
|
| 1487 |
return True |
| 1488 |
|
| 1489 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 1548 |
|
| 1549 |
dRank = ( iRank + iRank - len( aaTodo ) - 1 ) / 2.0 |
| 1550 |
for a in aaTodo: |
| 1551 |
lRankAbundance[a[0]] = dRank |
| 1552 |
|
| 1553 |
|
| 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 |
|
| 1569 |
for sName in lsSampleNames: |
| 1570 |
|
| 1571 |
lfSample = list(enumerate(npRankAbundance[sName])) |
| 1572 |
lfSample = sorted(lfSample, key = lambda a: a[1], reverse = True) |
| 1573 |
|
| 1574 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 1617 |
self._npaFeatureAbundance = self._npaFeatureAbundance[liFeatureKeep,:] |
| 1618 |
|
| 1619 |
|
| 1620 |
self._strCurrentFilterState += ":iCladeLevel=" + str(iCladeLevel) |
| 1621 |
return True |
| 1622 |
else: |
| 1623 |
return False |
| 1624 |
|
| 1625 |
|
| 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 |
|
| 1636 |
setSamples = set(lsSampleNames) |
| 1637 |
|
| 1638 |
|
| 1639 |
iOriginalCount = self._iOriginalSampleCount |
| 1640 |
|
| 1641 |
|
| 1642 |
lsKeepSamples = [sSample for sSample in self.funcGetSampleNames() if not sSample in setSamples] |
| 1643 |
|
| 1644 |
lfKeepSamples = [not sSample in setSamples for sSample in self.funcGetSampleNames()] |
| 1645 |
|
| 1646 |
|
| 1647 |
self._npaFeatureAbundance = self._npaFeatureAbundance[[self.funcGetIDMetadataName()]+lsKeepSamples] |
| 1648 |
|
| 1649 |
|
| 1650 |
for sKey in self._dictTableMetadata: |
| 1651 |
self._dictTableMetadata[sKey] = [value for iindex, value in enumerate(self._dictTableMetadata[sKey]) if lfKeepSamples[iindex]] |
| 1652 |
|
| 1653 |
|
| 1654 |
self._iOriginalSampleCount = len(self.funcGetSampleNames()) |
| 1655 |
|
| 1656 |
return self._iOriginalSampleCount == (iOriginalCount-len(setSamples)) |
| 1657 |
|
| 1658 |
|
| 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 |
|
| 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 |
|
| 1686 |
|
| 1687 |
|
| 1688 |
astrHeaders = iCol = None |
| 1689 |
adSeqs = np.array([0] * len(self.funcGetSampleNames())) |
| 1690 |
pTree = CClade( ) |
| 1691 |
aastrRaw = [] |
| 1692 |
|
| 1693 |
|
| 1694 |
|
| 1695 |
|
| 1696 |
|
| 1697 |
for dataRow in self._npaFeatureAbundance: |
| 1698 |
|
| 1699 |
sFeatureName = dataRow[0] |
| 1700 |
ldAbundances = list(dataRow)[1:] |
| 1701 |
|
| 1702 |
|
| 1703 |
adSeqs = adSeqs + np.array(list(dataRow)[1:]) |
| 1704 |
|
| 1705 |
|
| 1706 |
pTree.get( sFeatureName.split(self._cFeatureDelimiter) ).set( ldAbundances ) |
| 1707 |
|
| 1708 |
|
| 1709 |
|
| 1710 |
|
| 1711 |
pTree.impute( ) |
| 1712 |
hashFeatures = {} |
| 1713 |
pTree.freeze( hashFeatures, c_iSumAllCladeLevels, c_fOutputLeavesOnly ) |
| 1714 |
setstrFeatures = list(hashFeatures.keys( )) |
| 1715 |
|
| 1716 |
|
| •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 |
|
| 1728 |
astrFeatures = sorted( setstrFeatures ) |
| 1729 |
|
| 1730 |
|
| 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 |
|
| 1737 |
self._fIsSummed = True |
| 1738 |
|
| 1739 |
return True |
| 1740 |
|
| 1741 |
|
| 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 |
|
| 1763 |
lsMetadata = self._dictTableMetadata.get(strMetadata,[]) |
| 1764 |
setValues = set(lsMetadata) |
| 1765 |
|
| 1766 |
if len(setValues) == 0: |
| 1767 |
return [] |
| 1768 |
|
| 1769 |
retlAbundanceTables = [] |
| 1770 |
dictAbundanceBlocks = dict() |
| 1771 |
|
| 1772 |
lsNames = self.funcGetSampleNames() |
| 1773 |
|
| 1774 |
for value in setValues: |
| 1775 |
lfDataIndex = [sData==value for sData in lsMetadata] |
| 1776 |
|
| 1777 |
|
| 1778 |
npaStratfiedAbundance = self._npaFeatureAbundance[[self.funcGetIDMetadataName()]+list(np.compress(lfDataIndex,lsNames))] |
| 1779 |
|
| 1780 |
|
| 1781 |
dictStratifiedMetadata = dict() |
| 1782 |
for metadataType in self._dictTableMetadata: |
| 1783 |
dictValues = self.funcGetMetadata(metadataType) |
| 1784 |
dictStratifiedMetadata[metadataType] = np.compress(lfDataIndex,dictValues).tolist() |
| 1785 |
|
| 1786 |
|
| 1787 |
|
| 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 |
|
| 1796 |
retlAbundanceTables.append(objStratifiedAbundanceTable) |
| 1797 |
|
| 1798 |
return retlAbundanceTables |
| 1799 |
|
| 1800 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 1875 |
if not cDelimiter: |
| 1876 |
cDelimiter = self._cDelimiter |
| 1877 |
|
| 1878 |
|
| 1879 |
if(cFileType == None): |
| 1880 |
cFileType == ConstantsBreadCrumbs.c_strPCLFile |
| 1881 |
|
| 1882 |
if(cFileType == ConstantsBreadCrumbs.c_strPCLFile): |
| 1883 |
|
| 1884 |
self._funcWritePCLFile(xOutputFile, cDelimiter=cDelimiter) |
| 1885 |
elif(cFileType == ConstantsBreadCrumbs.c_strBiomFile): |
| 1886 |
|
| 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 |
|
| 1903 |
lsRowMetadataIDs, lsRowMetadataIDKeys = self.rwmtRowMetadata.funcMakeIDs() if self.rwmtRowMetadata else [[],[]] |
| 1904 |
|
| 1905 |
|
| 1906 |
f.writerows([[self.funcGetIDMetadataName()]+lsRowMetadataIDs+list(self.funcGetSampleNames())]) |
| 1907 |
|
| 1908 |
|
| 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 |
|
| 1915 |
lsOutput = list() |
| 1916 |
curAbundance = self._npaFeatureAbundance.tolist() |
| 1917 |
|
| 1918 |
for curAbundanceRow in curAbundance: |
| 1919 |
|
| 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 |
|
| 1937 |
|
| 1938 |
lSampNames = list(self.funcGetSampleNames()) |
| 1939 |
|
| 1940 |
|
| 1941 |
|
| 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 |
|
| 1964 |
|
| 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 |
|
| 1983 |
|
| 1984 |
|
| 1985 |
lData = list() |
| 1986 |
lAbundanceCopyResultArray = self.funcGetAbundanceCopy() |
| 1987 |
|
| 1988 |
for r in lAbundanceCopyResultArray: |
| 1989 |
lr = list(r) |
| 1990 |
lr.pop(0) |
| 1991 |
lAbundanceValues = list() |
| 1992 |
for AbundanceEntry in lr: |
| 1993 |
flAbundanceEntry = float(AbundanceEntry) |
| 1994 |
lAbundanceValues.append(flAbundanceEntry) |
| 1995 |
lData.append(lAbundanceValues) |
| 1996 |
arrData = array(lData) |
| 1997 |
|
| 1998 |
|
| 1999 |
|
| 2000 |
|
| 2001 |
|
| 2002 |
|
| 2003 |
|
| 2004 |
if bTaxonomyInRowsFlag == False: |
| 2005 |
BiomTable = table_factory(arrData, |
| 2006 |
lSampNames, |
| 2007 |
lObservationIds, |
| 2008 |
lMetaData, |
| 2009 |
constructor=SparseOTUTable) |
| 2010 |
else: |
| 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 |
|
| 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 |
|
| 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 |
|
| 2054 |
if(not ValidateData.funcIsValidFileName(strFileOne)): |
| 2055 |
sys.stderr.write( "AbundanceTable:checkRawDataFile::Error, file not valid. File:" + strFileOne + "\n" ) |
| 2056 |
return False |
| 2057 |
|
| 2058 |
if(not ValidateData.funcIsValidFileName(strFileTwo)): |
| 2059 |
sys.stderr.write( "AbundanceTable:checkRawDataFile::Error, file not valid. File:"+ strFileTwo + "\n" ) |
| 2060 |
return False |
| 2061 |
|
| 2062 |
|
| 2063 |
|
| 2064 |
istm = csv.reader(open(strFileOne,'rU'), csv.excel_tab, delimiter=cDelimiter) |
| 2065 |
lsContentsOne = [lsRow for lsRow in istm] |
| 2066 |
|
| 2067 |
|
| 2068 |
fileOneIdentifier = None |
| 2069 |
for sLine in lsContentsOne: |
| 2070 |
if sLine[0] == strIdentifier: |
| 2071 |
fileOneIdentifier = sLine |
| 2072 |
break |
| 2073 |
|
| 2074 |
|
| 2075 |
|
| 2076 |
istm = csv.reader(open(strFileTwo,'rU'), csv.excel_tab, delimiter=cDelimiter) |
| 2077 |
lsContentsTwo = [lsRow for lsRow in istm] |
| 2078 |
|
| 2079 |
|
| 2080 |
fileTwoIdentifier = None |
| 2081 |
for sLine in lsContentsTwo: |
| 2082 |
if sLine[0] == strIdentifier: |
| 2083 |
fileTwoIdentifier = sLine |
| 2084 |
break |
| 2085 |
|
| 2086 |
|
| 2087 |
|
| 2088 |
setsCommonIdentifiers = set(fileOneIdentifier) & set(fileTwoIdentifier) |
| 2089 |
if lsIgnoreValues: |
| 2090 |
setsCommonIdentifiers = setsCommonIdentifiers - set(lsIgnoreValues) |
| 2091 |
|
| 2092 |
|
| 2093 |
lfFileOneIDIndexes = [fileOneIdentifier.index(sCommonID) for sCommonID in setsCommonIdentifiers] |
| 2094 |
lfFileTwoIDIndexes = [fileTwoIdentifier.index(sCommonID) for sCommonID in setsCommonIdentifiers] |
| 2095 |
|
| 2096 |
|
| 2097 |
lfFileOneElements = [iIndex in lfFileOneIDIndexes for iIndex, sIdentifier in enumerate(fileOneIdentifier)] |
| 2098 |
lfFileTwoElements = [iIndex in lfFileTwoIDIndexes for iIndex, sIdentifier in enumerate(fileTwoIdentifier)] |
| 2099 |
|
| 2100 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 2146 |
|
| 2147 |
|
| 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 |
|
| 2156 |
istm = csv.reader(open(strInputFile,'rU'), csv.excel_tab, delimiter=cDelimiter) |
| 2157 |
sFileContents = [lsRow for lsRow in istm] |
| 2158 |
|
| 2159 |
|
| 2160 |
metadataInformation = dict() |
| 2161 |
|
| 2162 |
|
| 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 |
|
| 2170 |
|
| 2171 |
|
| 2172 |
stratifyByRow = sFileContents[iStratifyByRow] |
| 2173 |
for metaDataIndex in range(1,len(stratifyByRow)): |
| 2174 |
metadata = stratifyByRow[metaDataIndex] |
| 2175 |
|
| 2176 |
if not metadata or metadata in string.whitespace: |
| 2177 |
metadata = "Blank" |
| 2178 |
|
| 2179 |
metadata = metadata.strip(string.whitespace) |
| 2180 |
|
| 2181 |
if(not metadata in metadataInformation): |
| 2182 |
metadataInformation[metadata] = [] |
| 2183 |
metadataInformation[metadata].append(metaDataIndex) |
| 2184 |
|
| 2185 |
|
| 2186 |
|
| 2187 |
|
| 2188 |
|
| 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 |
|
| 2198 |
stratifiedAbundanceTables = dict() |
| 2199 |
for tableRow in sFileContents: |
| 2200 |
if(len(tableRow)> 1): |
| 2201 |
for metadata in metadataInformation: |
| 2202 |
|
| 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 |
|
| 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 |
|
| 2225 |
|
| 2226 |
|
| 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 |
|
| 2245 |
|
| 2246 |
try: |
| 2247 |
|
| 2248 |
BiomTable = load_table(xInputFile) if isinstance(xInputFile, str) else xInputFile |
| 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() |
| 2256 |
dRowsMetadata = None |
| 2257 |
BiomElements = json.loads(BiomTable.to_json('')) |
| •2258 |
for BiomKey, BiomValue in list(BiomElements.items()): |
| 2259 |
|
| 2260 |
|
| 2261 |
|
| 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 |
| 2268 |
or BiomKey == ConstantsBreadCrumbs.c_GeneratedBy |
| 2269 |
or BiomKey == ConstantsBreadCrumbs.c_strDateKey): |
| 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) |
| 2279 |
if len(sBugName) > iMaxIdLen: |
| 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) |
| 2288 |
|
| 2289 |
|
| 2290 |
|
| 2291 |
|
| 2292 |
|
| 2293 |
|
| 2294 |
BiomTaxDataWork = list() |
| 2295 |
BiomObservations = BiomTable.iter(axis='observation') |
| 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]) |
| 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 |
| 2328 |
BiomCommonArea['dRowsMetadata'] = None |
| 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()): |
| 2339 |
if key == ConstantsBreadCrumbs.c_id_lowercase: |
| 2340 |
strIDMetadata = ConstantsBreadCrumbs.c_ID |
| 2341 |
if ConstantsBreadCrumbs.c_ID not in BiomMetadata: |
| 2342 |
BiomMetadata[ConstantsBreadCrumbs.c_ID] = [None] * lenBiomValue |
| 2343 |
BiomMetadata[ConstantsBreadCrumbs.c_ID][cntMetadata] = value |
| 2344 |
|
| 2345 |
if key == ConstantsBreadCrumbs.c_metadata_lowercase: |
| 2346 |
if not value is None: |
| 2347 |
MetadataDict = value |
| •2348 |
for MDkey, MDvalue in list(MetadataDict.items()): |
| 2349 |
MDkey = MDkey |
| 2350 |
MDvalue = MDvalue |
| 2351 |
|
| 2352 |
if len(MDkey) > 0: |
| 2353 |
if not strIDMetadata: |
| 2354 |
strIDMetadata = MDkey |
| 2355 |
BiomCommonArea[ConstantsBreadCrumbs.c_sLastMetadata] = MDkey |
| 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 |
|
| 2366 |
|
| 2367 |
|
| 2368 |
BiomDtype = list() |
| 2369 |
iMaxIdLen+=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 |
|
| 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 |
| 2421 |
PostBiomValue = BiomValue |
| 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 |
|