# -*- coding: utf-8 -*-
# __author__ = 'JieYao'
from biocluster.agent import Agent
from biocluster.tool import Tool
import os
import types
import subprocess
from biocluster.core.exceptions import OptionError class PpinetworkAgent(Agent):
"""
需要calc_ppi.py
version 1.0
author: JieYao
last_modified: 2016.8.15
""" def __init__(self, parent):
super(PpinerworkAgent, self).__init__(parent)
options = [
{"name": "ppitable", "type": "infile"},
{"name": "cut", "type": "string", "default": "-1"}
]
self.add_option(options)
self.step.add_steps('PpinetworkAnalysis')
self.on('start', self.step_start)
self.on('end', self.step.end) def step_start(self):
self.step.PpinetworkAnalysis.start()
self.step.update() def step_end(self):
self.step.PpinetworkAnalysis.finish()
self.step.update() def check_options(self):
"""
重写参数检查
"""
if not self.option('ppitable').is_set():
raise OptionError('必须提供PPI网络表')
if not os.path.exists(self.option('ppitable')):
raise OptionError('PPI网络表路径错误')
ppi_list = open( self.option('ppitable'), "r").readline.strip().split("\t")
if "combined_score" not in ppi_list:
raise OptionError("PPI网络表缺少结合分数")
if ("yfrom" not in ppi_list) or ("to" not in ppi_list):
raise OptionError("PPI网络缺少相互作用蛋白信息")
try:
eval(self.option('cut'))
except:
raise OptionError("Cut参数值异常,无法转换")
return True def set_resource(self):
"""
设置所需资源
"""
self._cpu = 2
self._memory = '' def end():
result_dir = self.add_upload_dir(self.output_dir)
result_dir.add_repath_rules([
[".", "", "PPI网络分析结果输出目录"],
["./protein_interaction_network_centrality.txt", "txt", "PPI网络中心系数表"],
["./protein_interaction_network_clustering.txt", "txt", "PPI网络节点聚类系数表"],
["./protein_interaction_network_transitivity.txt", "txt", "PPI网络传递性"],
["./protein_interaction_network_by_cut.txt", "txt", "Cut值约束后的PPI网络"]
["./protein_interaction_network_degree_distribution.txt", "txt", "PPI网络度分布表"],
["./protein_interaction_network_node_degree.txt", "txt", "PPI网络节点度属性表"]
])
print self.get_upload_files()
super(PpinetworkAgent, self).end() class PpinetworkTool(Tool):
def __init__(self, config):
super(PpinetworkTool, self).__init__(config)
self._version = "1.0.1"
self.cmd_path = self.config.SOFTWARE_DIR + "/bioinfo/rna/scripts/calc_ppi.py"
self.ppi_table = self.option('ppitable')
self.out_files = ['protein_interaction_network_centrality.txt', 'protein_interaction_network_clustering.txt', 'protein_interaction_network_transitivity.txt', 'protein_interaction_network_by_cut.txt', 'protein_interaction_network_degree_distribution.txt', 'protein_interaction_network_node_degree.txt'] def run(self):
"""
运行
"""
super(PpinetworkTool, self).run()
self.run_ppi_network_py() def run_ppi_network_py(self):
"""
运行calc_ppi.py
"""
real_ppi_table = self.ppi_table
cmd = self.config.SOFTWARE_DIR + '.program/Python/bin/python'
cmd += self.cmd_path
cmd += " -i %s -o %s" %(real_ppi_table, self.work_dir + '.ppi_network')
if self.option("cut").is_set:
cmd += " -c %s" %(self.option('cut'))
self.logger.info("开始运行calc_ppi.py") try:
subprocess.check_output(cmd, shell=True)
self.logger.info('PPI_Network计算完成')
except subprocess.CalledProcessError:
self.logger.info('PPI_Network计算失败')
self.ser_error("运行calc_ppi.py失败")
allfiles = self.get_filesname()
for i in range(len(self.out_files)):
self.linkfile(allfiles[i], self.out_files[i])
self.end() def linkfile(self, oldfile, newname):
"""
link文件到output文件夹
:param oldfile 资源文件路径
:param newname 新的文件名
:return
"""
newpath = os.path.join(self.output_dir, newname)
if os.path.exists(newpath):
os.remove(newpath)
os.link(oldfile, newpath) def get_filesname(self):
files_status = [None, None, None, None, None, None]
for paths,d,filelist in os.walk(self.work_dir + '/ppi_network'):
for filename in filelist:
name = os.path.join(paths, filename)
for i in range(len(self.out_files)):
if self.out_files[i] in name:
files_status[i] = name
for i in range(len(self.out_files)):
if not files_status[i]:
self.set_error('未知原因,结果文件生成出错或丢失')
return files_status
 # -*- coding: utf-8 -*-
