Debian Codegraph @

Misc/samtobreak.hs

raw
1 {- Calculate contig and scaffold contiguity and correctness metrics.
2 - Written by Shaun Jackman.
3 -}
4
5 import Control.Arrow ((***))
6 import Control.Monad (when)
7 import Data.Bits ((.&.))
8 import Data.ByteString.Lazy.Char8 (ByteString)
9 import qualified Data.ByteString.Lazy.Char8 as S
10 import Data.Char (isDigit)
11 import Data.Function (on)
12 import Data.List (find, findIndex, groupBy, intercalate, partition, sortBy, span)
13 import Data.Maybe (fromJust, fromMaybe)
14 import System.Console.GetOpt
15 import System.Environment (getArgs)
16 import System.Exit (exitFailure, exitSuccess)
17
18 -- Return groups of equivalent elements. Unlike Data.List.groupBy,
19 -- consecutive pairs of elements are compared, and the relation need
20 -- not be transitive.
21 groupBy' rel [] = []
22 groupBy' rel (x:xs) = (x:ys) : groupBy' rel zs
23 where
24 (ys,zs) = groupByAux x xs
25 groupByAux x0 (x:xs) | rel x0 x = (x:ys, zs)
26 where (ys,zs) = groupByAux x xs
27 groupByAux y xs = ([], xs)
28
29 -- Return pairs of elements from a list.
30 pairs :: [a] -> [(a, a)]
31 pairs [] = []
32 pairs (x:y:ys) = (x, y) : pairs ys
33
34 -- Parse an integer from a ByteString.
35 readS :: ByteString -> Int
36 readS s = x where Just (x, _) = S.readInt s
37
38 -- Return the rank of the smallest element x for which the sum of the elements x or larger is at least c.
39 rankSumAtLeast :: Int -> [Int] -> Int
40 rankSumAtLeast c xs = i
41 where
42 i = fromMaybe 0 $ findIndex ((>= c) . snd) $ zip ws $ scanl1 (+) ws
43 ws = sortBy (flip compare) xs
44
45 -- Return the smallest element x for which the sum of the elements x or larger is at least c.
46 sumAtLeast :: Int -> [Int] -> Int
47 sumAtLeast c xs = x
48 where
49 (x, _) = fromMaybe (0, 0) $ find ((>= c) . snd) $ zip ws $ scanl1 (+) ws
50 ws = sortBy (flip compare) xs
51
52 -- Calculate NGx.
53 ngx :: Double -> Int -> [Int] -> Int
54 ngx x g = sumAtLeast $ ceiling $ x * fromIntegral g
55
56 -- Calculate N50.
57 n50 :: [Int] -> Int
58 n50 xs = ngx 0.5 (sum xs) xs
59
60 -- Calculate LGx.
61 lgx :: Double -> Int -> [Int] -> Int
62 lgx x g = rankSumAtLeast $ ceiling $ x * fromIntegral g
63
64 -- Calculate L50.
65 l50 :: [Int] -> Int
66 l50 xs = lgx 0.5 (sum xs) xs
67
68 -- A SAM record.
69 -- qname flag rname pos mapq cigar rnext pnext tlen seq qual
70 data SAM = SAM {
71 qname :: ByteString,
72 flag :: Int,
73 rname :: ByteString,
74 pos :: Int,
75 mapq :: Int,
76 cigar :: ByteString,
77 --rnext :: ByteString,
78 --pnext :: Int,
79 --tlen :: Int,
80 --qseq :: ByteString,
81 --qual :: ByteString
82 seqLength :: Int
83 }
84
85 -- Return whether the unmapped flag is set.
86 isUnmapped :: SAM -> Bool
87 isUnmapped x = flag x .&. 4 /= 0
88
89 -- Return whether the reverse complement flag is set.
90 isRC :: SAM -> Bool
91 isRC x = flag x .&. 16 /= 0
92
93 -- Parse the CIGAR string.
94 readCigar :: ByteString -> [(Int, Char)]
95 readCigar s = map (readS *** S.head) . pairs
96 . S.groupBy ((==) `on` isDigit) $ s
97
98 -- Return the left and right soft-clipping.
99 getSoftClip :: SAM -> (Int, Int)
100 getSoftClip sam = (
101 if elem (snd x) "HS" then fst x else 0,
102 if elem (snd y) "HS" then fst y else 0)
103 where
104 (x, y) = (head xs, last xs)
105 xs = readCigar $ cigar sam
106
107 -- Return the sum of the specified CIGAR elements.
108 cigarLength :: [Char] -> ByteString -> Int
109 cigarLength ops s = sum [n | (n, op) <- readCigar s, op `elem` ops]
110
111 -- Return the length of the query alignment.
112 qLength :: SAM -> Int
113 qLength = cigarLength "IM" . cigar
114
115 -- Return the start position of the query alignment oriented to agree
116 -- with the target.
117 qStart' = fst . getSoftClip
118
119 -- Return the end position of the query alignment oriented to agree
120 -- with the target.
121 qEnd' x = qStart' x + qLength x
122
123 -- Return the start position of the query alignment.
124 qStart :: SAM -> Int
125 qStart x = (if isRC x then snd else fst) $ getSoftClip x
126
127 -- Return the end position of the query alignment.
128 qEnd :: SAM -> Int
129 qEnd x = qStart x + qLength x
130
131 -- Return the length of the target alignment.
132 tLength :: SAM -> Int
133 tLength = cigarLength "DMN" . cigar
134
135 -- Return the start of the target alignment.
136 tStart :: SAM -> Int
137 tStart = pos
138
139 -- Return the end position of the target alignment.
140 tEnd :: SAM -> Int
141 tEnd x = tStart x + tLength x
142
143 -- Return the start position of the target alignment oriented to agree
144 -- with the query. The coordinate system is [-length, 0).
145 tStart' x = if isRC x then 0 - tEnd x else tStart x
146
147 -- Return the end position of the target alignment oriented to agree
148 -- with the query. The coordinate system is [-length, 0).
149 tEnd' x = tStart' x + tLength x
150
151 -- Parse a SAM record.
152 readSAM :: ByteString -> SAM
153 readSAM s = SAM qname (readS flag) rname (readS pos)
154 (readS mapq) cigar lengthQseq
155 where
156 lengthQseq = if S.head cigar == '*'
157 then fromIntegral $ S.length qseq
158 else cigarLength "HIMS" cigar
159 (qname:flag:rname:pos:mapq:cigar:_:_:_:qseq:_) = S.words s
160
161 -- Print a SAM record.
162 showSAM :: SAM -> String
163 showSAM (SAM qname flag rname pos mapq cigar _) = intercalate "\t"
164 [S.unpack qname, show flag, S.unpack rname, show pos,
165 show mapq, S.unpack cigar, "*", "0", "0", "*", "*"]
166
167 -- Exclude alignments that overlap a long alignment by 50%.
168 excludeOverlaps :: [SAM] -> [SAM]
169 excludeOverlaps xs = reverse . foldl accum [] $ xs
170 where
171 accum ys x = if any overlapx ys then ys else x:ys
172 where
173 overlapx y = end - start > (qLength x) `div` 2
174 where
175 start = max (qStart x) (qStart y)
176 end = min (qEnd x) (qEnd y)
177
178 -- Compare the target position.
179 compareTStart :: SAM -> SAM -> Ordering
180 compareTStart a b = compare (rname a, pos a) (rname b, pos b)
181
182 -- Patch gaps in the alignments that are shorter than 500 bp.
183 patchGaps :: Int -> [SAM] -> [SAM]
184 patchGaps optPatchGaps ws = reverse . foldl accum [] $ xs
185 where
186 xs = sortBy compareTStart ws
187 accum [] x = [x]
188 accum (y:ys) x = if isSmallGap y x then x:ys else x:y:ys
189 isSmallGap q p = (rname p, isRC p) == (rname q, isRC q)
190 && max gapt gapq < optPatchGaps
191 where
192 gapt = abs (tStart p - tEnd q)
193 gapq = abs (qStart' p - qEnd' q)
194
195 -- Return whether the pair of aligned contigs are colinear.
196 isColinear :: SAM -> SAM -> Bool
197 isColinear a b = (rname a, isRC a) == (rname b, isRC b)
198 && tStart' a < tStart' b && tEnd' a < tEnd' b
199
200 -- Return pairs of non-colinear alignments.
201 filterNonColinear :: [SAM] -> [(SAM, SAM)]
202 filterNonColinear xs = filter (not . uncurry isColinear)
203 $ zip xs (tail xs)
204
205 -- The command line options.
206 data Opt = OptAlignmentLength Int | OptContigLength Int | OptGenomeSize Int | OptMapq Int | OptPatchGaps Int |
207 OptSAM | OptSAMContigs | OptSAMScaffolds | OptText | OptTSV |
208 OptHelp | OptVersion
209 deriving Eq
210 options :: [OptDescr Opt]
211 options = [
212 Option ['a'] ["alignment-length"] (ReqArg (OptAlignmentLength . read) "N")
213 "exclude alignments with aligned query length shorter than N bp [500]",
214 Option ['l'] ["contig-length"] (ReqArg (OptContigLength . read) "N")
215 "exclude contigs shorter than N bp [200]",
216 Option ['G'] ["genome-size"] (ReqArg (OptGenomeSize . read) "N")
217 "expected genome size used to calculate NG50 [0]",
218 Option ['q'] ["mapq"] (ReqArg (OptMapq . read) "N")
219 "exclude alignments with mapq less than N [10]",
220 Option ['g'] ["patch-gaps"] (ReqArg (OptPatchGaps . read) "N")
221 "join alignments separated by a gap shorter than INT bp (with --text only) [500]",
222 Option ['p'] ["sam"] (NoArg OptSAM)
223 "output contig and scaffold breakpoints in SAM format",
224 Option [] ["sam-contigs"] (NoArg OptSAMContigs)
225 "output contig breakpoints in SAM format",
226 Option [] ["sam-scaffolds"] (NoArg OptSAMScaffolds)
227 "output scaffold breakpoints in SAM format",
228 Option [] ["text"] (NoArg OptText)
229 "output report in plain text format",
230 Option [] ["tsv"] (NoArg OptTSV)
231 "output report in TSV format [default]",
232 Option [] ["help"] (NoArg OptHelp)
233 "display this help and exit",
234 Option [] ["version"] (NoArg OptVersion)
235 "display version information and exit" ]
236 data Format = FormatSAM | FormatSAMContigs | FormatSAMScaffolds | FormatText | FormatTSV deriving Eq
237 data Options = Options {
238 optAlignmentLength :: Int,
239 optContigLength :: Int,
240 optGenomeSize :: Int,
241 optMapq :: Int,
242 optPatchGaps :: Int,
243 optFormat :: Format
244 }
245 defaultOptions = Options {
246 optAlignmentLength = 500,
247 optContigLength = 200,
248 optGenomeSize = 0,
249 optMapq = 10,
250 optPatchGaps = 500,
251 optFormat = FormatTSV
252 }
253
254 -- Parse the command line options.
255 parseOptions :: [Opt] -> Options
256 parseOptions = foldl parseOption defaultOptions
257 where
258 parseOption opt x = case x of
259 OptAlignmentLength n -> opt { optAlignmentLength = n }
260 OptContigLength n -> opt { optContigLength = n }
261 OptGenomeSize n -> opt { optGenomeSize = n }
262 OptMapq n -> opt { optMapq = n }
263 OptPatchGaps n -> opt { optPatchGaps = n }
264 OptSAM -> opt { optFormat = FormatSAM }
265 OptSAMContigs -> opt { optFormat = FormatSAMContigs }
266 OptSAMScaffolds -> opt { optFormat = FormatSAMScaffolds }
267 OptText -> opt { optFormat = FormatText }
268 OptTSV -> opt { optFormat = FormatTSV }
269
270 -- Parse the command line arguments.
271 parseArgs :: IO (Options, [String])
272 parseArgs = do
273 args <- getArgs
274 case getOpt Permute options args of
275 (opts, files, []) -> if OptHelp `elem` opts then help else
276 if OptVersion `elem` opts then putStr version >> exitSuccess else
277 return (parseOptions opts, files)
278 (_, _, errs) -> error (concat errs ++ tryHelp)
279 where
280 help = putStr (usageInfo usage options) >> exitSuccess
281 tryHelp = "Try 'abyss-samtobreak --help' for more information."
282 version = "abyss-samtobreak (ABySS) 2.3.10\n"
283 usage = "Usage: samtobreak [OPTION]... [FILE]...\n\
284 \Calculate contig and scaffold contiguity and correctness metrics.\n"
285
286 -- Calculate contig and scaffold contiguity and correctness metrics.
287 printStats :: Integer -> FilePath -> Options -> IO ()
288 printStats recordIndex path (Options optAlignmentLength optContigLength optGenomeSize optMapq optPatchGaps optFormat) = do
289 s <- S.readFile path
290 when (S.null s) $ error $ "`" ++ path ++ "' is empty"
291
292 let
293 -- Parse the SAM file and discard short contigs.
294 isHeader x = S.head x == '@'
295 (headers, alignments) = span isHeader . S.lines $ s
296 allContigs = map readSAM $ alignments
297
298 -- Calculate the size of the reference genome.
299 sq = filter ((S.pack "@SQ" ==) . head) . map S.words $ headers
300 referenceLengths = map (readS . S.drop 3 . fromJust . find (S.isPrefixOf $ S.pack "LN:")) sq
301 reference_bases = sum referenceLengths
302
303 -- Keep the first (primary) alignment of each contig.
304 primaryContigs = map head . groupBy ((==) `on` qname) $ allContigs
305
306 -- Group the contigs into scaffolds by their name.
307 isScaffoldDelimiter c = c == '_' || c == ':'
308 scaffoldName = S.takeWhile (not . isScaffoldDelimiter) . qname
309 primaryScaffolds = groupBy ((==) `on` scaffoldName) $ primaryContigs
310
311 -- Separate the mapped and unmapped contigs, and discard short contigs.
312 isLong x = seqLength x >= optContigLength
313 (unmapped, mapped) = partition isUnmapped $ filter isLong allContigs
314
315 -- Exclude overlapping alignments.
316 excluded = map excludeOverlaps
317 . groupBy ((==) `on` qname) $ mapped
318 concatExcluded = concat excluded
319 alignedContigLengths = map qLength concatExcluded
320
321 -- Keep long alignments with high mapping quality.
322 isGood x = mapq x >= optMapq && qLength x >= optAlignmentLength
323 good = filter (not . null) . map (filter isGood) $ excluded
324
325 -- Discard contigs that have more than one alignment.
326 -- Group contigs into scaffolds by their name.
327 oneHit = concat . filter ((== 1) . length) $ good
328 scaffs = groupBy ((==) `on` scaffoldName) $ oneHit
329
330 -- Print SAM headers.
331 when (optFormat == FormatSAM || optFormat == FormatSAMContigs || optFormat == FormatSAMScaffolds) (do
332 S.putStr $ S.unlines headers)
333
334 -- Print contig breakpoints.
335 when (optFormat == FormatSAMContigs || optFormat == FormatSAM) (do
336 mapM_ (putStrLn . showSAM) $ concat $ filter ((> 1) . length) $ good
337 )
338
339 -- Print scaffold breakpoints.
340 when (optFormat == FormatSAMScaffolds || optFormat == FormatSAM) (do
341 putStr $ concat
342 $ map (\(a, b) -> unlines [showSAM a, showSAM b])
343 $ concatMap filterNonColinear scaffs
344 )
345
346 -- Exit after printing the breakpoints.
347 when (optFormat == FormatSAM || optFormat == FormatSAMContigs || optFormat == FormatSAMScaffolds) (do
348 exitSuccess)
349
350 let
351 genomeSize = if optGenomeSize > 0 then optGenomeSize else reference_bases
352 ng50 = ngx 0.5 genomeSize
353 lg50 = lgx 0.5 genomeSize
354
355 -- Contig metrics
356 mapped_contigs = length good
357 unmapped_contigs = length unmapped
358 mapped_bases = sum alignedContigLengths
359 unmapped_contig_bases = sum . map seqLength $ unmapped
360 contigLengths = map seqLength $ filter isLong primaryContigs
361 contig_n50 = n50 contigLengths
362 contig_na50 = n50 alignedContigLengths
363 contig_ng50 = ng50 contigLengths
364 contig_nga50 = ng50 alignedContigLengths
365 contig_max = maximum contigLengths
366 contig_aligned_max = maximum alignedContigLengths
367 contig_l50 = l50 contigLengths
368 contig_la50 = l50 alignedContigLengths
369 contig_lg50 = lg50 contigLengths
370 contig_lga50 = lg50 alignedContigLengths
371 contigs = length contigLengths
372 contig_breakpoints = length (concat good) - length good
373
374 -- Scaffold metrics
375 scaffoldLengths = filter (>= optContigLength) . map (sum . map seqLength) $ primaryScaffolds
376 colinearScaffs = concatMap (groupBy' isColinear) scaffs
377 alignedScaffoldLengths = map (sum . map qLength) $ colinearScaffs
378 scaffold_n50 = n50 scaffoldLengths
379 scaffold_na50 = n50 alignedScaffoldLengths
380 scaffold_ng50 = ng50 scaffoldLengths
381 scaffold_nga50 = ng50 alignedScaffoldLengths
382 scaffold_max = maximum scaffoldLengths
383 scaffold_aligned_max = maximum alignedScaffoldLengths
384 scaffold_l50 = l50 scaffoldLengths
385 scaffold_la50 = l50 alignedScaffoldLengths
386 scaffold_lg50 = lg50 scaffoldLengths
387 scaffold_lga50 = lg50 alignedScaffoldLengths
388 scaffolds = length scaffoldLengths
389 total_bases = sum scaffoldLengths
390 scaffold_breakpoints = length colinearScaffs - length scaffs
391 total_breakpoints = contig_breakpoints + scaffold_breakpoints
392
393 when (optFormat == FormatText) (do
394 when (recordIndex > 0) (putChar '\n')
395
396 putStrLn $ "File: " ++ path
397
398 putStr "Number of unmapped contigs: "
399 print unmapped_contigs
400
401 putStr "Total length of unmapped contigs: "
402 print unmapped_contig_bases
403
404 putStr "Number of alignments dropped due to excessive overlaps: "
405 print $ length mapped - length concatExcluded
406
407 putStr "Mapped contig bases: "
408 print mapped_bases
409
410 putStr $ "Contig N50: "
411 print contig_n50
412
413 putStr $ "Contig NA50: "
414 print contig_na50
415
416 putStr $ "Contig NG50: "
417 print contig_ng50
418
419 putStr $ "Contig NGA50: "
420 print contig_nga50
421
422 putStr $ "Contig max: "
423 print contig_max
424
425 putStr $ "Contig aligned max: "
426 print contig_aligned_max
427
428 putStr "Number of break points: "
429 print $ length concatExcluded - length excluded
430
431 putStr $ "Number of Q10 break points longer than " ++ show optAlignmentLength ++ " bp: "
432 print contig_breakpoints
433
434 -- Patch small gaps.
435 when (optPatchGaps > 0) (do
436 let
437 patched = map (patchGaps optPatchGaps) excluded
438 concatPatched = concat patched
439
440 patchedGood = filter (not . null) . map (filter isGood) $ patched
441 concatPatchedGood = concat patchedGood
442
443 putStr "Number of break points after patching gaps shorter than 500 bp: "
444 print $ length concatPatched - length patched
445
446 putStr "Number of Q10 break points longer than 500 bp after gap patching: "
447 print $ length concatPatchedGood - length patchedGood
448 )
449
450 putStr $ "Scaffold N50: "
451 print scaffold_n50
452
453 putStr $ "Scaffold NA50: "
454 print scaffold_na50
455
456 putStr $ "Scaffold NG50: "
457 print scaffold_ng50
458
459 putStr $ "Scaffold NGA50: "
460 print scaffold_nga50
461
462 putStr $ "Scaffold max: "
463 print scaffold_max
464
465 putStr $ "Scaffold aligned max: "
466 print scaffold_aligned_max
467
468 putStr $ "Number of Q10 scaffold breakpoints longer than " ++ show optAlignmentLength ++ " bp: "
469 print scaffold_breakpoints
470
471 putStr "Number of contig and scaffold breakpoints: "
472 print total_breakpoints
473 )
474
475 when (optFormat == FormatTSV) (do
476 when (recordIndex == 0) (
477 putStrLn ("File"
478 ++ "\tContig_N50"
479 ++ "\tContig_NA50"
480 ++ "\tContig_NG50"
481 ++ "\tContig_NGA50"
482 ++ "\tContig_max"
483 ++ "\tContig_aligned_max"
484 ++ "\tScaffold_N50"
485 ++ "\tScaffold_NA50"
486 ++ "\tScaffold_NG50"
487 ++ "\tScaffold_NGA50"
488 ++ "\tScaffold_max"
489 ++ "\tScaffold_aligned_max"
490 ++ "\tContig_breakpoints"
491 ++ "\tScaffold_breakpoints"
492 ++ "\tTotal_breakpoints"
493 ++ "\tContig_L50"
494 ++ "\tContig_LA50"
495 ++ "\tContig_LG50"
496 ++ "\tContig_LGA50"
497 ++ "\tScaffold_L50"
498 ++ "\tScaffold_LA50"
499 ++ "\tScaffold_LG50"
500 ++ "\tScaffold_LGA50"
501 ++ "\tReference_bases"
502 ++ "\tTotal_bases"
503 ++ "\tMapped_bases"
504 ++ "\tUnmapped_contig_bases"
505 ++ "\tContigs"
506 ++ "\tMapped_contigs"
507 ++ "\tUnmapped_contigs"
508 ++ "\tScaffolds"
509 ++ "\talignment-length"
510 ++ "\tcontig-length"
511 ++ "\tmapq"
512 ++ "\tgenome-size")
513 )
514 putStr path
515 putStr $ '\t' : show contig_n50
516 putStr $ '\t' : show contig_na50
517 putStr $ '\t' : show contig_ng50
518 putStr $ '\t' : show contig_nga50
519 putStr $ '\t' : show contig_max
520 putStr $ '\t' : show contig_aligned_max
521 putStr $ '\t' : show scaffold_n50
522 putStr $ '\t' : show scaffold_na50
523 putStr $ '\t' : show scaffold_ng50
524 putStr $ '\t' : show scaffold_nga50
525 putStr $ '\t' : show scaffold_max
526 putStr $ '\t' : show scaffold_aligned_max
527 putStr $ '\t' : show contig_breakpoints
528 putStr $ '\t' : show scaffold_breakpoints
529 putStr $ '\t' : show total_breakpoints
530 putStr $ '\t' : show contig_l50
531 putStr $ '\t' : show contig_la50
532 putStr $ '\t' : show contig_lg50
533 putStr $ '\t' : show contig_lga50
534 putStr $ '\t' : show scaffold_l50
535 putStr $ '\t' : show scaffold_la50
536 putStr $ '\t' : show scaffold_lg50
537 putStr $ '\t' : show scaffold_lga50
538 putStr $ '\t' : show reference_bases
539 putStr $ '\t' : show total_bases
540 putStr $ '\t' : show mapped_bases
541 putStr $ '\t' : show unmapped_contig_bases
542 putStr $ '\t' : show contigs
543 putStr $ '\t' : show mapped_contigs
544 putStr $ '\t' : show unmapped_contigs
545 putStr $ '\t' : show scaffolds
546 putStr $ '\t' : show optAlignmentLength
547 putStr $ '\t' : show optContigLength
548 putStr $ '\t' : show optMapq
549 putStr $ '\t' : show genomeSize
550 putChar '\n'
551 )
552
553 -- Calculate contig and scaffold contiguity and correctness metrics.
554 main :: IO ()
555 main = do
556 (opt, files) <- parseArgs
557 case files of
558 [] -> printStats 0 "/dev/stdin" opt
559 otherwise -> mapM_ (\(recordIndex, path) -> do
560 printStats recordIndex path opt) (zip [0..] files)