python運行jackhmmer二進制命令的包裝器類

jackhmmer 是 HMMER 軟件套件中的一個工具,用于進行高敏感度的蛋白質序列比對。HMMER(Hidden Markov Model based on profile)是一套用于分析蛋白質序列的工具,它使用隱藏馬爾可夫模型(HMM)來建模蛋白質家族的多序列比對信息。

以下是 jackhmmer 工具的主要特點和用途:

  1. 迭代比對: jackhmmer 是一個迭代的比對工具,它通過在每一輪比對中更新模型,逐步提高比對的靈敏度。這有助于發現相似性較弱的序列關系。

  2. Profile比對: jackhmmer 使用 Profile HMMs(Profile Hidden Markov Models)來表示蛋白質家族的模型。這種模型不僅考慮了氨基酸在給定位置的分布,還考慮了它們之間的相互關系。

  3. 對比數據庫: jackhmmer 可以用于在大型蛋白質數據庫(如UniProt數據庫)中搜索相似的序列。用戶可以提供一個查詢序列,然后 jackhmmer 將其與數據庫中的序列進行比對,找到相似性較高的序列。

  4. 靈敏度和特異性: jackhmmer 的設計旨在在保持高靈敏度的同時,盡量降低假陽性比對的數量,以提高比對的特異性。

