在生信分析中常常需要对各类ID进行转换,常见的比如
Ensembl的 gene_id
"ENSG00000187634" , transcript_id
"ENST00000342066" 还有我们需要转换为的基因名symbol。进行转换的方法很多,包括在线的网站、R包(org.Hs.eg.db)
等等,这些工具在一些常见的物种上得到了很好的支持。但是对于某些虽然有GTF文件,但是研究较少的物种就显得力不从心了,于是笔者用Python实现了一个各类基因gene ID互换的工具。废话不多说具体代码见文章最后,简单介绍下使用方法:
有如下表格
表格的第一列为Ensembl
gene_id
,此时需要将gene id
转为symbol
,我们首选需要该物种的gtf文件,这里使用hg19(来自Ensembl的GTF)。执行命令
python TransFromGTF.py -input CAP-vs-CA.genes.filter.annot.xls -gtf hg19.gtf -source gene_id -to gene_name -idname id -outname list.out --header --keep
参数:
-input:
指定需要转换的文件,以\t分割;
-gtf:
指定文件的GTF文件,这里使用的是Ensembl的,如果使用NCBI要根据实际调整;
-source:
需要转换的ID在GTF中的称谓,如在GTF中把ENSG00000000003称为gene_id,这个需要根据GTF实际来,可以通过less hg19.gtf查看在GTF中需要转换的ID在GTF注释中的称谓,需要和笔者一样使用的是Ensembl的GTF那么,geneid就是gene_id,转录本id就是transcript_id,而symbol就是gene_name;
-to:
需要转成的目标ID在GTF中的称谓,如这里我要转symbol就是gene_name;
-idname:
需要转换的ID在输入文件中的标题名称,如图的就是id,如果没有标题的文件用0~n代表;
-outname:
输出的文件名称;
--header:
文件有行头,如果文件有行头必须添加此参数,否则不可加入此参数;没有行头时idname用0~n表示,有时则用列名表示;
--keep:
使用该参数时,软件不会覆盖原来的ID,而是在原来的基础上加上一列,不适用这个参数会直接在指定列替换。
大致思路为首先遍历GTF文件,并构建对应的字典,随后读取需要转换文件的表格进行遍历替换。得益于哈希算法,脚本可以快速的对ID进行替换。
TransFromGTF.py软件代码如下:
# -*- coding: utf-8 -*-
import os
import sys
import argparse
import pandas as pd
#############################################################################
#Author:Xizzy email: txizzy#gmail.com
#Describtion: Transform ID from GTF file
#Version: V1.0
#Date: 2021/8/28
#Motify:2021/9/5
#Example: python TransFromGTF.py -input CAP-vs-CA.genes.filter.annot.xls -source gene_id -to gene_name -idname id -outname list.out --header
#############################################################################
parser=argparse.ArgumentParser(description='Transform ID from GTF file! This is a type GTF annot: gene_id "ENSG00000187634"; transcript_id "ENST00000342066"; gene_name "SAMD11"; transcript_name "SAMD11-010"; transcript_biotype "protein_coding"; tag "CCDS"; ccds_id "CCDS2"; havana_transcript "OTTHUMT00000276866";tag "basic"')
parser.add_argument('-input',type=str,help='Input file',required=True)
parser.add_argument('-gtf',type=str,help='Your GTF file path",required=True)
parser.add_argument('-outname',type=str,help='Output name, default is out.xls',default='out.xls')
parser.add_argument('-source',type=str,help='Iuput file id type, the name must be same for gtf file!',required=True)
parser.add_argument('-to',type=str,help='The type to be converted, the name must be same for gtf file!',required=True)
parser.add_argument('-idname',type=str,help='Input the name of column to be handled. For no header input, use 0~n to select the column',required=True)
parser.add_argument('--header',action="store_true",help='Input has header')
parser.add_argument('--keep',action="store_true",help='Do not substitute directly')
args=parser.parse_args()
def get_id(id_list,id_from,trans_to):
with open(args.gtf,'r') as gff:
result = []
hash_dict = dict()
for line in gff:
line1=line.strip().split('\t',8)
try:
Name = line1[8]
except:
continue
try:
from_type = eval(Name.split(id_from)[1].split(';')[0])
#hash methods, it need a large memory!!
to_type = eval(Name.split(trans_to)[1].split(';')[0])
hash_dict[from_type] = to_type
except:
continue
for item in id_list:
try:
result.append(hash_dict[item])
except:
result.append('')
continue
return(result)
if __name__=='__main__':
if(args.header):
df = pd.read_csv(args.input,sep='\t')
else:
df = pd.read_csv(args.input,sep='\t',header=None)
args.idname = int(args.idname)
if(args.source == 'transcript_id'):
keyword=list(df[args.idname].str.split('.',expand=True)[0])
else:
keyword = list(df[args.idname])
df.rename(columns={args.idname:args.to},inplace=True)
if(args.keep):
df[args.idname] = keyword
df[args.to] = get_id(keyword,args.source,args.to)
if(args.header):
df.to_csv(args.outname,sep='\t',index=0)
else:
df.to_csv(args.outname,sep='\t',index=0,header=False)
最后:如果想了解更多和生信或者精品咖啡有关的内容欢迎关注我的微信公众号:**生信咖啡**,更多精彩等你发现!