文章MSM_metagenomics(五):共现分析

2024-06-16 23:44

本文主要是介绍文章MSM_metagenomics(五):共现分析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

欢迎大家关注全网生信学习者系列:

  • WX公zhong号:生信学习者
  • Xiao hong书:生信学习者
  • 知hu:生信学习者
  • CDSN:生信学习者2

介绍

本教程是使用一个Python脚本来分析多种微生物(即strains, species, genus等)的共现模式。

数据

大家通过以下链接下载数据:

  • 百度网盘链接:https://pan.baidu.com/s/1f1SyyvRfpNVO3sLYEblz1A
  • 提取码: 请关注WX公zhong号_生信学习者_后台发送 复现msm 获取提取码

Python packages required

  • pandas >= 1.3.5
  • matplotlib >= 3.5.0
  • seaborn >= 0.11.2

Co-presence pattern analysis

使用step_curve_drawer.py 做共线性分析

  • 代码
#!/usr/bin/env python"""
NAME: step_curve_drawer.py
DESCRIPTION: This script is to analyze the co-prsense of multiple species in different categories,by drawing step curves.
"""import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import sys
import argparse
import textwrapdef read_args(args):# This function is to parse argumentsparser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,description = textwrap.dedent('''\This program is to do draw step curves to analyze co-presense of multiple species in different groups.'''),epilog = textwrap.dedent('''\examples:step_curve_drawer.py --abundance_table <abundance_table_w_md.tsv> --variable <variable_name> --species_number <nr_sps> --output <output.svg>'''))parser.add_argument('--abundance_table',nargs = '?',help = 'Input the MetaPhlAn4 abundance table which contains only a group of species one wants to analyze their co-presense state, with metadata being wedged.',type = str,default = None)parser.add_argument('--variable',nargs = '?',help = 'Specify the header of the variable in the metadata table you want to assess. For example, \[Diet] variable columns has three categries - [vegan]/[Flexitarian]/[Omnivore].',type = str,default = None)parser.add_argument('--minimum_abundance',nargs = '?',help = 'Specify the minimum abundance used for determining presense. note: [0, 100] and [0.0] by default',type = float,default = 0.0)parser.add_argument('--species_number',nargs = '?',help = 'Specify the total number of multiple species in the analysis.',type = int)parser.add_argument('--output',nargs = '?',help = 'Specify the output figure name.',type = str,default = None)parser.add_argument('--palette',nargs = '?',help = 'Input a tab-delimited mapping file where values are group names and keys are color codes.',type = str,default = None)return vars(parser.parse_args())class PandasDealer:"""This is an object for dealing pandas dataframe."""def __init__(self, df_):self.df_ = df_def read_csv(self):# Ths fucntion will read tab-delimitted file into a pandas dataframe.return pd.read_csv(self.df_, sep = '\t', index_col = False, low_memory=False)def rotate_df(self):# this function is to rotate the metaphlan-style table into tidy dataframe to ease searching work,df_ = self.read_csv()df_rows_lists = df_.values.tolist()rotated_df_dict = {df_.columns[0]: df_.columns[1:]}for i in df_rows_lists:rotated_df_dict[i[0]] = i[1:]rotated_df = pd.DataFrame.from_dict(rotated_df_dict)return rotated_dfclass CopEstimator:def __init__(self, sub_df_md):self.sub_df_md = sub_df_md # sub_df_md: a subset of dataframe which contains only a group of species one wants to do co-presence analysis.def make_copresense_df(self, factor, total_species_nr, threshold = 0.0):# factor: the factor you want to assess the category percentage.# total_species_nr: specify the total number of species you want to do co-presense analysis.rotated_df = PandasDealer(self.sub_df_md)rotated_df = rotated_df.rotate_df()cols = rotated_df.columns[-total_species_nr: ].to_list() categories = list(set(rotated_df[factor].to_list()))copresense = []cate_name = []ratios = []for c in categories:sub_df = rotated_df[rotated_df[factor] == c]species_group_df = sub_df[cols]species_group_df = species_group_df.apply(pd.to_numeric)species_group_df['total'] = species_group_df[cols].gt(threshold).sum(axis=1)for i in range(1, total_species_nr + 1):ratio = count_non_zero_rows(species_group_df, i)copresense.append(i)cate_name.append(c)ratios.append(ratio)return pd.DataFrame.from_dict({"copresense": copresense,factor: cate_name,"percentage": ratios})def count_non_zero_rows(df_, nr):total_rows = len(df_.index)sub_df = df_[df_['total'] >= nr]ratio = len(sub_df.index)/total_rowsreturn ratioclass VisualTools:def __init__(self, processed_df, factor):self.processed_df = processed_dfself.factor = factordef step_curves(self, opt_name, palette = None):categories = list(set(self.processed_df[self.factor].to_list()))if palette:palette_dict = {i.rstrip().split('\t')[0]: i.rstrip().split('\t')[1] for i in open(palette).readlines()}for c in categories:sub_df = self.processed_df[self.processed_df[self.factor] == c]plt.step(sub_df["percentage"]*100, sub_df["copresense"], label = c, color = palette_dict[c])else:for c in categories:sub_df = self.processed_df[self.processed_df[self.factor] == c]plt.step(sub_df["percentage"]*100, sub_df["copresense"], label = c)plt.title("Number of species in an individual if present")plt.xlabel("Percentage")plt.ylabel("Co-presense")plt.legend(title = self.factor)plt.savefig(opt_name, bbox_inches = "tight")if __name__ == "__main__":pars = read_args(sys.argv)cop_obj = CopEstimator(pars['abundance_table'])p_df = cop_obj.make_copresense_df(pars['variable'], pars['species_number'], pars['minimum_abundance'])vis_obj = VisualTools(p_df, pars['variable'])vis_obj.step_curves(pars['output'], palette = pars['palette'])
  • 用法
usage: step_curve_drawer.py [-h] [--abundance_table [ABUNDANCE_TABLE]] [--variable [VARIABLE]] [--minimum_abundance [MINIMUM_ABUNDANCE]] [--species_number [SPECIES_NUMBER]] [--output [OUTPUT]][--palette [PALETTE]]This program is to do draw step curves to analyze co-presense of multiple species in different groups.optional arguments:-h, --help            show this help message and exit--abundance_table [ABUNDANCE_TABLE]Input the MetaPhlAn4 abundance table which contains only a group of species one wants to analyze their co-presense state, with metadata being wedged.--variable [VARIABLE]Specify the header of the variable in the metadata table you want to assess. For example, [Diet] variable columns has three categries - [vegan]/[Flexitarian]/[Omnivore].--minimum_abundance [MINIMUM_ABUNDANCE]Specify the minimum abundance used for determining presense. note: [0, 100] and [0.0] by default--species_number [SPECIES_NUMBER]Specify the total number of multiple species in the analysis.--output [OUTPUT]     Specify the output figure name.--palette [PALETTE]   Input a tab-delimited mapping file where values are group names and keys are color codes.examples:python step_curve_drawer.py --abundance_table <abundance_table_w_md.tsv> --variable <variable_name> --species_number <nr_sps> --output <output.svg>

为了演示step_curve_drawer.py的使用,我们将绘制基于metaphlan相对丰度表特定于Segatalla copri(之前称为Prevotella copri)的八个谱系:./data/mpa4_pcopri_abundances_md.tsv的共现模式,这些数据来自MSMNon-MSM人群。MSMNon-MSM样本将使用自定义颜色进行标记,颜色分配来自一个颜色映射文件color map file: ./data/copresence_color_map.tsv

python step_curve_drawer.py \--abundance_table mpa_pcopri_abundances_md.tsv \--variable sexual_orientation \--species_number 8 \--palette copresence_color_map.tsv \--output copresence_plot.png

请添加图片描述

这篇关于文章MSM_metagenomics(五):共现分析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1067885

相关文章

[职场] 公务员的利弊分析 #知识分享#经验分享#其他

公务员的利弊分析     公务员作为一种稳定的职业选择,一直备受人们的关注。然而,就像任何其他职业一样,公务员职位也有其利与弊。本文将对公务员的利弊进行分析,帮助读者更好地了解这一职业的特点。 利: 1. 稳定的职业:公务员职位通常具有较高的稳定性,一旦进入公务员队伍,往往可以享受到稳定的工作环境和薪资待遇。这对于那些追求稳定的人来说,是一个很大的优势。 2. 薪资福利优厚:公务员的薪资和

高度内卷下,企业如何通过VOC(客户之声)做好竞争分析?

VOC,即客户之声,是一种通过收集和分析客户反馈、需求和期望,来洞察市场趋势和竞争对手动态的方法。在高度内卷的市场环境下,VOC不仅能够帮助企业了解客户的真实需求,还能为企业提供宝贵的竞争情报,助力企业在竞争中占据有利地位。 那么,企业该如何通过VOC(客户之声)做好竞争分析呢?深圳天行健企业管理咨询公司解析如下: 首先,要建立完善的VOC收集机制。这包括通过线上渠道(如社交媒体、官网留言

打包体积分析和优化

webpack分析工具:webpack-bundle-analyzer 1. 通过<script src="./vue.js"></script>方式引入vue、vuex、vue-router等包(CDN) // webpack.config.jsif(process.env.NODE_ENV==='production') {module.exports = {devtool: 'none

个人博客文章目录索引(持续更新中...)

文章目录 一、Java基础二、Java相关三、MySql基础四、Mybatis基础及源码五、MybatisPlus基础六、Spring基础及源码七、Tomcat源码八、SpringMVC基础及源码   随着文章数量多起来,每次着急翻找半天,而是新申请的域名下来了,决定整理下最近几年的文章目录索引。(红色标记为常检索文章) 一、Java基础 1、Java基础(一):语言概述2、J

Java中的大数据处理与分析架构

Java中的大数据处理与分析架构 大家好,我是免费搭建查券返利机器人省钱赚佣金就用微赚淘客系统3.0的小编,也是冬天不穿秋裤,天冷也要风度的程序猿!今天我们来讨论Java中的大数据处理与分析架构。随着大数据时代的到来,海量数据的存储、处理和分析变得至关重要。Java作为一门广泛使用的编程语言,在大数据领域有着广泛的应用。本文将介绍Java在大数据处理和分析中的关键技术和架构设计。 大数据处理与

段,页,段页,三种内存(RAM)管理机制分析

段,页,段页         是为实现虚拟内存而产生的技术。直接使用物理内存弊端:地址空间不隔离,内存使用效率低。 段 段:就是按照二进制文件的格式,在内存给进程分段(包括堆栈、数据段、代码段)。通过段寄存器中的段表来进行虚拟地址和物理地址的转换。 段实现的虚拟地址 = 段号+offset 物理地址:被分为很多个有编号的段,每个进程的虚拟地址都有段号,这样可以实现虚实地址之间的转换。其实所谓的地

mediasoup 源码分析 (八)分析PlainTransport

mediasoup 源码分析 (六)分析PlainTransport 一、接收裸RTP流二、mediasoup 中udp建立过程 tips 一、接收裸RTP流 PlainTransport 可以接收裸RTP流,也可以接收AES加密的RTP流。源码中提供了一个通过ffmpeg发送裸RTP流到mediasoup的脚本,具体地址为:mediasoup-demo/broadcaste

关于文章“python+百度语音识别+星火大模型+讯飞语音合成的语音助手”报错的修改

前言 关于我的文章:python+百度语音识别+星火大模型+讯飞语音合成的语音助手,运行不起来的问题 文章地址: https://blog.csdn.net/Phillip_xian/article/details/138195725?spm=1001.2014.3001.5501 1.报错问题 如果运行中报错,且报错位置在Xufi_Voice.py文件中的pcm_2_wav,如下图所示

Java并发编程—阻塞队列源码分析

在前面几篇文章中,我们讨论了同步容器(Hashtable、Vector),也讨论了并发容器(ConcurrentHashMap、CopyOnWriteArrayList),这些工具都为我们编写多线程程序提供了很大的方便。今天我们来讨论另外一类容器:阻塞队列。   在前面我们接触的队列都是非阻塞队列,比如PriorityQueue、LinkedList(LinkedList是双向链表,它实现了D

线程池ThreadPoolExecutor类源码分析

Java并发编程:线程池的使用   在前面的文章中,我们使用线程的时候就去创建一个线程,这样实现起来非常简便,但是就会有一个问题:   如果并发的线程数量很多,并且每个线程都是执行一个时间很短的任务就结束了,这样频繁创建线程就会大大降低系统的效率,因为频繁创建线程和销毁线程需要时间。   那么有没有一种办法使得线程可以复用,就是执行完一个任务,并不被销毁,而是可以继续执行其他的任务?