from concurrent import futures
import glob
import os
import subprocess
from typing import Set, Optional, Callable, Mapping, Any, Sequence
from urllib import request
from absl import logging
import contextlib
import tempfile
import shutil
import time@contextlib.contextmanager
def timing(msg: str):logging.info('Started %s', msg)tic = time.time()yieldtoc = time.time()logging.info('Finished %s in %.3f seconds', msg, toc - tic)@contextlib.contextmanager
def tmpdir_manager(base_dir: Optional[str] = None):"""Context manager that deletes a temporary directory on exit."""tmpdir = tempfile.mkdtemp(dir=base_dir)try:yield tmpdirfinally:shutil.rmtree(tmpdir, ignore_errors=True)def _keep_line(line: str, seqnames: Set[str]) -> bool:"""Function to decide which lines to keep."""if not line.strip():return Trueif line.strip() == '//':  # End tagreturn Trueif line.startswith('# STOCKHOLM'):  # Start tagreturn Trueif line.startswith('#=GC RF'):  # Reference Annotation Linereturn Trueif line[:4] == '#=GS':  # Description lines - keep if sequence in list._, seqname, _ = line.split(maxsplit=2)return seqname in seqnameselif line.startswith('#'):  # Other markup - filter outreturn Falseelse:  # Alignment data - keep if sequence in list.seqname = line.partition(' ')[0]return seqname in seqnamesdef truncate_stockholm_msa(stockholm_msa_path: str, max_sequences: int) -> str:"""Reads + truncates a Stockholm file while preventing excessive RAM usage."""seqnames = set()filtered_lines = []with open(stockholm_msa_path) as f:for line in f:if line.strip() and not line.startswith(('#', '//')):# Ignore blank lines, markup and end symbols - remainder are alignment# sequence parts.seqname = line.partition(' ')[0]seqnames.add(seqname)if len(seqnames) >= max_sequences:breakf.seek(0)for line in f:if _keep_line(line, seqnames):filtered_lines.append(line)return ''.join(filtered_lines)class Jackhmmer:"""Python wrapper of the Jackhmmer binary."""def __init__(self,*,binary_path: str,database_path: str,n_cpu: int = 8,n_iter: int = 1,e_value: float = 0.0001,z_value: Optional[int] = None,get_tblout: bool = False,filter_f1: float = 0.0005,filter_f2: float = 0.00005,filter_f3: float = 0.0000005,incdom_e: Optional[float] = None,dom_e: Optional[float] = None,num_streamed_chunks: int = 2,streaming_callback: Optional[Callable[[int], None]] = None):"""Initializes the Python Jackhmmer wrapper.Args:binary_path: The path to the jackhmmer executable.database_path: The path to the jackhmmer database (FASTA format).n_cpu: The number of CPUs to give Jackhmmer.n_iter: The number of Jackhmmer iterations.e_value: The E-value, see Jackhmmer docs for more details.z_value: The Z-value, see Jackhmmer docs for more details.get_tblout: Whether to save tblout string.filter_f1: MSV and biased composition pre-filter, set to >1.0 to turn off.filter_f2: Viterbi pre-filter, set to >1.0 to turn off.filter_f3: Forward pre-filter, set to >1.0 to turn off.incdom_e: Domain e-value criteria for inclusion of domains in MSA/nextround.dom_e: Domain e-value criteria for inclusion in tblout.num_streamed_chunks: Number of database chunks to stream over.streaming_callback: Callback function run after each chunk iteration withthe iteration number as argument."""self.binary_path = binary_pathself.database_path = database_pathself.num_streamed_chunks = num_streamed_chunksif not os.path.exists(self.database_path) and num_streamed_chunks is None:logging.error('Could not find Jackhmmer database %s', database_path)raise ValueError(f'Could not find Jackhmmer database {database_path}')self.n_cpu = n_cpuself.n_iter = n_iterself.e_value = e_valueself.z_value = z_valueself.filter_f1 = filter_f1self.filter_f2 = filter_f2self.filter_f3 = filter_f3self.incdom_e = incdom_eself.dom_e = dom_eself.get_tblout = get_tbloutself.streaming_callback = streaming_callbackdef _query_chunk(self,input_fasta_path: str,database_path: str,max_sequences: Optional[int] = None) -> Mapping[str, Any]:"""Queries the database chunk using Jackhmmer."""#print("in function: _query_chunk")with tmpdir_manager() as query_tmp_dir:sto_path = os.path.join(query_tmp_dir, 'output.sto')# The F1/F2/F3 are the expected proportion to pass each of the filtering# stages (which get progressively more expensive), reducing these# speeds up the pipeline at the expensive of sensitivity.  They are# currently set very low to make querying Mgnify run in a reasonable# amount of time.cmd_flags = [# Don't pollute stdout with Jackhmmer output.'-o', '/dev/null','-A', sto_path,'--noali','--F1', str(self.filter_f1),'--F2', str(self.filter_f2),'--F3', str(self.filter_f3),'--incE', str(self.e_value),# Report only sequences with E-values <= x in per-sequence output.'-E', str(self.e_value),'--cpu', str(self.n_cpu),'-N', str(self.n_iter)]if self.get_tblout:tblout_path = os.path.join(query_tmp_dir, 'tblout.txt')cmd_flags.extend(['--tblout', tblout_path])if self.z_value:cmd_flags.extend(['-Z', str(self.z_value)])if self.dom_e is not None:cmd_flags.extend(['--domE', str(self.dom_e)])if self.incdom_e is not None:cmd_flags.extend(['--incdomE', str(self.incdom_e)])#print("input_fasta_path:",input_fasta_path)cmd = [self.binary_path] + cmd_flags + [input_fasta_path, database_path]#print('cmd:',cmd)logging.info('Launching subprocess "%s"', ' '.join(cmd))process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)with timing(f'Jackhmmer ({os.path.basename(database_path)}) query'):_, stderr = process.communicate()retcode = process.wait()if retcode:raise RuntimeError('Jackhmmer failed\nstderr:\n%s\n' % stderr.decode('utf-8'))# Get e-values treamed_chunks or each target nametbl = ''if self.get_tblout:with open(tblout_path) as f:tbl = f.read()if max_sequences is None:with open(sto_path) as f:sto = f.read()else:sto = truncate_stockholm_msa(sto_path, max_sequences)raw_output = dict(sto=sto,tbl=tbl,stderr=stderr,n_iter=self.n_iter,e_value=self.e_value)return raw_outputdef query(self,input_fasta_path: str,max_sequences: Optional[int] = None) -> Sequence[Mapping[str, Any]]:"""Queries the database using Jackhmmer."""return self.query_multiple([input_fasta_path], max_sequences)[0]def query_multiple(self,input_fasta_paths: Sequence[str],max_sequences: Optional[int] = None,) -> Sequence[Sequence[Mapping[str, Any]]]:"""Queries the database for multiple queries using Jackhmmer."""#print("in function: query_multiple")## 1. 只有一個數據庫文件的代碼,不需要多線程 if self.num_streamed_chunks is None:single_chunk_results = []for input_fasta_path in input_fasta_paths:single_chunk_results.append([self._query_chunk(input_fasta_path, self.database_path, max_sequences)])return single_chunk_results#db_basename = os.path.basename(self.database_path)## 2. 數據庫很大,可以分成幾個文件,并行搜索。通過匿名函數生成數據庫的路徑db_chunk = lambda db_idx: f'{self.database_path}.{db_idx}'#print("input_fasta_paths:",input_fasta_paths)# 多線程運行self._query_chunk函數with futures.ThreadPoolExecutor(max_workers=3) as executor:# chunked_outputs 為列表,每個列表中是一個序列搜索結果的字典chunked_outputs = [[] for _ in range(len(input_fasta_paths))]for fasta_index, input_fasta_path in enumerate(input_fasta_paths):# 對每一個fasta序列,多線程運行self._query_chunkm_futures = {executor.submit(self._query_chunk, input_fasta_path, db_chunk(i)    , max_sequences): i for i in range(1, self.num_streamed_chunks + 1)}  #print("m_futures:")#print(m_futures)# 等待線程結束,寫入數據到chunked_outputsfor future in futures.as_completed(m_futures):data = future.result()chunked_outputs[fasta_index].append(data)return chunked_outputsif __name__ == "__main__":jackhmmer_binary_path  = "/home/zheng/anaconda3/envs/deep_learning/bin/jackhmmer"database_path = "/home/zheng/test/test_database/globins45.fa"input_fasta_paths = ["/home/zheng/test/HBB_HUMAN.fa","/home/zheng/test/HBB_LARRI.fa"]print("創建jackhmmer_runner對象:")jackhmmer_runner = Jackhmmer(binary_path = jackhmmer_binary_path,database_path = database_path,num_streamed_chunks = 1)print("開始搜索同源序列:")# 搜索單個序列的同源序列chunked_outputs = jackhmmer_runner.query(input_fasta_paths[1],3)# 搜索多個序列的同源序列#chunked_outputs = jackhmmer_runner.query_multiple(input_fasta_paths,3)print("chunked_outputs:",chunked_outputs)

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/165181.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/165181.shtml
英文地址,請注明出處:http://en.pswp.cn/news/165181.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

