文章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

相关文章

Redis主从/哨兵机制原理分析

《Redis主从/哨兵机制原理分析》本文介绍了Redis的主从复制和哨兵机制,主从复制实现了数据的热备份和负载均衡,而哨兵机制可以监控Redis集群,实现自动故障转移,哨兵机制通过监控、下线、选举和故... 目录一、主从复制1.1 什么是主从复制1.2 主从复制的作用1.3 主从复制原理1.3.1 全量复制

Redis主从复制的原理分析

《Redis主从复制的原理分析》Redis主从复制通过将数据镜像到多个从节点,实现高可用性和扩展性,主从复制包括初次全量同步和增量同步两个阶段,为优化复制性能,可以采用AOF持久化、调整复制超时时间、... 目录Redis主从复制的原理主从复制概述配置主从复制数据同步过程复制一致性与延迟故障转移机制监控与维

Redis连接失败:客户端IP不在白名单中的问题分析与解决方案

《Redis连接失败:客户端IP不在白名单中的问题分析与解决方案》在现代分布式系统中,Redis作为一种高性能的内存数据库,被广泛应用于缓存、消息队列、会话存储等场景,然而,在实际使用过程中,我们可能... 目录一、问题背景二、错误分析1. 错误信息解读2. 根本原因三、解决方案1. 将客户端IP添加到Re

Redis主从复制实现原理分析

《Redis主从复制实现原理分析》Redis主从复制通过Sync和CommandPropagate阶段实现数据同步,2.8版本后引入Psync指令,根据复制偏移量进行全量或部分同步,优化了数据传输效率... 目录Redis主DodMIK从复制实现原理实现原理Psync: 2.8版本后总结Redis主从复制实

锐捷和腾达哪个好? 两个品牌路由器对比分析

《锐捷和腾达哪个好?两个品牌路由器对比分析》在选择路由器时,Tenda和锐捷都是备受关注的品牌,各自有独特的产品特点和市场定位,选择哪个品牌的路由器更合适,实际上取决于你的具体需求和使用场景,我们从... 在选购路由器时,锐捷和腾达都是市场上备受关注的品牌,但它们的定位和特点却有所不同。锐捷更偏向企业级和专

Spring中Bean有关NullPointerException异常的原因分析

《Spring中Bean有关NullPointerException异常的原因分析》在Spring中使用@Autowired注解注入的bean不能在静态上下文中访问,否则会导致NullPointerE... 目录Spring中Bean有关NullPointerException异常的原因问题描述解决方案总结

python中的与时间相关的模块应用场景分析

《python中的与时间相关的模块应用场景分析》本文介绍了Python中与时间相关的几个重要模块:`time`、`datetime`、`calendar`、`timeit`、`pytz`和`dateu... 目录1. time 模块2. datetime 模块3. calendar 模块4. timeit

python-nmap实现python利用nmap进行扫描分析

《python-nmap实现python利用nmap进行扫描分析》Nmap是一个非常用的网络/端口扫描工具,如果想将nmap集成进你的工具里,可以使用python-nmap这个python库,它提供了... 目录前言python-nmap的基本使用PortScanner扫描PortScannerAsync异

Oracle数据库执行计划的查看与分析技巧

《Oracle数据库执行计划的查看与分析技巧》在Oracle数据库中,执行计划能够帮助我们深入了解SQL语句在数据库内部的执行细节,进而优化查询性能、提升系统效率,执行计划是Oracle数据库优化器为... 目录一、什么是执行计划二、查看执行计划的方法(一)使用 EXPLAIN PLAN 命令(二)通过 S

性能分析之MySQL索引实战案例

文章目录 一、前言二、准备三、MySQL索引优化四、MySQL 索引知识回顾五、总结 一、前言 在上一讲性能工具之 JProfiler 简单登录案例分析实战中已经发现SQL没有建立索引问题,本文将一起从代码层去分析为什么没有建立索引? 开源ERP项目地址:https://gitee.com/jishenghua/JSH_ERP 二、准备 打开IDEA找到登录请求资源路径位置