# __author__ = 'JieYao' import os
import argparse
from biocluster.config import Config
import shutil
import networkx global name_list
name_list = [""] def search(node_name):
global name_list
for i in range(len(name_list)):
if node_name == name_list[i]:
return i
name_list += [node_name]
return len(name_list)-1 parser = argparse.ArgumentParser(description='输入蛋白质相互作用网络,输出网络信息')
parser.add_argument('-i', "--PPI_network", help="输入的PPI网络", required = True)
parser.add_argument('-c', "--cut", help='蛋白相互作用阈值', required = False)
parser.add_argument('-o', "--output", help = "输出文件输出路径", required = True)
#parser.add_argument('-top', "--top", help = "First k important interaction in graph", required = False)
args = vars(parser.parse_args()) inFile = args["PPI_network"]
outFile = args["output"]
if not args["cut"]:
cut = -1
else:
cut = args["cut"] G = networkx.Graph()
with open(inFile, "r") as tmp_file:
data = tmp_file.readlines()
for i in range(1,len(data)):
s = data[i].rstrip().split("\t")
if eval(s[15]) >= cut:
G.add_edge(search(s[0]), search(s[1]), weight = eval(s[15])) Transitivity = networkx.transitivity(G)
Clustering = networkx.clustering(G)
Degree_distribution = networkx.degree_histogram(G)
Degree_Centrality = networkx.degree_centrality(G)
Closeness_Centrality = networkx.closeness_centrality(G)
Betweenness_Centrality = networkx.betweenness_centrality(G)
with open(os.path.join(args["output"], "protein_interaction_network_degree_distribution.txt"), "w") as tmp_file:
tmp_file.write("Degree\tNode_Num\n")
for i in range(len(Degree_distribution)):
tmp_file.write(str(i)+"\t"+str(Degree_distribution[i]))
with open(os.path.join(args["output"], "protein_interaction_network_by_cut.txt"), "w") as tmp_file:
tmp_file.write("Node_Num = " + str(len(G.nodes())) + "\n")
tmp_file.write("Edge_Num = " + str(len(G.edges())) + "\n")
tmp_file.write("Node1_Name\tNode2_Name\tWeight\n")
for i in G.edges():
tmp_file.write(name_list[i[0]]+"\t"+name_list[i[1]]+"\t"+str(G[i[0]][i[1]]["weight"])+"\n")
with open(os.path.join(args["output"], "protein_interaction_network_node_degree.txt"), "w") as tmp_file:
tmp_file.write("Node_ID\tNode_Name\tDegree\n")
for i in range(1,len(G)+1):
tmp_file.write(str(i)+"\t"+name_list[i]+"\t")
tmp_file.write(str(G.degree(i))+"\n")
with open(os.path.join(args["output"], "protein_interaction_network_centrality.txt"), "w") as tmp_file:
tmp_file.write("Node_ID\tNode_Name\tDegree_Centrality\t")
tmp_file.write("Closeness_Centrality\tBetweenness_Centrality\n")
for i in range(1,len(G)+1):
tmp_file.write(str(i)+"\t"+name_list[i]+"\t")
tmp_file.write(str(Degree_Centrality[i])+"\t")
tmp_file.write(str(Closeness_Centrality[i])+"\t")
tmp_file.write(str(Betweenness_Centrality[i])+"\n") with open(os.path.join(args["output"], "protein_interaction_network_clustering.txt"), "w") as tmp_file:
tmp_file.write("Node_ID\tProtein_Name\tClustering\n")
for i in range(1,len(G)+1):
tmp_file.write(str(i)+"\t"+name_list[i]+"\t"+str(Clustering[i])+"\n") with open(os.path.join(args["output"], "protein_interaction_network_transitivity.txt"), "w") as tmp_file:
tmp_file.write("Transitivity\n")
tmp_file.write(str(Transitivity)+"\n")

calc_ppi

PPI_network&calc_ppi的更多相关文章

随机推荐

  1. Spark SQL概念学习系列之Spark SQL的简介(一)

    Spark SQL提供在大数据上的SQL查询功能,类似于Shark在整个生态系统的角色,它们可以统称为SQL on Spark. 之前,Shark的查询编译和优化器依赖于Hive,使得Shark不得不 ...

  2. [iOS微博项目 - 1.1] - 设置导航栏主题(统一样式)

    A.导航栏两侧文字按钮 1.需求: 所有导航栏两侧的文字式按钮统一样式 普通样式:橙色 高亮样式:红色 不可用样式:亮灰 阴影:不使用 字体大小:15   github: https://github ...

  3. CSS 酷站

    http://mikkelbang.com/#!videos

  4. 创建类模式(三):创建者(Builder)

    定义 将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示.这使得构件算法和组装方式可以独立应对变化:复用同样的构建算法可以创建不同的表示,不同的构建过程可以复用相同的部件组装方式 ...

  5. 剑指OFFER之矩形覆盖(九度OJ1390)

    题目描述: 我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形.请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法? 输入: 输入可能包含多个测试样例,对于每个测试案例, 输入 ...

  6. ALT(预警)

    1. Alert简介 Alert是一种Oracle系统中的一种机制,它可以监视系统数据库,在规定的情况下给规定用户一个通知,通知可以是邮件或者其他形式,在标注的系统和客户化系统中都是可以定义使用的 2 ...

  7. GCD求最大公约数

    求最大公约数哪个强,果断GCD,非递归版本和递归版本如下: #include<iostream> using namespace std; int gcd(int a, int b){ / ...

  8. js中的if判断十分优美的简洁写法

    本尊混迹猿人类也有5年有余,从最开始的C#到java再到php到至今的python,不能说精通,也算得上是熟悉,对各个语言的语法也算是了解. 虽然目前在开发web程序,了解一些java知识,但是今天在 ...

  9. PHP 支持IMAP

    linux下安装php支持imap 2008-11-26 10:31:10|  分类: linux 学习日志|举报|字号 订阅     第一步:安装apache注:当前目录为/tmp,目录下有http ...

  10. Codeforces Round #277 (Div. 2) E. LIS of Sequence DP

    E. LIS of Sequence Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/486/pr ...