nodejs微信小程序+python+PHP -留學信息查詢系統的設計與實現-安卓-計算機畢業設計

目 錄 摘 要 I ABSTRACT II 目 錄 II 第1章 緒論 1 1.1背景及意義 1 1.2 國內外研究概況 1 1.3 研究的內容 1 第2章 相關技術 3 2.1 nodejs簡介 4 2.2 express框架介紹 6 2.4 MySQL數據庫 4 第3章 系統分析 5 3.1 需求分析 5 3.2 系統可行性分析 5 3.2.1技術可行性&#xff1a;…

543. 二叉樹的直徑 --力扣 --JAVA

題目 給你一棵二叉樹的根節點&#xff0c;返回該樹的 直徑 。 二叉樹的 直徑 是指樹中任意兩個節點之間最長路徑的 長度 。這條路徑可能經過也可能不經過根節點 root 。 兩節點之間路徑的 長度 由它們之間邊數表示。 解題思路 最長長度可以理解為左子樹最長路徑加上右子樹最長…

MySQL錯誤之ONLY_FULL_GROUP_BY

報錯信息&#xff1a; 翻譯&#xff1a; 對該報錯的解釋 所以&#xff0c;實際上該報錯是由于在SQL查詢語句中有group by&#xff0c;而這個包含group by的SQL查詢寫的并不規范導致的&#xff0c;這個ONLY_FULL_GROUP_BY模式開啟之后檢查就會很嚴格&#xff0c;如果select列表…

uniapp為什么能支持多端開發?uniapp底層是怎么做的?

文章目錄 前言uniapp為什么能支持多端開發&#xff1f;uniapp底層是怎么做條件編譯uniapp的語法uniapp如何編譯為不同端的代碼uniapp的底層是如何做平臺特性適配的呢&#xff1f;后言 前言 hello world歡迎來到前端的新世界 &#x1f61c;當前文章系列專欄&#xff1a;uniapp &…

【lua】記錄函數名和參數(為了延后執行)

需求背景 一個服務緩存玩家信息到對象里&#xff0c;通過對象的函數定時同步到數據庫中&#xff0c;如果玩家掉線 清空對象&#xff0c;但是后續步驟導致對象數據需要變更&#xff0c;對象不存在&#xff0c; 就不方便變更了&#xff0c;怎么處理&#xff1f; 方案思考 1.臨…

計算機網絡——路由

文章目錄 1. 前言&#xff1a;2. 路由基礎2.1. 路由的相關概念2.2. 路由的特征2.3. 路由的過程 3 路由協議3.1. 靜態路由&#xff1a;3.2. 動態路由&#xff1a;3.2.1. 距離矢量協議3.2.2. OSPF協議&#xff1a;3.2.2.1.OSPF概述OSPF的工作原理路由計算功能特性 3.2.2.2.OSPF報…

【Kafka】Java整合Kafka

1.引入依賴 <dependency><groupId>org.apache.kafka</groupId><artifactId>kafka-clients</artifactId><version>2.3.1</version></dependency> 2.搭建生產者 package com.wen.kafka;import org.apache.kafka.clients.produ…

Vuejs+ElementUI搭建后臺管理系統框架

文章目錄 1. Vue.js 項目創建1.1 vue-cli 安裝1.2 使用 vue-cli 創建項目1.3 文件/目錄介紹1.4 啟動 Web 服務 2. 集成 Vue Router 前端路由2.1 Vue Router 是什么2.2 集成 Vue Router 方法2.3 使 Vue Router 生效 3. 集成 Vuex 組件3.1 Vuex 是什么3.2 集成 Vuex 方法3.3 使 V…

