<p>Hi, 
I would like to calculate the percent-identity from a CIGAR string from a <a href='http://samtools.sourceforge.net/SAM1.pdf'>BAM</a>/SAM file containing alignments. I want to calculate the PID only for the aligned region, ignoring clipped ends ("H","S"). I can parse the CIGAR in R and get the sums for each letter in the CIGAR, so it's just a conceptual question about the definition and whether or not it is correct:
so given the CIGAR contains characters: "M" (match),"N" (skip),"D" (Deletion),"I"(Insertion), "S" (soft-clip),"H" (hard-clip), of which I ignore "S", "H", and "M" is the total sum of M, N the total of N, etc.:</p>

<p>e.g.: <code>10S 20M5I5D20M 10S</code></p>

<p>Is this a good way of defining the formula?</p>

<pre><code>pid1 := 100 * M / (M+N+I)
</code></pre>

<p>or maybe</p>

<pre><code>pid2 := 100* M / (M+N+I-D)
</code></pre>

<p>the example: pid1 = ~88% but then pid2 = 100% (which wouldn't make much sense).</p>

<p>Related: <a href='http://biostar.stackexchange.com/questions/9358/is-there-any-r-package-to-parse-cigar-element-of-sam-files/17031#17031'>http://biostar.stackexchange.com/questions/9358/is-there-any-r-package-to-parse-cigar-element-of-sam-files/17031#17031</a></p>

<p>Thank you very much</p>

<p>No one seems to have mentioned it, but how about the "NM" tag ("edit distance" in SAM format specification)? I think this is the closest to "mismatches" that can be obtained in a relatively fast way by parsing bam files. One caveat, indels are always going to be a problem when defining identity and I don't know how they are counted in the "NM" tag, perhaps different programs have different ways of counting them.</p>