-
Notifications
You must be signed in to change notification settings - Fork 12
/
core.clj
56 lines (50 loc) · 2.16 KB
/
core.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
(ns cljam.io.bam.core
"The core of BAM features."
(:require [clojure.java.io :as cio]
[clojure.string :as cstr]
[cljam.io.bam [common :as common]
[reader :as reader]
[writer :as writer]]
[cljam.io.bam-index :as bai]
[cljam.io.util.lsb :as lsb])
(:import java.util.Arrays
[java.io DataInputStream DataOutputStream IOException FileNotFoundException]
[bgzf4j BGZFInputStream BGZFOutputStream]
cljam.io.bam.reader.BAMReader
cljam.io.bam.writer.BAMWriter))
;; Reading
;; -------
(defn- bam-index
"Load an index file (BAI) for the given BAM file."
[bam-path]
(if-let [bai-path (->> ["$1.bai" ".bai" "$1.BAI" ".BAI"]
(eduction
(comp
(map #(cstr/replace bam-path #"(?i)(\.bam)$" %))
(filter #(.isFile (cio/file %)))))
first)]
(bai/bam-index bai-path)
(throw (FileNotFoundException. (str "Could not find BAM Index file for " bam-path)))))
(defn ^BAMReader reader
"Creates a `cljam.io.bam.BAMReader` instance for the given path."
[f]
(let [rdr (BGZFInputStream. (cio/file f))
data-rdr (DataInputStream. rdr)]
(when-not (Arrays/equals ^bytes (lsb/read-bytes data-rdr 4) (.getBytes ^String common/bam-magic))
(throw (IOException. "Invalid BAM file")))
(let [{:keys [header refs]} (reader/load-headers data-rdr)
index-delay (delay (bam-index f))]
(BAMReader. (.getAbsolutePath (cio/file f))
header refs rdr data-rdr index-delay (.getFilePointer rdr)))))
(defn ^BAMReader clone-reader
"Clones bam reader sharing persistent objects."
[^BAMReader rdr]
(let [bgzf-rdr (BGZFInputStream. (cio/file (.f rdr)))
data-rdr (DataInputStream. bgzf-rdr)]
(.seek bgzf-rdr (.start-pos rdr))
(BAMReader. (.f rdr) (.header rdr) (.refs rdr) bgzf-rdr data-rdr (.index-delay rdr) (.start-pos rdr))))
;; Writing
;; -------
(defn ^BAMWriter writer [f]
(BAMWriter. (.getAbsolutePath (cio/file f))
(DataOutputStream. (BGZFOutputStream. (cio/file f)))))