mdshw5/pyfaidx — pull request #10 by azalea (2014-06-10 17:53:49+00:00)
Title: Add feature key_function

Add an optional callback function key_function to Fasta and Faidx that should return a unique key for the dictionary from the rname.

"key_function" works similarly as the counterpart in [Bio.SeqIO.to_dict()](http://biopython.org/DIST/docs/api/Bio.SeqIO-module.html#to_dict), which is intended to create unique keys for the dictionary.

For example,

def map_ref_chr(ref):
'''
>>>map_ref_chr('NC_000014.8')
'8'
'''
m = re.search('NC_(\d+)\.\d+', ref)
chr = int(m.group(1))
if chr == 23:
return 'chrX'
if chr == 24:
return 'chrY'
if chr == 12920:
return 'chrMT'
return 'chr%d'%chr

def map_name_chr(name):
parts = name.split('|')
i = parts.index('ref')
assert i != -1
ref = parts[i+1]
return map_ref_chr(ref)

genome = Fasta(genomefile)
print 'Without key_function:'
print genome.keys()
genome = Fasta(genomefile, key_function=map_name_chr)
print 'With key_function:'
print genome.keys()

will print

Without key_function:
['gi|224589812|ref|NC_000020.10|', 'gi|251831106|ref|NC_012920.1|', 'gi|224589803|ref|NC_000012.11|', 'gi|224589817|ref|NC_000005.9|', 'gi|224589821|ref|NC_000009.11|', 'gi|224589810|ref|NC_000019.9|', 'gi|224589816|ref|NC_000004.11|', 'gi|224589805|ref|NC_000014.8|', 'gi|224589820|ref|NC_000008.10|', 'gi|224589809|ref|NC_000018.9|', 'gi|224589813|ref|NC_000021.8|', 'gi|224589815|ref|NC_000003.11|', 'gi|224589806|ref|NC_000015.9|', 'gi|224589818|ref|NC_000006.11|', 'gi|224589811|ref|NC_000002.11|', 'gi|224589823|ref|NC_000024.9|', 'gi|224589808|ref|NC_000017.10|', 'gi|224589801|ref|NC_000010.10|', 'gi|224589819|ref|NC_000007.13|', 'gi|224589807|ref|NC_000016.9|', 'gi|224589802|ref|NC_000011.9|', 'gi|224589800|ref|NC_000001.10|', 'gi|224589822|ref|NC_000023.10|', 'gi|224589804|ref|NC_000013.10|', 'gi|224589814|ref|NC_000022.10|']
With key_function:
['chrMT', 'chrY', 'chrX', 'chr13', 'chr12', 'chr11', 'chr10', 'chr17', 'chr16', 'chr15', 'chr14', 'chr19', 'chr18', 'chr22', 'chr20', 'chr21', 'chr7', 'chr6', 'chr5', 'chr4', 'chr3', 'chr2', 'chr1', 'chr9', 'chr8']

A test file is included in tests/test_feature_key_function.py that uses the current data in tests/data, which shows how to use gene names rather than RefSeq RNA accessions to retrieve sequences. But the idea is rather to create unique and succinct chromosome names.