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

def read_args(args):
    # This function is to parse arguments

    parser = 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_df

class 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_rows

    return ratio
    

class VisualTools:
    def __init__(self, processed_df, factor):
        self.processed_df = processed_df
        self.factor = factor

    def 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

请添加图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/713164.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

维度建模中的事实表设计原则

维度建模是一种数据仓库设计方法&#xff0c;其核心是围绕业务过程建立事实表和维度表。事实表主要存储与业务过程相关的度量数据&#xff0c;而维度表则描述这些度量数据的属性。 以下是设计事实表时需要遵循的几个重要原则&#xff0c;来源于《维度建模》那本书上&#xff0…

13.docker registry(私有仓库)

docker registry&#xff08;私有仓库&#xff09; 1.从公有仓库中下载镜像比较慢 &#xff0c;比如docker run执行一个命令假设本地不存在的镜像&#xff0c;则会去共有仓库进行下载。 2.如果要是2台机器之间进行拷贝&#xff0c;则拷贝的是完整的镜像更消耗空间。 3.如果1个…

python数据分析-糖尿病数据集数据分析预测

一、研究背景和意义 糖尿病是美国最普遍的慢性病之一&#xff0c;每年影响数百万美国人&#xff0c;并对经济造成重大的经济负担。糖尿病是一种严重的慢性疾病&#xff0c;其中个体失去有效调节血液中葡萄糖水平的能力&#xff0c;并可能导致生活质量和预期寿命下降。。。。 …

docker 简单在线安装教程

1、配置阿里镜像源 wget https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo -O /etc/yum.repos.d/docker-ce.repo 2、指定版本安装docker 本次制定安装 docker 服务版本、客户端版本都为&#xff1a; 19.03.14-3.el7 yum -y install docker-ce-19.03.14-3.e…

【python】tkinter GUI开发: 多行文本Text,单选框Radiobutton,复选框Checkbutton,画布canvas的应用实战详解

✨✨ 欢迎大家来到景天科技苑✨✨ &#x1f388;&#x1f388; 养成好习惯&#xff0c;先赞后看哦~&#x1f388;&#x1f388; &#x1f3c6; 作者简介&#xff1a;景天科技苑 &#x1f3c6;《头衔》&#xff1a;大厂架构师&#xff0c;华为云开发者社区专家博主&#xff0c;…

【Spine学习06】之IK约束绑定,制作人物待机动画,图表贝塞尔曲线优化动作

引入IK约束的概念&#xff1a; 约束目标父级 被约束骨骼子集 这样理解更好&#xff0c;约束目标可以控制被约束的两个骨骼运作 IK约束绑定过程中呢&#xff0c;如果直接绑定最下面的脚掌骨骼会发生偏移&#xff0c;所以在开始处理IK之前&#xff0c;需要先设置一个ROOT结点下的…

采煤vr事故灾害应急模拟救援训练降低生命财产损失

在化工工地&#xff0c;设备繁多、环境复杂&#xff0c;潜藏着众多安全隐患&#xff0c;稍有不慎便可能引发安全事故。为了保障工地的安全&#xff0c;我们急需一套全面、高效的安全管理解决方案。web3d开发公司深圳华锐视点研发的工地安全3D模拟仿真隐患排查系统&#xff0c;正…

hugo-magic主题使用教程(一)

前提条件 以下教程以windows10为例操作终端使用git bash魔法上网的前提下 下载hugo https://github.com/gohugoio/hugo/releases/download/v0.127.0/hugo_extended_0.127.0_windows-amd64.zip解压到任意目录,然后将目录添加到系统环境变量 如图 (windows)打开cmd 输入 hugo …

Superset 二次开发之Git篇 git cherry-pick

Cherry-Pick 命令是 Git 中的一种功能&#xff0c;用于将特定的提交&#xff08;commit&#xff09;从一个分支应用到另一个分支。它允许你选择性地应用某些提交&#xff0c;而不是合并整个分支。Cherry-Pick 非常适合在需要将特定更改移植到其他分支时使用&#xff0c;例如从开…

为什么用SDE(随机微分方程)来描述扩散过程【论文精读】

