Skip to main content
Join the official 2020 Python Developers SurveyStart the survey!

Microbiome classification pipeline

Project description


CCMetagen processes sequence alignments produced with KMA, which implements the ConClave sorting scheme to achieve highly accurate read mappings. The pipeline is fast enough to use the whole NCBI nt collection as reference, facilitating the inclusion of understudied organisms, such as microbial eukaryotes, in metagenome surveys. CCMetagen produces ranked taxonomic results in user-friendly formats that are ready for publication or downstream statistical analyses.

If you this tool, please cite CCMetagen and KMA:

Besides the guidelines below, we also provide a tutorial to reproduce our metagenome clasisfication analyses of the microbiome of wild birds here.

The guidelines below will guide you in using the command-line version of the CCMetagen pipeline.

CCMetagen is also available as a web service at Note that we recommend using this command-line version to analyze data exceeding 1.5Gb.

Requirements and Installation

Make sure you have the dependencies below installed and accessible in your $PATH. The guidelines below are for Unix systems.

  • If you do not have it already, download and install Python 3.6 CCMetagen requires the Python modules pandas (>0.23) and ETE3. The easiest way to install these modules is via conda or pip:

conda install pandas

  • You need a C-compiler and zlib development files to install KMA:

sudo apt-get install libz-dev

  • Download and install KMA:
git clone
cd kma && make

Note - a new version of KMA - v1.3.0 – has been released, featuring higher speed and precision. We recommend that you update KMA to v.1.3.0

  • Krona is required for graphs. To install Krona it in the local folder:
tar xvf KronaTools-2.7.tar 
cd  KronaTools-2.7
./ --prefix . 
  • Then download CCMetagen and add it to your path. You have two options:

Install CCMetagen via git:

git clone

