forked from samtools/hts-specs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CRAMv3.tex
3088 lines (2509 loc) · 121 KB
/
CRAMv3.tex
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
%&pdfLaTeX
% !TEX encoding = UTF-8 Unicode
\documentclass[a4paper]{article}
\usepackage{ifxetex}
\ifxetex
\usepackage{fontspec}
\setmainfont[Mapping=tex-text]{STIXGeneral}
\else
\usepackage[T1]{fontenc}
\usepackage[latin1]{inputenc}
\fi
\usepackage{textcomp}
\usepackage{graphicx}
\usepackage{array}
\usepackage{fixltx2e}
\usepackage{amssymb}
\usepackage{fancyhdr}
\usepackage{amsmath}
\usepackage{algpseudocode}
\usepackage{threeparttable}
\usepackage{tikz}
\usetikzlibrary{positioning,shapes.multipart}
\usetikzlibrary{decorations.pathreplacing}
\renewcommand{\headrulewidth}{0pt}
\renewcommand{\footrulewidth}{0pt}
\newcommand\bits{\,\mbox{bits}}
\newcommand\MB{\,\mbox{MB}}
\setlength{\parindent}{0cm}
\setlength{\parskip}{0.18cm}
\usepackage[hmargin=2cm,vmargin=2.5cm,bindingoffset=0.0cm]{geometry}
\usepackage[pdfborder={0 0 0}]{hyperref}
\begin{document}
\input{CRAMv3.ver}
\title{CRAM format specification (version 3.0)}
\author{[email protected]}
\date{\headdate}
\maketitle
\begin{quote}\small
The master version of this document can be found at
\url{https://github.com/samtools/hts-specs}.\\
This printing is version~\commitdesc\ from that repository,
last modified on the date shown above.
\end{quote}
\begin{center}
\textit{license: Apache 2.0}
\end{center}
\vspace*{1em}
\section{\textbf{Overview}}
This specification describes the CRAM 3.0 format.
CRAM has the following major objectives:
\begin{enumerate}
\item Significantly better lossless compression than BAM
\item Full compatibility with BAM
\item Effortless transition to CRAM from using BAM files
\item Support for controlled loss of BAM data
\end{enumerate}
The first three objectives allow users to take immediate advantage of the CRAM
format while offering a smooth transition path from using BAM files. The fourth
objective supports the exploration of different lossy compression strategies and
provides a framework in which to effect these choices. Please note that the CRAM
format does not impose any rules about what data should or should not be preserved.
Instead, CRAM supports a wide range of lossless and lossy data preservation strategies
enabling users to choose which data should be preserved.
Data in CRAM is stored either as CRAM records or using one of the general purpose
compressors (gzip, bzip2). CRAM records are compressed using a number of different
encoding strategies. For example, bases are reference compressed by encoding base
differences rather than storing the bases themselves.\footnote{Markus Hsi-Yang Fritz,
Rasko Leinonen, Guy Cochrane, and Ewan Birney,
\textbf{Efficient storage of high throughput DNA sequencing data using reference-based compression},
{\sl Genome Res.}~2011~21: 734--740;
\href{http://dx.doi.org/doi:10.1101/gr.114819.110}{doi:10.1101/gr.114819.110};
{\sc pmid:}21245279.}
\section{\textbf{Data types}}
CRAM specification uses logical data types and storage data types; logical data
types are written as words (e.g. int) while physical data types are written using
single letters (e.g. i). The difference between the two is that storage data types
define how logical data types are stored in CRAM. Data in CRAM is stored either
as bits or bytes. Writing values as bits and bytes is described in detail
below.
\subsection{\textbf{Logical data types}}
\begin{description}
\item[Byte]\ \newline
Signed byte (8 bits).
\item[Integer]\ \newline
Signed 32-bit integer.
\item[Long]\ \newline
Signed 64-bit integer.
\item[Array]\ \newline
An array of any logical data type: array\texttt{<}type\texttt{>}
\end{description}
% \begin{tabular}{ll}
% \textbf{Byte} & Signed byte (8 bits). \\
% \\
% \textbf{Integer} & Signed 32-bit integer. \\
% \\
% \textbf{Long} & Signed 64-bit integer. \\
% \\
% \textbf{Array} & An array of any logical data type: \texttt{<}type\texttt{>}[ ] \\
% \end{tabular}
\subsection{\textbf{Writing bits to a bit stream}}
A bit stream consists of a sequence of 1s and 0s. The bits are written most significant
bit first where new bits are stacked to the right and full bytes on the left are
written out. In a bit stream the last byte will be incomplete if less than 8 bits
have been written to it. In this case the bits in the last byte are shifted to
the left.
\subsubsection*{Example of writing to bit stream}
Let's consider the following example. The table below shows a sequence of write
operations:
\begin{tabular}{|l|l|l|l|l|}
\hline
\textbf{Operation order} & \textbf{Buffer state before} & \textbf{Written bits} & \textbf{Buffer state after} & \textbf{Issued bytes}\tabularnewline
\hline
1 & 0x0 & 1 & 0x1 & -\tabularnewline
\hline
2 & 0x1 & 0 & 0x2 & -\tabularnewline
\hline
3 & 0x2 & 11 & 0xB & -\tabularnewline
\hline
4 & 0xB & 0000 0111 & 0x7 & 0xB0\tabularnewline
\hline
\end{tabular}
After flushing the above bit stream the following bytes are written: 0xB0 0x70.
Please note that the last byte was 0x7 before shifting to the left and became 0x70
after that:
\texttt{> echo "obase=16; ibase=2; 00000111" \textbar{} bc\\
7\\
\\
> echo "obase=16; ibase=2; 01110000" \textbar{} bc\\
70}
And the whole bit sequence:
\texttt{> echo "obase=2; ibase=16; B070" \textbar{} bc\\
1011000001110000}
When reading the bits from the bit sequence it must be known that only 12 bits
are meaningful and the bit stream should not be read after that.
\subsubsection*{Note on writing to bit stream}
When writing to a bit stream both the value and the number of bits in the value
must be known. This is because programming languages normally operate with bytes
(8 bits) and to specify which bits are to be written requires a bit-holder, for
example an integer, and the number of bits in it. Equally, when reading a value
from a bit stream the number of bits must be known in advance. In case of prefix
codes (e.g. Huffman) all possible bit combinations are either known in advance
or it is possible to calculate how many bits will follow based on the first few
bits. Alternatively, two codes can be combined, where the first contains the number
of bits to read.
\subsection{\textbf{Writing bytes to a byte stream}}
\label{subsec:writing-bytes}
The interpretation of byte stream is straightforward. CRAM uses \emph{little endianness}
for bytes when applicable and defines the following storage data types:
\begin{description}
\item[Boolean (bool)]\ \newline
Boolean is written as 1-byte with 0x0 being `false' and 0x1 being `true'.
\item[Integer (int32)]\ \newline
Signed 32-bit integer, written as 4 bytes in little-endian byte order.
\item[Long (int64)]\ \newline
Signed 64-bit integer, written as 8 bytes in little-endian byte order.
\item[ITF-8 integer (itf8)]\ \newline
This is an alternative way to write an integer value. The idea is similar to UTF-8
encoding and therefore this encoding is called ITF-8 (Integer Transformation Format
- 8 bit).
The most significant bits of the first byte have special meaning and are called
`prefix'. These are 0 to 4 true bits followed by a 0. The number of 1's denote
the number of bytes to follow. To accommodate 32 bits such representation requires
5 bytes with only 4 lower bits used in the last byte 5.
\item[LTF-8 long (ltf8)]\ \newline
See ITF-8 for more details. The only difference between ITF-8 and LTF-8 is the
number of bytes used to encode a single value. To do so 64 bits are required and
this can be done with 9 byte at most with the first byte consisting of just 1s
or 0xFF value.
\item[{Array (array\texttt{<}type\texttt{>})}]\ \newline
A variable sized array with an explicitly written dimension.
Array length is written first as integer (itf8), followed by the elements of the array.
Implicit or fixed-size arrays are also used, written as \textit{type}\texttt{[ ]} or \textit{type}\texttt{[4]} (for example).
These have no explicit dimension included in the file format and instead rely on the specification itself to document the array size.
\item[{Encoding}]\ \newline
Encoding is a data type that specifies how data series have been compressed. Encodings
are defined as encoding\texttt{<}type\texttt{>} where the type is a logical data
type as opposed to a storage data type.
An encoding is written as follows. The first integer (itf8) denotes the codec id
and the second integer (itf8) the number of bytes in the following encoding-specific
values.
Subexponential encoding example:
\begin{tabular}{|l|l|l|}
\hline
\textbf{Value} & \textbf{Type} & \textbf{Name}\tabularnewline
\hline
0x7 & itf8 & codec id\tabularnewline
\hline
0x2 & itf8 & number of bytes to follow\tabularnewline
\hline
0x0 & itf8 & offset\tabularnewline
\hline
0x1 & itf8 & K parameter\tabularnewline
\hline
\end{tabular}
The first byte ``0x7'' is the codec id.
The next byte ``0x2'' denotes the length of the bytes to follow (2).
The subexponential encoding has 2 parameters: integer (itf8) offset and integer (itf8) K.
offset = 0x0 = 0
K = 0x1 = 1
\item[{Map}]\ \newline
A map is a collection of keys and associated values. A map with N keys is written
as follows:
\begin{tabular}{|l|l|l|l|l|l|l|l|}
\hline
size in bytes & N & key 1 & value 1 & key ... & value ... & key N & value N\tabularnewline
\hline
\end{tabular}
Both the size in bytes and the number of keys are written as integer (itf8). Keys
and values are written according to their data types and are specific to each map.
\item[String]\ \newline
A string is represented as byte arrays using UTF-8 format. Read names, reference
sequence names and tag values with type `Z' are stored as UTF-8.
\end{description}
\section{\textbf{Encodings }}
Encoding is a data structure that captures information about compression details
of a data series that are required to uncompress it. This could be a set of constants
required to initialize a specific decompression algorithm or statistical properties
of a data series or, in case of data series being stored in an external block,
the block content id.
Encoding notation is defined as the keyword `encoding' followed by its data type
in angular brackets, for example `encoding\texttt{<}byte\texttt{>}' stands for
an encoding that operates on a data series of data type `byte'.
Encodings may have parameters of different data types, for example the EXTERNAL
encoding has only one parameter, integer id of the external block. The following
encodings are defined:
\begin{tabular}{|l|l|>{\raggedright}p{155pt}|>{\raggedright}p{160pt}|}
\hline
\textbf{Codec} & \textbf{ID} & \textbf{Parameters} & \textbf{Comment}\tabularnewline
\hline
NULL & 0 & none & series not preserved\tabularnewline
\hline
EXTERNAL & 1 & int block content id & the block content identifier used to associate
external data blocks with data series\tabularnewline
\hline
Deprecated (GOLOMB) & 2 & int offset, int M & Golomb coding\tabularnewline
\hline
HUFFMAN & 3 & array\texttt{<}int\texttt{>}, array\texttt{<}int\texttt{>} & coding with int/byte values\tabularnewline
\hline
BYTE\_ARRAY\_LEN & 4 & encoding\texttt{<}int\texttt{>} array length, encoding\texttt{<}byte\texttt{>}
bytes & coding of byte arrays with array length\tabularnewline
\hline
BYTE\_ARRAY\_STOP & 5 & byte stop, int external block\linebreak{}
content id & coding of byte arrays with a stop value \tabularnewline
\hline
BETA & 6 & int offset, int number of bits & binary coding\tabularnewline
\hline
SUBEXP & 7 & int offset, int K & subexponential coding\tabularnewline
\hline
Deprecated (GOLOMB\_RICE) & 8 & int offset, int log$_{\text{2}}$m & Golomb-Rice coding\tabularnewline
\hline
GAMMA & 9 & int offset & Elias gamma coding\tabularnewline
\hline
\end{tabular}
See section~\ref{sec:encodings} for more detailed descriptions of all the above coding algorithms and their parameters.
\section{\textbf{Checksums}}
The checksumming is used to ensure data integrity. The following checksumming algorithms are used in CRAM.
\subsection{\textbf{CRC32}}
This is a cyclic redundancy checksum 32-bit long with the polynomial 0x04C11DB7. Please refer to \href{http://www.itu.int/rec/recommendation.asp?type=folders&lang=e&parent=T-REC-V.42}{ITU-T V.42} for more details. The value of the CRC32 hash function is written as an integer.
\subsection{\textbf{CRC32 sum}}
CRC32 sum is a combination of CRC32 values by summing up all individual CRC32 values modulo 2\textsuperscript{32}.
\section{\textbf{File structure}}
The overall CRAM file structure is described in this section. Please refer to other
sections of this document for more detailed information.
A CRAM file consists of a fixed length file definition, followed by a CRAM header container,
then one or more data containers, and finally a special end-of-file container.
\begin{center}
\begin{tikzpicture}[
every node/.style={scale=1.0},
boxes/.style={rectangle split,rectangle split parts=#1,draw,rectangle split horizontal,text width=5em,align=center,minimum height=1cm,fill=black!5,on grid},
notes/.style={text width=20em,align=center,minimum height=1cm,on grid},
]
\node (file) [boxes=6] {
\nodepart{one}File definition
\nodepart[text width=8em]{two}CRAM Header Container
\nodepart{three}Data Container
\nodepart{four}...
\nodepart{five}Data Container
\nodepart[text width=8em]{six}CRAM EOF Container
};
\end{tikzpicture}
Figure 1: A CRAM file consists of a file definition, followed by a header container, then other containers.
\end{center}
Containers consist of one or more blocks. The first container, called the CRAM header container,
is used to store a textual header as described in the SAM specification (see the section 7.1).
\begin{center}
\begin{tikzpicture}[
every node/.style={scale=1.0},
boxes/.style={rectangle split,rectangle split parts=#1,draw,rectangle split horizontal,text width=5em,align=center,minimum height=1cm,fill=black!5,on grid},
notes/.style={text width=20em,align=center,minimum height=1cm,on grid},
]
\node (file) [boxes=6] {
\nodepart{one}File definition
\nodepart[text width=8em]{two}CRAM Header Container
\nodepart{three}Data Container
\nodepart{four}...
\nodepart{five}Data Container
\nodepart[text width=8em]{six}CRAM EOF Container
};
\node (header) [boxes=2,below=1 of file.three south, text width=15em] {
\nodepart{one}Block 1:\break
CRAM Header\break
(optionally compressed)
\nodepart{two}Optional Block 2:\break
nul padding bytes\break
(uncompressed)
};
\draw (file.one split south) to (header.north west);
\draw (file.two split south) to (header.north east);
\end{tikzpicture}
Figure 2: The the first container holds the CRAM header text.
\end{center}
Each container starts with a container header structure followed by
one or more blocks.
The first block in each container is the compression header block
giving details of how to decode data in subsequent blocks.
Each block starts with a block header structure followed by the block
data.
\begin{center}
\begin{tikzpicture}[
every node/.style={scale=1.0},
boxes/.style={rectangle split,rectangle split parts=#1,draw,rectangle split horizontal,text width=5em,align=center,minimum height=1cm,fill=black!5,on grid},
notes/.style={text width=20em,align=center,minimum height=1cm,on grid},
]
\node (file) [boxes=6] {
\nodepart{one}File definition
\nodepart[text width=8em]{two}CRAM Header Container
\nodepart{three}Data Container
\nodepart{four}...
\nodepart{five}Data Container
\nodepart[text width=8em]{six}CRAM EOF Container
};
\node (container) [boxes=5,below=1 of file.three south,text width=8em] {
\nodepart{one}Container Header structure
\nodepart{two}Compression Header Block
\nodepart[text width=4em]{three}Block 1
\nodepart[text width=3em]{four}...
\nodepart[text width=4em]{five}Block M
};
\draw (file.two split south) to (container.north west);
\draw (file.three split south) to (container.north east);
\node (blocks) [boxes=2,below=1 of container.two south,text width=6em] {
\nodepart{one}Block Header structure
\nodepart{two}Block data
};
\draw (container.one split south) to (blocks.north west);
\draw (container.two split south) to (blocks.north east);
\end{tikzpicture}
Figure 3: Containers as a series of blocks
\end{center}
The blocks after the compression header are organised logically into slices. One
slice may contain, for example, a contiguous region of alignment data. Slices begin
with a slice header block and are followed by one or more data blocks.
It is these data blocks which hold the primary bulk of CRAM data.
The data blocks are further subdivided into a core data block and one or more external data blocks.
\begin{center}
\begin{tikzpicture}[
every node/.style={scale=1.0},
boxes/.style={rectangle split,rectangle split parts=#1,draw,rectangle split horizontal,text width=5em,align=center,minimum height=1cm,fill=black!5,on grid},
notes/.style={text width=20em,align=center,minimum height=1cm,on grid},
]
\node (file) [boxes=6] {
\nodepart{one}File definition
\nodepart[text width=8em]{two}CRAM Header Container
\nodepart{three}Data Container
\nodepart{four}...
\nodepart{five}Data Container
\nodepart[text width=8em]{six}CRAM EOF Container
};
\node (container) [boxes=9,below=1 of file.three south,text width=8em] {
\nodepart{one}Container Header structure
\nodepart{two}Compression Header Block
\nodepart[text width=3em]{three}Block
\nodepart[text width=2em]{four}...
\nodepart[text width=3em]{five}Block
\nodepart[text width=7em]{six}. . .
\nodepart[text width=3em]{seven}Block
\nodepart[text width=2em]{eight}...
\nodepart[text width=3em]{nine}Block
};
\draw (file.two split south) to (container.north west);
\draw (file.three split south) to (container.north east);
\draw[decoration={brace,mirror,amplitude=5pt,raise=2pt},decorate]
(container.two split south) to (container.five split south);
\node [below=0.2 of container.four south] {Slice 1};
\draw[decoration={brace,mirror,amplitude=5pt,raise=2pt},decorate]
(container.six split south) to (container.south east);
\node [below=0.2 of container.eight south] {Slice N};
\node (slice) [boxes=5,below=1 of container.four south, text width=6.5em] {
\nodepart{one}Slice Header Block
\nodepart{two}Core Data Block
\nodepart{three}External Data Block 1
\nodepart{four}...
\nodepart{five}External Data Block M
};
\draw (container.two split south) to (slice.north west);
\draw (container.five split south) to (slice.north east);
\end{tikzpicture}
Figure 4: Slices formed from a series of concatenated blocks
\end{center}
\section{\textbf{File definition}}
Each CRAM file starts with a fixed length (26 bytes) definition with the following
fields:
\begin{tabular}{|l|l|l|}
\hline
\textbf{Data type} & \textbf{Name} & \textbf{Value}\tabularnewline
\hline
byte[4] & format magic number & CRAM (0x43 0x52 0x41 0x4d)\tabularnewline
\hline
unsigned byte & major format number & 3 (0x3)\tabularnewline
\hline
unsigned byte & minor format number & 0 (0x0)\tabularnewline
\hline
byte[20] & file id & CRAM file identifier (e.g. file name or SHA1 checksum)\tabularnewline
\hline
\end{tabular}
Valid CRAM \textit{major}.\textit{minor} version numbers are as follows:
\begin{itemize}
\item[\textit{1.0}]
The original public CRAM release.
\item[\textit{2.0}]
The first CRAM release implemented in both Java and C; tidied up
implementation vs specification differences in \textit{1.0}.
\item[\textit{2.1}]
Gained end of file markers; compatible with \textit{2.0}.
\item[\textit{3.0}]
Additional compression methods; header and data checksums;
improvements for unsorted data.
\end {itemize}
\section{\textbf{Container header structure}}
The file definition is followed by one or more containers with the following header
structure where the container content is stored in the `blocks' field:
\begin{tabular}{|l|>{\raggedright}p{120pt}|>{\raggedright}p{260pt}|}
\hline
\textbf{Data type} & \textbf{Name} & \textbf{Value}
\tabularnewline
\hline
int32 & length & the sum of the lengths of all blocks in this container (headers and data);
equal to the total byte length of the container minus the byte length of this header structure\tabularnewline
\hline
itf8 & reference sequence id & reference sequence identifier or\linebreak{}
-1 for unmapped reads\linebreak{}
-2 for multiple reference sequences.\linebreak{}
All slices in this container must have a reference sequence id matching this value.\tabularnewline
\hline
itf8 & starting position on the reference & the alignment start position or\linebreak{}
0 if the container is multiple-reference
or contains unmapped unplaced reads\tabularnewline
\hline
itf8 & alignment span & the length of the alignment or\linebreak{}
0 if the container is multiple-reference
or contains unmapped unplaced reads\tabularnewline
\hline
itf8 & number of records & number of records in the container\tabularnewline
\hline
ltf8 & record counter & 1-based sequential index of records in the file/stream.\tabularnewline
\hline
ltf8 & bases & number of read bases\tabularnewline
\hline
itf8 & number of blocks & the total number of blocks in this container\tabularnewline
\hline
array\texttt{<}itf8\texttt{>} & landmarks & the locations of slices in this container as byte offsets from the end of
this container header, used for random access indexing.
The landmark count must equal the slice count.\linebreak{}
Since the block before the first slice is the compression header,
landmarks[0] is equal to the byte length of the compression header.\tabularnewline
\hline
int & crc32 & CRC32 hash of the all the preceding bytes in the container.\tabularnewline
\hline
byte[ ] & blocks & The blocks contained within the container.\tabularnewline
\hline
\end{tabular}
\subsection{\textbf{CRAM header container}}
The first container in a CRAM file contains a textual header in a single block, optionally
gzip compressed. This text header currently matches the SAM header specification. Only
gzip is allowed as compression method for this block. The CRAM header container does not
include a compression header block.
It is recommended to reserve 50\% more space in the CRAM header container than
is required for the SAM header text by optionally padding the container with a second
raw block consisting of all zeroes. This can be used to subsequently expand the header
container in place, such as when updating @SQ records, while preserving the absolute
offsets of all subsequent containers.
\section{\textbf{Block structure}}
Containers consist of one or more blocks. Block compression is applied independently
and in addition to any encodings used to compress data within the block. The block
have the following header structure with the data stored in the `block data' field:
\begin{tabular}{|l|>{\raggedright}p{120pt}|>{\raggedright}p{260pt}|}
\hline
\textbf{Data type} & \textbf{Name} & \textbf{Value}
\tabularnewline
\hline
byte & method & the block compression method: \linebreak{}
0: raw (none)*\linebreak{}
1: gzip\linebreak{}
2: bzip2\linebreak{}
3: lzma\linebreak{}
4: rans\tabularnewline
\hline
byte & block content type id & the block content type identifier\tabularnewline
\hline
itf8 & block content id & the block content identifier used to associate external
data blocks with data series\tabularnewline
\hline
itf8 & size in bytes* & size of the block data after applying block compression\tabularnewline
\hline
itf8 & raw size in bytes* & size of the block data before applying block compression\tabularnewline
\hline
byte[ ] & block data & the data stored in the block:\linebreak{}
$\bullet$ bit stream of CRAM records (core data block)\linebreak{}
$\bullet$ byte stream (external data block)\linebreak{}
$\bullet$ additional fields ( header blocks)\tabularnewline
\hline
byte[4] & CRC32 & CRC32 hash value for all preceding bytes in the block\tabularnewline
\hline
\end{tabular}
* Note on raw method: both compressed and raw sizes must be set to the same value.
\subsection{\textbf{Block content types}}
CRAM has the following block content types:
\begin{threeparttable}[t]
\begin{tabular}{|>{\raggedright}p{143pt}|>{\raggedright}p{45pt}|>{\raggedright}p{116pt}|>{\raggedright}p{114pt}|}
\hline
\textbf{Block content type} & \textbf{Block content type id} & \textbf{Name} & \textbf{Contents}\tabularnewline
\hline
FILE\_HEADER & 0 & CRAM header block & CRAM header\tabularnewline
\hline
COMPRESSION\_HEADER & 1 & Compression header block & See specific section\tabularnewline
\hline
SLICE\_HEADER\tnote{a} & 2 & Slice header block & See specific section\tabularnewline
\hline
& 3 & & reserved\tabularnewline
\hline
EXTERNAL\_DATA & 4 & external data block & data produced by external encodings\tabularnewline
\hline
CORE\_DATA & 5 & core data block & bit stream of all encodings except for external encodings\tabularnewline
\hline
\end{tabular}
\begin{tablenotes}
\item[a] Formerly MAPPED\_SLICE\_HEADER. Now used by all slice headers regardless of mapping status.
\end{tablenotes}
\end{threeparttable}
\subsection{\textbf{Block content id}}
Block content id is used to distinguish between external blocks in the same slice.
Each external encoding has an id parameter which must be one of the external block
content ids. For external blocks the content id is a positive integer. For all
other blocks content id should be 0. Consequently, all external encodings must
not use content id less than 1.
\subsubsection*{Data blocks}
Data is stored in data blocks. There are two types of data blocks: core data blocks
and external data blocks.The difference between core and external data blocks is
that core data blocks consist of data series that are compressed using bit encodings
while the external data blocks are byte compressed. One core data block and any
number of external data blocks are associated with each slice.
Writing to and reading from core and external data blocks is organised through
CRAM records. Each data series is associated with an encoding. In case of external
encodings the block content id is used to identify the block where the data series
is stored. Please note that external blocks can have multiple data series associated
with them; in this case the values from these data series will be interleaved.
\subsection{\textbf{CRAM header block}}
The SAM header is stored in a single block within the first container.
The following constraints apply to the SAM header:
\begin{itemize}
\item The SQ:MD5 checksum is required unless the reference sequence has been embedded
into the file.
\end{itemize}
\subsection{\textbf{Compression header block}}
\label{subsec:compression-header}
The compression header block consists of 3 parts: preservation map, data series
encoding map and tag encoding map.
\subsubsection*{Preservation map}
The preservation map contains information about which data was preserved in the
CRAM file. It is stored as a map with byte[2] keys:
\begin{tabular}{|l|l|>{\raggedright}p{100pt}|>{\raggedright}p{220pt}|}
\hline
\textbf{Key} & \textbf{Value data type} & \textbf{Name} & \textbf{Value}\tabularnewline
\hline
RN & bool & read names included & true if read names are preserved for all reads\tabularnewline
\hline
AP & bool & AP data series delta & true if AP data series is delta, false otherwise\tabularnewline
\hline
RR & bool & reference required & true if reference sequence is required to restore
the data completely\tabularnewline
\hline
SM & byte[5] & substitution matrix & substitution matrix\tabularnewline
\hline
TD & array\texttt{<}byte\texttt{>} & tag ids dictionary & a list of lists of tag ids, see tag encoding section\tabularnewline
\hline
\end{tabular}
The boolean values are optional, defaulting to true when absent, although it is recommended to explicitly set them. SM and TD are mandatory.
\subsubsection*{Data series encodings}
Each data series has an encoding. These encoding are stored in a map with byte[2]
keys and are decoded in approximately this order\footnote{The precise order is defined in section~\ref{sec:record}.}:
\begin{threeparttable}[t]
\begin{tabular}{|l|l|>{\raggedright}p{100pt}|>{\raggedright}p{220pt}|}
\hline
\textbf{Key} & \textbf{Value data type} & \textbf{Name} & \textbf{Value}\tabularnewline
\hline
BF & encoding\texttt{<}int\texttt{>} & BAM bit flags & see separate section\tabularnewline
\hline
CF & encoding\texttt{<}int\texttt{>} & CRAM bit flags & see specific section\tabularnewline
\hline
RI & encoding\texttt{<}int\texttt{>} & reference id & record reference id from
the SAM file header\tabularnewline
\hline
RL & encoding\texttt{<}int\texttt{>} & read lengths & read lengths\tabularnewline
\hline
AP & encoding\texttt{<}int\texttt{>} & in-seq positions & if \textbf{AP-Delta} = true: 0-based alignment start
delta from the AP value in the previous record.
Note this delta may be negative, for example when switching references in a multi-reference slice.
When the record is the first in the slice, the previous position used is the slice alignment-start field (hence the first delta should be zero for single-reference slices, or the AP value itself for multi-reference slices). \linebreak{}
if \textbf{AP-Delta} = false: encodes the alignment start position directly\tabularnewline
\hline
RG & encoding\texttt{<}int\texttt{>} & read groups & read groups. Special value
`-1' stands for no group.\tabularnewline
\hline
RN\tnote{a} & encoding\texttt{<}byte[ ]\texttt{>} & read names & read names\tabularnewline
\hline
MF & encoding\texttt{<}int\texttt{>} & next mate bit flags & see specific section\tabularnewline
\hline
NS & encoding\texttt{<}int\texttt{>} & next fragment reference sequence id & reference
sequence ids for the next fragment \tabularnewline
\hline
NP & encoding\texttt{<}int\texttt{>} & next mate alignment start & alignment positions
for the next fragment\tabularnewline
\hline
TS & encoding\texttt{<}int\texttt{>} & template size & template sizes\tabularnewline
\hline
NF & encoding\texttt{<}int\texttt{>} & distance to next fragment & number of records
to the next fragment\tnote{b}\tabularnewline
\hline
TL\tnote{c} & encoding\texttt{<}int\texttt{>} & tag ids & list of tag ids, see tag encoding
section\tabularnewline
\hline
FN & encoding\texttt{<}int\texttt{>} & number of read features & number of read
features in each record\tabularnewline
\hline
FC & encoding\texttt{<}byte\texttt{>} & read features codes & see separate section\tabularnewline
\hline
FP & encoding\texttt{<}int\texttt{>} & in-read positions & positions of the read
features\tabularnewline
\hline
DL & encoding\texttt{<}int\texttt{>} & deletion lengths & base-pair deletion lengths\tabularnewline
\hline
BB & encoding\texttt{<}byte[ ]\texttt{>} & stretches of bases & bases\tabularnewline
\hline
QQ & encoding\texttt{<}byte[ ]\texttt{>} & stretches of quality scores & quality scores\tabularnewline
\hline
BS & encoding\texttt{<}byte\texttt{>} & base substitution codes & base substitution
codes\tabularnewline
\hline
IN & encoding\texttt{<}byte[ ]\texttt{>} & insertion & inserted bases\tabularnewline
\hline
RS & encoding\texttt{<}int\texttt{>} & reference skip length & number of skipped
bases for the `N' read feature\tabularnewline
\hline
PD & encoding\texttt{<}int\texttt{>} & padding & number of padded bases\tabularnewline
\hline
HC & encoding\texttt{<}int\texttt{>} & hard clip & number of hard clipped bases\tabularnewline
\hline
SC & encoding\texttt{<}byte[ ]\texttt{>} & soft clip & soft clipped bases\tabularnewline
\hline
MQ & encoding\texttt{<}int\texttt{>} & mapping qualities & mapping quality scores\tabularnewline
\hline
BA & encoding\texttt{<}byte\texttt{>} & bases & bases\tabularnewline
\hline
QS & encoding\texttt{<}byte\texttt{>} & quality scores & quality scores\tabularnewline
\hline
TC\tnote{d} & N/A & legacy field & to be ignored\tabularnewline
\hline
TN\tnote{d} & N/A & legacy field & to be ignored\tabularnewline
\end{tabular}
\begin{tablenotes}
\item[a] Note RN this is decoded after MF if the record is detached from the mate and we are attempting to auto-generate read names.
\item[b] The count is reset for each slice so NF can only refer to a record later within this slice.
\item[c] TL is followed by decoding the tag values themselves, in order of appearance in the tag dictionary.
\item[d] TC and TN are legacy data series from CRAM 1.0.
They have no function in CRAM 3.0 and should not be present.
However some implementations do output them and decoders must silently skip these fields.
It is illegal for TC and TN to contain any data values, although there
may be empty blocks associated with them.
\end{tablenotes}
\end{threeparttable}
\subsubsection*{Tag encodings}
\label{subsubsec:tags}
The tag dictionary (TD) describes the unique combinations of tag id / type that occur on each alignment record.
For example if we search the id / types present in each record and find only two combinations -- X1:i BC:Z SA:Z: and X1:i: BC:Z -- then we have two dictionary entries in the TD map.
Let $L_{i}=\{T_{i0}, T_{i1}, \ldots, T_{ix}\}$ be a list of all tag ids for a record $R_{i}$, where $i$ is the sequential record index and $T_{ij}$ denotes $j$-th tag id in the record.
The list of unique $L_{i}$ is stored as the TD value in the preservation map.
Maintaining the order is not a requirement for encoders (hence ``combinations''), but it is permissible and thus different permutations, each encoded with their own elements in TD, should be supported by the decoder.
Each $L_{i}$ element in TD is assigned a sequential integer number starting with 0.
These integer numbers are referred to by the TL data series.
Using TD, an integer from the TL data series can be mapped back into a list of tag ids.
Thus per alignment record we only need to store tag values and not their ids and types.
The TD is written as a byte array consisting of $L_{i}$ values separated with \textbackslash{}0.
Each $L_{i}$ value is written as a concatenation of 3 byte $T_{ij}$ elements: tag id followed by BAM tag type code (one of A, c, C, s, S, i, I, f, F, Z, H or B, as described in the SAM specification).
For example the TD for tag lists X1:i BC:Z SA:Z and X1:i BC:Z may be encoded as X1CBCZSAZ\textbackslash{}0X1CBCZ\textbackslash{}0, with X1C indicating a 1 byte unsigned value for tag X1.
\subsubsection*{Tag values}
The encodings used for different tags are stored in a map.
The key is 3 bytes formed from the BAM tag id and type code, matching the TD dictionary described above.
Unlike the Data Series Encoding Map, the key is stored in the map as an ITF8 encoded integer, constructed using $(char1<<16) + (char2<<8) + type$.
For example, the 3-byte representation of OQ:Z is \{0x4F, 0x51, 0x5A\} and these bytes are intepreted as the integer key 0x004F515A, leading to an ITF8 byte stream \{0xE0, 0x4F, 0x51, 0x5A\}.
\begin{tabular}{|l|l|l|>{\raggedright}p{160pt}|}
\hline
\textbf{Key} & \textbf{Value data type} & \textbf{Name} & \textbf{Value}
\tabularnewline
\hline
TAG ID 1:TAG TYPE 1 & encoding\texttt{<}byte[ ]\texttt{>} & read tag 1 & tag values
(names and types are available in the data series code)\tabularnewline
\hline
... & & ... & ...\tabularnewline
\hline
TAG ID N:TAG TYPE N & encoding\texttt{<}byte[ ]\texttt{>} & read tag N & ...\tabularnewline
\hline
\end{tabular}
Note that tag values are encoded as array of bytes. The routines to convert tag
values into byte array and back are the same as in BAM with the exception of value
type being captured in the tag key rather in the value.
Hence consuming 1 byte for types `C' and `c', 2 bytes for types `S' and `s', 4 bytes for types `I', `i' and `f', and a variable number of bytes for types `H', `Z' and `B'.
\subsection{\textbf{Slice header block}}
The slice header block is never compressed (block method=raw). For reference mapped
reads the slice header also defines the reference sequence context of the data
blocks associated with the slice. Mapped reads can be stored along with
\textbf{placed unmapped}\footnote{Unmapped reads can be \textit{placed} or \textit{unplaced}.
By placed unmapped read we mean a read that is unmapped according to bit 0x4 of the
BF (BAM bit flags) data series, but has position fields filled in, thus "placing" it on a reference sequence. In contrast,
unplaced unmapped reads have have a reference sequence ID of -1 and alignment position of 0.}
reads on the same reference within the same slice.
Slices with the Multiple Reference flag (-2) set as the sequence ID in the header may contain reads
mapped to multiple external references, including unmapped\footnotemark[\value{footnote}] reads (placed on these references or unplaced),
but multiple embedded references cannot be combined in this way. When multiple references are
used, the RI data series will be used to determine the reference sequence ID for each record. This
data series is not present when only a single reference is used within a slice.
The Unmapped (-1) sequence ID in the header is for slices containing only unplaced
unmapped\footnotemark[\value{footnote}] reads.
A slice containing data that does not use the external reference in
any sequence may set the reference MD5 sum to zero. This can happen
because the data is unmapped or the sequence has been stored verbatim
instead of via reference-differencing. This latter scenario is
recommended for unsorted or non-coordinate-sorted data.
The slice header block contains the following fields.
\begin{tabular}{|l|l|>{\raggedright}p{200pt}|}
\hline
\textbf{Data type} & \textbf{Name} & \textbf{Value}\tabularnewline
\hline
itf8 & reference sequence id & reference sequence identifier or\linebreak{}
-1 for unmapped reads\linebreak{}
-2 for multiple reference sequences.\linebreak{}
This value must match that of its enclosing container.\tabularnewline
\hline
itf8 & alignment start & the alignment start position.\linebreak{}
0 if the slice is multiple-reference
or contains unmapped unplaced reads\tabularnewline
\hline
itf8 & alignment span & the length of the alignment.\linebreak{}
0 if the slice is multiple-reference
or contains unmapped unplaced reads\tabularnewline
\hline
itf8 & number of records & the number of records in the slice\tabularnewline
\hline
ltf8 & record counter & 1-based sequential index of records in the file/stream\tabularnewline
\hline
itf8 & number of blocks & the number of blocks in the slice\tabularnewline
\hline
itf8[ ] & block content ids & block content ids of the blocks in the slice\tabularnewline
\hline
itf8 & embedded reference bases block content id & block content id for the embedded
reference sequence bases or -1 for none\tabularnewline
\hline
byte[16] & reference md5 & MD5 checksum of the reference bases within the slice
boundaries. If this slice has reference sequence id of -1 (unmapped) or -2 (multi-ref)
the MD5 should be 16 bytes of \textbackslash{}0. For embedded references, the MD5
can either be all-zeros or the MD5 of the embedded sequence.\tabularnewline
\hline
byte[ ] & optional tags & a series of tag,type,value tuples encoded as
per BAM auxiliary fields.\tabularnewline
\hline
\end{tabular}
The optional tags are encoded in the same manner as BAM tags. I.e. a
series of binary encoded tags concatenated together where each tag
consists of a 2 byte key (matching [A-Za-z][A-Za-z0-9]) followed by a
1 byte type ([AfZHcCsSiIB]) followed by a string of bytes in a format
defined by the type.
Tags starting in a capital letter are reserved while lowercase ones or
those starting with X, Y or Z are user definable. Any tag not
understood by a decoder should be skipped over without producing an
error.
At present no tags are defined.
% Details omitted until we fully work through all the corner cases,
% such as seq/qual of *.
%
% Reserved tags are defined as follows:
%
% \begin{tabular}{|l|l|>{\raggedright}p{325pt}|}
% \hline
% \textbf{Tag type} & \textbf{BAM format} & \textbf{Meaning}\tabularnewline
% \hline
% BD & i & Sum over all reads of the CRC32 hash of sequence base. This
% may be used to validate round-trips in and out of CRAM.
% calls\tabularnewline
% \hline
% SD & i & Sum over all reads of the CRC32 hash of quality scores. (If
% the quality string is ``*'' in SAM then the hash is of the BAM encoded
% version - a string of bytes with value 255.)\tabularnewline
% \hline
% \end{tabular}
\subsection{\textbf{Core data block}}
A core data block is a bit stream (most significant bit first) consisting of data from one
or more CRAM records. Please note that one byte could hold more then one CRAM record
as a minimal CRAM record could be just a few bits long. The core data block has
the following fields:
\begin{tabular}{|l|>{\raggedright}p{120pt}|>{\raggedright}p{260pt}|}
\hline
\textbf{Data type} & \textbf{Name} & \textbf{Value}
\tabularnewline
\hline
bit[ ] & CRAM record 1 & The first CRAM record\tabularnewline
\hline
... & ... & ...\tabularnewline
\hline
bit[ ] & CRAM record N & The Nth CRAM record \tabularnewline
\hline
\end{tabular}
\subsection{\textbf{External data blocks}}
The relationship between the core data block and external data blocks is shown in the following
picture:
\begin{center}
\begin{tikzpicture}
\usetikzlibrary{shapes, shadows, positioning, arrows, decorations.markings}
\pgfdeclarelayer{background}
\pgfsetlayers{background,main}
\tikzstyle{dsbox} = [blockbox, text width=6em, minimum width=6em, minimum height=3em, rounded corners, drop shadow]
\tikzstyle{blockbox}=[draw, fill=white, text width=4.0em, text centered, minimum height=1.0em, drop shadow]
\tikzstyle{encodedblocklarge} = [blockbox, text width=6em, minimum width=8em, minimum height=4em, drop shadow]
\tikzstyle{encodedblock} = [blockbox, text width=6em, minimum width=8em, minimum height=3em, drop shadow]
\tikzstyle{texto} = [above, text width=8em, text centered]
\newcommand{\cramRecord}[6]{%