2023全球數字貿易創新大賽-人工智能元宇宙-4-10

目錄 競賽感悟: 創業的話 好的項目 數字工廠,智慧制造:集群控制的安全問題

dlv 安裝與使用

dlv 安裝 第一步&#xff1a; # git clone https://github.com/go-delve/delve # cd delve # make install 第二步&#xff1a; # ln -s /root/go/bin/dlv /usr/local/bin/dlv 第三步&#xff1a; # dlv version Delve Debugger Version: 1.21.2 Build: d6f215b27b6d8a4e4…

Excel中出現“#NAME?”怎么辦?(文本原因)

excel 單元格出現 #NAME? 錯誤的原因有二&#xff1a; 函數公式輸入不對導致 #NAME? 錯誤。 在單元格中字符串的前面加了號&#xff0c;如下圖中的--GoJG7sEe6RqgTnlUcitA&#xff0c;本身我們想要的是--GoJG7sEe6RqgTnlUcitA&#xff0c;但因為某些不當的操作在前面加了號&…

vue+SpringBoot的圖片上傳

前端VUE的代碼實現 直接粘貼過來element-UI的組件實現 <el-uploadclass"avatar-uploader"action"/uploadAvatar" //這個action的值是服務端的路徑&#xff0c;其他不用改:show-file-list"false":on-success"handleAvatarSuccess"…

萬界星空科技商業開源MES/免費MES/低代碼MES

萬界星空科技商業開源MES可以提供包括制造數據管理、計劃排程管理、生產調度管理、庫存管理、質量管理、人力資源管理、工作中心/設備管理、工具工裝管理、采購管理、成本管理、項目看板管理、生產過程控制、底層數據集成分析、上層數據集成分解等管理模塊&#xff0c;打造一個…

141.【Git版本控制-本地倉庫-遠程倉庫-IDEA開發工具全解版】

Git-深入挖掘 (一)、Git分布式版本控制工具1.目標2.概述(1).開發中的實際常見(2).版本控制器的方式(3).SVN (集中版本控制器)(4).Git (分布版本控制器)(5).Git工作流程圖 (二)、Git安裝與常用命令1.Git環境配置(1).安裝Git的操作(2).Git的配置操作(3).為常用的指令配置別名 (可…

element中el-switch的v-model自定義值

一、問題 element中的el-switch的值默認都是true或false&#xff0c;但是有些時候后端接口該字段可能是0或者1&#xff0c;如果說再轉換一次值&#xff0c;那就有點太費力了。如下所示&#xff1a; <template><el-switchinactive-text"否"active-text&quo…

【Seata源碼學習 】篇四 TM事務管理器是如何開啟全局事務

TM發送 單個或批量 消息 以發送GlobalBeginRequest消息為例 TM在執行攔截器鏈路前將向TC發送GlobalBeginRequest 消息 io.seata.tm.api.DefaultGlobalTransaction#begin(int, java.lang.String) Overridepublic String begin(String applicationId, String transactionServi…

操作系統發展過程--單道批處理系統、多道批處理系統、分時系統、實時系統

一、單道批處理系統 計算機早期&#xff0c;為了能提高利用率&#xff0c;需要盡量保持系統的連續運行&#xff0c;即在處理完一個作業之后&#xff0c;緊接著處理下一個作業&#xff0c;以減少機器的空閑等待時間 1.單道批處理系統的處理過程 為了實現對作業的連續處理&…

51單片機應用從零開始(七)·循環語句(if語句,swtich語句)

51單片機應用從零開始&#xff08;一&#xff09;-CSDN博客 51單片機應用從零開始&#xff08;二&#xff09;-CSDN博客 51單片機應用從零開始&#xff08;三&#xff09;-CSDN博客 51單片機應用從零開始&#xff08;四&#xff09;-CSDN博客 51單片機應用從零開始&#xff08;…

數倉成本下降近一半,StarRocks 存算分離助力云覽科技業務出海

成都云覽科技有限公司傾力打造了鳳凰瀏覽器&#xff0c;專注于為海外用戶提供服務&#xff0c;公司致力于構建一個全球性的數字內容連接入口&#xff0c;為用戶帶來更為優質、高效、個性化的瀏覽體驗。 作為數據驅動的高科技公司&#xff0c;從數據中挖掘價值一直是公司核心任務…

【Spring進階系列丨第四篇】學習Spring中的Bean管理(基于xml配置)

前言 在之前的學習中我們知道&#xff0c;容器是一個空間的概念&#xff0c;一般理解為可盛放物體的地方。在Spring容器通常理解為BeanFactory或者ApplicationContext。我們知道spring的IOC容器能夠幫我們創建對象&#xff0c;對象交給spring管理之后我們就不用手動去new對象。…