为什么用SDE(随机微分方程)来描述扩散过程【论文精读】 B站视频&#xff1a;为什么用SDE(随机微分方程)来描述扩散过程 论文&#xff1a;Score-Based Generative Modeling through Stochastic Differential Equations 地址&#xff1a;https://doi.org/10.48550/arXiv.2011.13…

单调栈(续)、由斐波那契数列讲述矩阵快速降幂技巧

在这里先接上一篇文章单调栈&#xff0c;这里还有单调栈的一道题 题目一&#xff08;单调栈续&#xff09; 给定一个数组arr&#xff0c; 返回所有子数组最小值的累加和 就是一个数组&#xff0c;有很多的子数组&#xff0c;每个数组肯定有一个最小值&#xff0c;要把所有子…

享元和代理模式

文章目录 享元模式1.引出享元模式1.展示网站项目需求2.传统方案解决3.问题分析 2.享元模式1.基本介绍2.原理类图3.外部状态和内部状态4.类图5.代码实现1.AbsWebSite.java 抽象的网站2.ConcreteWebSite.java 具体的网站&#xff0c;type属性是内部状态3.WebSiteFactory.java 网站…

《C语言》动态内存管理

文章目录 一、动态内存分配二、关于动态内存开辟的函数1、malloc2、free3、calloc4、realloc 三、常见的动态内存的错误1、对NULL指针的解引用操作2、对动态开辟空间的越界访问3、对非动态开辟内存使用free释放4、释放free释放一块动态开辟的内存的一部分5、对同一块动态内存多…

Ubuntu基础-VirtualBox安装增强功能

目录 零. 前言 一. 安装 1.点击安装增强功能 2.点击光盘图标 3.复制到新文件夹 4.运行命令 5.重启系统 6.成果展示 二. 打开共享 1.共享粘贴 ​编辑2.共享文件夹 三.总结 安装步骤 打开共享粘贴功能&#xff1a; 打开共享文件夹功能&#xff1a; 零. 前言 在使用…

设计模式-代理模式Proxy(结构型)

代理模式&#xff08;Proxy&#xff09; 代理模式是一种结构型模式&#xff0c;它可以通过一个类代理另一个类的功能。代理类持有被代理类的引用地址&#xff0c;负责将请求转发给代理类&#xff0c;并且可以在转发前后做一些处理 图解 角色 抽象主题&#xff08;Subject&…

upload-labs第九关教程

upload-labs第九关教程 一、源代码分析代码审计::$DATA介绍 二、绕过分析特殊字符::$data绕过上传eval.php使用burpsuite抓包进行修改放包&#xff0c;查看是否上传成功使用中国蚁剑进行连接 一、源代码分析 代码审计 $is_upload false; $msg null; if (isset($_POST[submi…

抖音a_bogus,mstoken爬虫逆向补环境2024-06-15最新版

抖音a_bogus,mstoken爬虫逆向补环境2024-06-15最新版 接口及参数 打开网页版抖音&#xff0c;右键视频进入详情页。F12打开控制台筛选detail&#xff0c;然后刷新网页&#xff0c;找到请求。可以发现我们本次的参数目标a_bogus&#xff0c;msToken在cookie中可以获得&#xf…

无公网ip、服务器无法上网如何实现外网访问

在ipv4的大环境下&#xff0c;公网ip和车牌号一样抢手&#xff0c;一个固定公网ip价格非常昂贵&#xff0c;中小企业承担不起&#xff0c;也不愿意在上面投入&#xff1b;同时勒索病毒日益猖獗&#xff0c;企业信息化负责人为了保证数据安全性&#xff0c;干脆禁止服务器上外网…

分布式微服务: springboot底层机制实现

springboot底层机制实现 搭建SpringBoot底层机制开发环境ConfigurationBean会发生什么,并分析机制提出问题: SpringBoot 是怎么启动Tomcat, 并可以支持访问Controller源码分析: SpringApplication.run()SpringBoot的debug流程 实现SpringBoot底层机制[Tomcat启动分析 Spring容…

在向量数据库中存储多模态数据,通过文字搜索图片

在向量数据中存储多模态数据&#xff0c;通过文字搜索图片&#xff0c;Chroma 支持文字和图片&#xff0c;通过 OpenClip 模型对文字以及图片做 Embedding。本文通过 Chroma 实现一个文字搜索图片的功能。 OpenClip CLIP&#xff08;Contrastive Language-Image Pretraining&…