This will download CCMetagen and the tutorial files. You can also just download the python files from this github directory (, and the ones in the ccmetagen folder if you rather avoid downloading all other files.

Then add the CCMetagen python scripts to the path, temporarily or permanently. For example: PATH=$PATH<your_folder>/CCMetagen

To update CCMetagen, go to the CCMetagen folder and type: git pull

Or install CCMetagen via pip:

pip install CCMetagen

This will automatically install the necessary python packages (pandas and ete3), so you can skip that step if you use pip.


Option 1 Download the indexed (ready-to-go) nt database either here or here. Download the file (96GB zipped file, 165GB uncompressed). Unzip the database: unzip ncbi_nt_kma. This database contains the whole in NCBI nucleotide collection (of of Jan 2018), and therefore is suitable to identify a range of microorganisms, including prokaryotes and eukaryotes.

Option 2 We have indexed a more recent version of the ncbi nucleotide collection (June 2019) that does not contain environemntal or artificial sequences. The file can be found here and contains all ncbi nt entries excluding the descendants of environmental eukaryotes (taxid 61964), environmental prokaryotes (48479), unclassified sequences (12908) and artificial sequences (28384).

Option 3: Build your own reference database. Follow the instructions in the KMA website to index the database. It is important that taxids are incorporated in sequence headers for processing with CCMetagen. We provide scripts to rename sequences in the nt database here.

If you want to use the RefSeq database, the format is similar to the one required for Kraken. The Opiniomics blog describes how to download sequences in an adequate format. Note that you still need to build the index with KMA: kma_index -i refseq.fna -o refseq_indexed -NI -Sparse - or kma_index -i refseq.fna -o refseq_indexed -NI -Sparse TG for faster analysis.

Quick Start

  • First map sequence reads (or contigs) to the database with KMA.

For paired-end files:

kma -ipe $SAMPLE_R1 $SAMPLE_R2 -o sample_out_kma -t_db $db -t $th -1t1 -mem_mode -and -apm f

For single-end files:

kma -i $SAMPLE -o sample_out_kma -t_db $db -t $th -1t1 -mem_mode -and

If you want to calculate abundance in reads per million (RPM) or to calculate the proportion of mapped reads, add the flag -ef (extended features):

kma -ipe $SAMPLE_R1 $SAMPLE_R2 -o sample_out_kma -t_db $db -t $th -1t1 -mem_mode -and -apm f -ef


$db is the path to the reference database $th is the number of threads $SAMPLE_R1 is the path to the mate1 of a paired-end metagenome/metatranscriptome sample (fastq or fasta) $SAMPLE_R2 is the path to the mate2 of a paired-end metagenome/metatranscriptome sample (fastq or fasta) $SAMPLE is the path to a single-end metagenome/metatranscriptome file (reads or contigs)

  • Then run CCMetagen: -i $sample_out_kma.res -o results

Where $sample_out_kma.res is alignment results produced by KMA.

Note that if you are running CCMetagen from the local folder (instead of adding it to your path), you may need to add 'python' before CCMetagen: python -i $sample_out_kma.res -o results

Done! This will make an additional quality filter and output a text file with ranked taxonomic classifications and a krona graph file for interactive visualization.

An example of the CCMetagen output can be found here (.csv file) and here (.html file).

In the .csv file, you will find the depth (abundance) of each match. Depth can be estimated in three ways: by counting the number of nucleotides matching the reference sequence (use flag --depth_unit nc, by applying an additional correction for template length (default in KMA and CCMetagen), or by calculating depth in Reads Per Million (RPM, use flag --depth_unit rpm). If you want RPM values, you will need to suply the .mapstats file generated with KMA.

You can adjust the stringency of the taxonomic assignments by adjusting the minimum coverage (--coverage), the minimum abundance (--depth), and the minimum level of sequence similarity (--query_identity). Coverage is the percentage of bases in the reference sequence that is covered by the consensus sequence (your query), it can be over 100% when the consensus sequence is larger than the reference (due to insertions for example).

If you change the default depth unit, we recommend adjusting the minimum abundance (--depth) to remove taxa found in low abundance accordingly. For example, you can use -d 200 (200 nucleotides) when using --depth_unit nc, which is similar to -d 0.2 when using the default '--depth_unit kma' option. If you choose to calculate abundances in RPM, you may want to adjust the minimum abundance according to your sequence depth. For example, to calculate abundances in RPM, and filter out all matches with less than one read per million: -i $sample_out_kma.res -o results -map $sample_out_kma.mapstat --depth_unit rpm --depth 1

If you would like to know the proportion of reads mapped to each template, run kma with the '-ef' flag. This will generate a file with the '.mapstat' extension. Then provide this file to CCMetagen (-map $sample_out_kma.mapstat) and add the flag '-ef y': -i $sample_out_kma.res -o results -map $sample_out_kma.mapstat -ef y

This will filter the .mapstat file, removing the templates that did not pass CCMetagen's quality control, will add the percentage of mapped reads for each template and will output a file with extension 'stats_csv'. It will also output the overall proportion of reads mapped to these templates in the terminal. For more details about the additional columns of this file, please check KMA's manual.

Understanding the ranked taxonomic output of CCMetagen: The taxonomic classifications reflect the sequence similarity between query and reference sequences, according to default or user-defined similarity thresholds. For example, if a match is 97% similar to the reference sequence, the match will not get a species-level classification. If the match is 85% similar to the reference sequence, then the species, genus and family-level classifications will be 'none'. Note that this is different from identifications tagged as unk_x (unknown taxa). These unknowns indicate taxa where higher-rank classifications have not been defined (according to the NCBI taxonomy database), and it is unrelated to sequence similarity.

For a list of options to customize your analyze, type: -h
  • To get the abundance of each taxon, and/or summarize results for multiple samples, use CCMetagen_merge: -i $CCMetagen_out

Where $CCMetagen_out is the folder containing the CCMetagen taxonomic classifications. The results must be in .csv format (default or '--mode text' output of CCMetagen), and these files must end in ".res.csv".

The flag '-t' define the taxonomic level to merge the results. The default is species-level.

You can also filter out specific taxa, at any taxonomic level:

Use flag -kr to keep (k) or remove (r) taxa. Use flag -l to set the taxonomic level for the filtering. Use flag -tlist to list the taxa to keep or remove (separated by comma).

EX1: Filter out bacteria: -i $CCMetagen_out -kr r -l Kingdom -tlist Bacteria

EX2: Filter out bacteria and Metazoa: -i $CCMetagen_out -kr r -l Kingdom -tlist Bacteria, Metazoa

EX3: Merge results at family-level, and remove Metazoa and Viridiplantae taxa at Kingdom level: -i $CCMetagen_out -t Family -kr r -l Kingdom -tlist Metazoa,Viridiplantae -o family_table

For species-level filtering (where there is a space in taxa names), use quotation marks. Ex 4: Keep only Escherichia coli and Candida albicans: -i 05_KMetagen/ -kr k -l Species -tlist "Escherichia coli,Candida albicans"

If you only have one sample, you can also use CMetagen_merge to get one line per taxa.

To see all options, type: -h

This file should look like this.

  • To extract sequences of a given taxon, use CCMetagen_extract_seqs:

This script will produce a fasta file containing all reads assigned to a taxon of interest. Ex: Generate a fasta file containing all sequences that mapped to the genus Eschericha: -iccm $CCMetagen_out -ifrag $sample_out_kma.frag -l Genus -t Eschericha

Where $CCMetagen_out is the .csv file generated with CCMetagen and $sample_out_kma.frag is the .frag file generated with KMA. The frag file needs to be decompressed: gunzip *.frag.gz

For species-level filtering (where there is a space in taxon names), use quotation marks. Ex: Generate a fasta file containing all sequences that mapped to E. coli: -iccm $CCMetagen_out -ifrag $sample_out_kma.frag -l Species -t "Escherichia coli"

Check out our tutorial for an applied example of the CCMetagen pipeline.


  • Error taxid not found. You probably need to update your local ETE3 database, which contains the taxids and lineage information:
from ete3 import NCBITaxa
ncbi = NCBITaxa()
  • TypeError: concat() got an unexpected keyword argument 'sort'. If you get this error, please update the python module pandas:
pip install pandas --upgrade --user
  • WARNING: no NCBI's taxid found for accession [something], this match will not get taxonomic ranks

    This is not an error, this is just a warning indicating that one of your query sequences matchs to a genbank record for which the NCBI taxonomic identifier (taxid) is not known. CCMetagen therefore will not be able to assign taxonomic ranks to this match, but you will still be able to see it in the output file.

  • KeyError: "['Superkingdom' 'Kingdom' 'Phylum' 'Class' 'Order' 'Family' .... ] not in index" Make sure that the output of CCMetagen ends in '.csv'.

  • The results of the at different taxonomic levels do not sum up. As explained above, this script merges all unclassified taxa at a given taxonomic level. For example, if you have 20 matches to the genus Candida, but only 2 matches were classified at the species level, the output of -t Species (default) will only have the abundances of two classified Candida species, while the others will be merged with the "Unclassified" taxa. The output of -t Genus however will contain all 20 matches. If this behaviour is undesirable, one option is to disable the similarity thresholds (use flag -off) - so that all taxonomic levels are reported regardless of their similarity to the reference sequence. Alternatively, you can cluster species at the 'Closest_match' (using the flag --tax_level Closest_match).

Complete option list


usage: [-h] [-m MODE] -i RES_FP [-o OUTPUT_FP]
                    [-r REFERENCE_DATABASE] [-ef EXTENDED_OUTPUT_FILE]
                    [-du DEPTH_UNIT] [-map MAPSTAT] [-d DEPTH] [-c COVERAGE]
                    [-q QUERY_IDENTITY] [-p PVALUE] [-st SPECIES_THRESHOLD]
                    [-gt GENUS_THRESHOLD] [-ft FAMILY_THRESHOLD]
                    [-ot ORDER_THRESHOLD] [-ct CLASS_THRESHOLD]
                    [-pt PHYLUM_THRESHOLD] [-off TURN_OFF_SIM_THRESHOLDS]

optional arguments:
  -h, --help            show this help message and exit
  -m MODE, --mode MODE  what do you want CCMetagen to do? Valid options are
                        'visual', 'text' or 'both': text: parses kma, filters
                        based on quality and output a text file with taxonomic
                        information and detailed mapping information visual:
                        parses kma, filters based on quality and output a
                        simplified text file and a krona html file for
                        visualization both: outputs both text and visual file
                        formats. Default = both
  -i RES_FP, --res_fp RES_FP
                        Path to the KMA result (.res file)
  -o OUTPUT_FP, --output_fp OUTPUT_FP
                        Path to the output file. Default = CCMetagen_out
                        Which reference database was used. Options: UNITE,
                        RefSeq or nt. Default = nt
                        Produce an extended output file that includes the
                        percentage of classified reads. Options: y or n. To
                        use this featire, you need to generate the mapstat
                        file when required unning KMA (use flag -ef), and use
                        it as input in CCMetagen (flag --mapstat). Default = n
  -du DEPTH_UNIT, --depth_unit DEPTH_UNIT
                        Desired unit for Depth(abundance) measurements.
                        Default = kma (KMA default depth, which is the number
                        of nucleotides overlapping each template, divided by
                        the lengh of the template). Alternatively, you can
                        have abundance calculated in Reads Per Million (RPM,
                        option 'rpm'), or simply count the number of
                        nucleotides overlaping the template (option 'nc'). If
                        you use the 'nc' or 'rpm' options, remember to change
                        the default --depth parameter accordingly. Valid
                        options are nc, rpm and kma
  -map MAPSTAT, --mapstat MAPSTAT
                        Path to the mapstat file produced with KMA when using
                        the -ef flag (.mapstat). Required when calculating
                        abundances in RPM or when producing the
  -d DEPTH, --depth DEPTH
                        minimum sequencing depth. Default = 0.2. If you use
                        --depth_unit nc, change this accordingly. For example,
                        -d 200 (200 nucleotides) is similar to -d 0.2 when
                        using the default '--depth_unit kma' option.
  -c COVERAGE, --coverage COVERAGE
                        Minimum coverage. Default = 20 (i.e. 20% of the
                        reference sequence)
  -q QUERY_IDENTITY, --query_identity QUERY_IDENTITY
                        Minimum query identity (Phylum level). Default = 50
  -p PVALUE, --pvalue PVALUE
                        Minimum p-value. Default = 0.05.
                        Species-level similarity threshold. Default = 98.41
  -gt GENUS_THRESHOLD, --genus_threshold GENUS_THRESHOLD
                        Genus-level similarity threshold. Default = 96.31
                        Family-level similarity threshold. Default = 88.51
  -ot ORDER_THRESHOLD, --order_threshold ORDER_THRESHOLD
                        Order-level similarity threshold. Default = 81.21
  -ct CLASS_THRESHOLD, --class_threshold CLASS_THRESHOLD
                        Class-level similarity threshold. Default = 80.91
                        Phylum-level similarity threshold. Default = 0 - not
  -off TURN_OFF_SIM_THRESHOLDS, --turn_off_sim_thresholds TURN_OFF_SIM_THRESHOLDS
                        Turns simularity-based filtering off. Options = y or
                        n. Default = n
  --version             show program's version number and exit

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for CCMetagen, version 1.2.4
Filename, size File type Python version Upload date Hashes
Filename, size CCMetagen-1.2.4-py3-none-any.whl (31.4 kB) File type Wheel Python version py3 Upload date Hashes View
Filename, size CCMetagen-1.2.4.tar.gz (24.2 kB) File type Source Python version None Upload date Hashes View

Supported by

Pingdom Pingdom Monitoring Google Google Object Storage and Download Analytics Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page