aboutsummaryrefslogtreecommitdiff
path: root/content/posts/2019-01-03-encoding-binary-data-into-dna-sequence.md
diff options
context:
space:
mode:
Diffstat (limited to 'content/posts/2019-01-03-encoding-binary-data-into-dna-sequence.md')
-rw-r--r--content/posts/2019-01-03-encoding-binary-data-into-dna-sequence.md411
1 files changed, 411 insertions, 0 deletions
diff --git a/content/posts/2019-01-03-encoding-binary-data-into-dna-sequence.md b/content/posts/2019-01-03-encoding-binary-data-into-dna-sequence.md
new file mode 100644
index 0000000..b285756
--- /dev/null
+++ b/content/posts/2019-01-03-encoding-binary-data-into-dna-sequence.md
@@ -0,0 +1,411 @@
1---
2title: Encoding binary data into DNA sequence
3url: encoding-binary-data-into-dna-sequence.html
4date: 2019-01-03T12:00:00+02:00
5type: post
6draft: false
7---
8
9## Initial thoughts
10
11Imagine a world where you could go outside and take a leaf from a tree and put
12it through your personal DNA sequencer and get data like music, videos or
13computer programs from it. Well, this is all possible now. It was not done on a
14large scale because it is quite expensive to create DNA strands but it's
15possible.
16
17Encoding data into DNA sequence is relatively simple process once you understand
18the relationship between binary data and nucleotides and scientists have been
19making large leaps in this field in order to provide viable long-term storage
20solution for our data that would potentially survive our specie if case of
21global disaster. We could imprint all the world's knowledge into plants and
22ensure the survival of our knowledge.
23
24More optimistic usage for this technology would be easier storage of ever
25growing data we produce every day. Once machines for sequencing DNA become fast
26enough and cheaper this could mean the next evolution of storing data and
27abandoning classical hard and solid state drives in data warehouses.
28
29As we currently stand this is still not viable but it is quite an amazing and
30cool technology.
31
32My interests in this field are purely in encoding processes and experimental
33testing mainly because I don't have the access to this expensive machines. My
34initial goal was to create a toolkit that can be used by everybody to encode
35their data into a proper DNA sequence.
36
37## Glossary
38
39**deoxyribose** A five-carbon sugar molecule with a hydrogen atom rather than a
40hydroxyl group in the 2′ position; the sugar component of DNA nucleotides.
41
42**double helix** The molecular shape of DNA in which two strands of nucleotides
43wind around each other in a spiral shape.
44
45**nitrogenous base** A nitrogen-containing molecule that acts as a base; often
46referring to one of the purine or pyrimidine components of nucleic acids.
47
48**phosphate group** A molecular group consisting of a central phosphorus atom
49bound to four oxygen atoms.
50
51**RGB** The RGB color model is an additive color model in which red, green and
52blue light are added together in various ways to reproduce a broad array of
53colors.
54
55**GCC** The GNU Compiler Collection is a compiler system produced by the GNU
56Project supporting various programming languages.
57
58## Data encoding
59
60**TL;DR:** Encoding involves the use of a code to change original data into a
61form that can be used by an external process.
62
63Encoding is the process of converting data into a format required for a number
64of information processing needs, including:
65
66- Program compiling and execution
67- Data transmission, storage and compression/decompression
68- Application data processing, such as file conversion
69
70Encoding can have two meanings:
71
72- In computer technology, encoding is the process of applying a specific code,
73 such as letters, symbols and numbers, to data for conversion into an
74 equivalent cipher.
75- In electronics, encoding refers to analog to digital conversion.
76
77## Quick history of DNA
78
79- **1869** - Friedrich Miescher identifies "nuclein".
80- **1900s** - The Eugenics Movement.
81- **1900** – Mendel's theories are rediscovered by researchers.
82- **1944** - Oswald Avery identifies DNA as the 'transforming principle'.
83- **1952** - Rosalind Franklin photographs crystallized DNA fibres.
84- **1953** - James Watson and Francis Crick discover the double helix structure of DNA.
85- **1965** - Marshall Nirenberg is the first person to sequence the bases in each codon.
86- **1983** - Huntington's disease is the first mapped genetic disease.
87- **1990** - The Human Genome Project begins.
88- **1995** - Haemophilus Influenzae is the first bacterium genome sequenced.
89- **1996** - Dolly the sheep is cloned.
90- **1999** - First human chromosome is decoded.
91- **2000** – Genetic code of the fruit fly is decoded.
92- **2002** – Mouse is the first mammal to have its genome decoded.
93- **2003** – The Human Genome Project is completed.
94- **2013** – DNA Worldwide and Eurofins Forensic discover identical twins have differences in their genetic makeup.
95
96## What is DNA?
97
98Deoxyribonucleic acid, a self-replicating material which is **present in nearly
99all living organisms** as the main constituent of chromosomes. It is the
100**carrier of genetic information**.
101
102> The nitrogen in our DNA, the calcium in our teeth, the iron in our blood,
103> the carbon in our apple pies were made in the interiors of collapsing stars.
104> We are made of starstuff.
105> **-- Carl Sagan, Cosmos**
106
107The nucleotide in DNA consists of a sugar (deoxyribose), one of four bases
108(cytosine (C), thymine (T), adenine (A), guanine (G)), and a phosphate.
109Cytosine and thymine are pyrimidine bases, while adenine and guanine are purine
110bases. The sugar and the base together are called a nucleoside.
111
112![DNA](/assets/dna-sequence/dna-basics.jpg)
113
114*DNA (a) forms a double stranded helix, and (b) adenine pairs with thymine and
115cytosine pairs with guanine. (credit a: modification of work by Jerome Walker,
116Dennis Myts)*
117
118## Encode binary data into DNA sequence
119
120As an input file you can use any file you want:
121
122- ASCII files,
123- Compiled programs,
124- Multimedia files (MP3, MP4, MVK, etc),
125- Images,
126- Database files,
127- etc.
128
129Note: If you would copy all the bytes from RAM to file or pipe data to file you
130could encode also this data as long as you provide file pointer to the encoder.
131
132### Basic Encoding
133
134As already mentioned, the Basic Encoding is based on a simple mapping. Since DNA
135is composed of 4 nucleotides (Adenine, Cytosine, Guanine, Thymine; usually
136referred using the first letter). Using this technique we can encode
137
138$$ log_2(4) = log_2(2^2) = 2 bits $$
139
140using a single nucleotide. In this way, we are able to use the 4 bases that
141compose the DNA strand to encode each byte of data.
142
143| Two bits | Nucleotides |
144| -------- | ---------------- |
145| 00 | **A** (Adenine) |
146| 10 | **G** (Guanine) |
147| 01 | **C** (Cytosine) |
148| 11 | **T** (Thymine) |
149
150With this in mind we can simply encode any data by using two-bit to Nucleotides
151conversion.
152
153```python
154{ Algorithm 1: Naive byte array to DNA encode }
155procedure EncodeToDNASequence(f) string
156begin
157 enc string
158 while not eof(f) do
159 c byte := buffer[0] { Read 1 byte from buffer }
160 bin integer := sprintf('08b', c) { Convert to string binary }
161 for e in range[0, 2, 4, 6] do
162 if e[0] == 48 and e[1] == 48 then { 0x00 - A (Adenine) }
163 enc += 'A'
164 else if e[0] == 48 and e[1] == 49 then { 0x01 - G (Guanine) }
165 enc += 'G'
166 else if e[0] == 49 and e[1] == 48 then { 0x10 - C (Cytosine) }
167 enc += 'C'
168 else if e[0] == 49 and e[1] == 49 then { 0x11 - T (Thymine) }
169 enc += 'T'
170 return enc { Return DNA sequence }
171end
172```
173
174Another encoding would be **Goldman encoding**. Using this encoding helps with
175Nonsense mutation (amino acids replaced by a stop codon) that occurs and is the
176most problematic during translation because it leads to truncated amino acid
177sequences, which in turn results in truncated proteins.
178
179[Where to store big data? In DNA: Nick Goldman at TEDxPrague](https://www.youtube.com/watch?v=a4PiGWNsIEU)
180
181### FASTA file format
182
183In bioinformatics, FASTA format is a text-based format for representing either
184nucleotide sequences or peptide sequences, in which nucleotides or amino acids
185are represented using single-letter codes. The format also allows for sequence
186names and comments to precede the sequences. The format originates from the
187FASTA software package, but has now become a standard in the field of
188bioinformatics.
189
190The first line in a FASTA file started either with a ">" (greater-than) symbol
191or, less frequently, a ";" (semicolon) was taken as a comment. Subsequent lines
192starting with a semicolon would be ignored by software. Since the only comment
193used was the first, it quickly became used to hold a summary description of the
194sequence, often starting with a unique library accession number, and with time
195it has become commonplace to always use ">" for the first line and to not use
196";" comments (which would otherwise be ignored).
197
198```
199;LCBO - Prolactin precursor - Bovine
200; a sample sequence in FASTA format
201MDSKGSSQKGSRLLLLLVVSNLLLCQGVVSTPVCPNGPGNCQVSLRDLFDRAVMVSHYIHDLSS
202EMFNEFDKRYAQGKGFITMALNSCHTSSLPTPEDKEQAQQTHHEVLMSLILGLLRSWNDPLYHL
203VTEVRGMKGAPDAILSRAIEIEEENKRLLEGMEMIFGQVIPGAKETEPYPVWSGLPSLQTKDED
204ARYSAFYNLLHCLRRDSSKIDTYLKLLNCRIIYNNNC*
205
206>MCHU - Calmodulin - Human, rabbit, bovine, rat, and chicken
207ADQLTEEQIAEFKEAFSLFDKDGDGTITTKELGTVMRSLGQNPTEAELQDMINEVDADGNGTID
208FPEFLTMMARKMKDTDSEEEIREAFRVFDKDGNGYISAAELRHVMTNLGEKLTDEEVDEMIREA
209DIDGDGQVNYEEFVQMMTAK*
210
211>gi|5524211|gb|AAD44166.1| cytochrome b [Elephas maximus maximus]
212LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV
213EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG
214LLILILLLLLLALLSPDMLGDPDNHMPADPLNTPLHIKPEWYFLFAYAILRSVPNKLGGVLALFLSIVIL
215GLMPFLHTSKHRSMMLRPLSQALFWTLTMDLLTLTWIGSQPVEYPYTIIGQMASILYFSIILAFLPIAGX
216IENY
217```
218
219FASTA format was extended by [FASTQ](https://en.wikipedia.org/wiki/FASTQ_format)
220format from the [Sanger Centre](https://www.sanger.ac.uk/) in Cambridge.
221
222### PNG encoded DNA sequence
223
224| Nucleotides | RGB | Color name |
225| ------------ | ----------- | ---------- |
226| A ➞ Adenine | (0,0,255) | Blue |
227| G ➞ Guanine | (0,100,0) | Green |
228| C ➞ Cytosine | (255,0,0) | Red |
229| T ➞ Thymine | (255,255,0) | Yellow |
230
231With this in mind we can create a simple algorithm to create PNG representation
232of a DNA sequence.
233
234```python
235{ Algorithm 2: Naive DNA to PNG encode from FASTA file }
236procedure EncodeDNASequenceToPNG(f)
237begin
238 i image
239 while not eof(f) do
240 c char := buffer[0] { Read 1 char from buffer }
241 case c of
242 'A': color := RGB(0, 0, 255) { Blue }
243 'G': color := RGB(0, 100, 0) { Green }
244 'C': color := RGB(255, 0, 0) { Red }
245 'T': color := RGB(255, 255, 0) { Yellow }
246 drawRect(i, [x, y], color)
247 save(i) { Save PNG image }
248end
249```
250
251## Encoding text file in practice
252
253In this example we will take a simple text file as our input stream for
254encoding. This file will have a quote from Niels Bohr and saved as txt file.
255
256> How wonderful that we have met with a paradox. Now we have some hope of
257> making progress.
258> ― Niels Bohr
259
260First we encode text file into FASTA file.
261
262```bash
263./dnae-encode -i quote.txt -o quote.fa
2642019/01/10 00:38:29 Gathering input file stats
2652019/01/10 00:38:29 Starting encoding ...
266 106 B / 106 B [==================================] 100.00% 0s
2672019/01/10 00:38:29 Saving to FASTA file ...
2682019/01/10 00:38:29 Output FASTA file length is 438 B
2692019/01/10 00:38:29 Process took 987.263µs
2702019/01/10 00:38:29 Done ...
271```
272
273Output of `quote.fa` file contains the encoded DNA sequence in ASCII format.
274
275```
276>SEQ1
277GACAGCTTGTGTACAAGTGTGCTTGCTCGCGAGCGGGTACGCGCGTGGGCTAACAAGTGA
278GCCAGCAGGTGAACAAGTGTGCGGACAAGCCAGCAGGTGCGCGGACAAGCTGGCGGGTGA
279ACAAGTGTGCCGGTGAGCCAACAAGCAGACAAGTAAGCAGGTACGCAGGCGAGCTTGTCA
280ACTCACAAGATCGCTTGTGTACAAGTGTGCGGACAAGCCAGCAGGTGCGCGGACAAGTAT
281GCTTGCTGGCGGACAAGCCAGCTTGTAAGCGGACAAGCTTGCGCACAAGCTGGCAGGCCT
282GCCGGCTCGCGTACAAATTCACAAGTAAGTACGCTTGCGTGTACGCGGGTATGTATACTC
283AACCTCACCAAACGGGACAAGATCGCCGGCGGGCTAGTATACAAGAACGCTTGCCAGTAC
284AACC
285```
286
287Then we encode FASTA file from previous operation to encode this data into PNG.
288
289```bash
290./dnae-png -i quote.fa -o quote.png
2912019/01/10 00:40:09 Gathering input file stats ...
2922019/01/10 00:40:09 Deconstructing FASTA file ...
2932019/01/10 00:40:09 Compositing image file ...
294 424 / 424 [==================================] 100.00% 0s
2952019/01/10 00:40:09 Saving output file ...
2962019/01/10 00:40:09 Output image file length is 1.1 kB
2972019/01/10 00:40:09 Process took 19.036117ms
2982019/01/10 00:40:09 Done ...
299```
300
301After encoding into PNG format this file looks like this.
302
303![Encoded Quote in PNG format](/assets/dna-sequence/quote.png)
304
305The larger the input stream is the larger the PNG file would be.
306
307Compiled basic Hello World C program with
308[GCC](https://www.gnu.org/software/gcc/) would [look
309like](/assets/dna-sequence/sample.png).
310
311```c
312// gcc -O3 -o sample sample.c
313#include <stdio.h>
314
315main() {
316 printf("Hello, world!\n");
317 return 0;
318}
319```
320
321## Toolkit for encoding data
322
323I have created a toolkit with two main programs:
324
325- dnae-encode (encodes file into FASTA file)
326- dnae-png (encodes FASTA file into PNG)
327
328Toolkit with full source code is available on
329[github.com/mitjafelicijan/dna-encoding](https://github.com/mitjafelicijan/dna-encoding).
330
331### dnae-encode
332
333```bash
334> ./dnae-encode --help
335usage: dnae-encode --input=INPUT [<flags>]
336
337A command-line application that encodes file into DNA sequence.
338
339Flags:
340 --help Show context-sensitive help (also try --help-long and --help-man).
341 -i, --input=INPUT Input file (ASCII or binary) which will be encoded into DNA sequence.
342 -o, --output="out.fa" Output file which stores DNA sequence in FASTA format.
343 -s, --sequence=SEQ1 The description line (defline) or header/identifier line, gives a name and/or a unique identifier for the sequence.
344 -c, --columns=60 Row characters length (no more than 120 characters). Devices preallocate fixed line sizes in software.
345 --version Show application version.
346```
347
348### dnae-png
349
350```bash
351> ./dnae-png --help
352usage: dnae-png --input=INPUT [<flags>]
353
354A command-line application that encodes FASTA file into PNG image.
355
356Flags:
357 --help Show context-sensitive help (also try --help-long and --help-man).
358 -i, --input=INPUT Input FASTA file which will be encoded into PNG image.
359 -o, --output="out.png" Output file in PNG format that represents DNA sequence in graphical way.
360 -s, --size=10 Size of pairings of DNA bases on image in pixels (lower resolution lower file size).
361 --version Show application version.
362```
363
364## Benchmarks
365
366First we generate some binary sample data with dd.
367
368```bash
369dd if=<(openssl enc -aes-256-ctr -pass pass:"$(dd if=/dev/urandom bs=128 count=1 2>/dev/null | base64)" -nosalt < /dev/zero) of=1KB.bin bs=1KB count=1 iflag=fullblock
370```
371
372Our freshly generated 1KB file looks something like this (its full of garbage
373data as intended).
374
375![Sample binary file 1KB](/assets/dna-sequence/sample-binary-file.png)
376
377We create following binary files:
378
379- 1KB.bin
380- 10KB.bin
381- 100KB.bin
382- 1MB.bin
383- 10MB.bin
384- 100MB.bin
385
386After this we create FASTA files for all the binary files by encoding them
387into DNA sequence.
388
389```bash
390./dnae-encode -i 100MB.bin -o 100MB.fa
391```
392
393Then we GZIP all the FASTA files to see how much the can be compressed.
394
395```bash
396gzip -9 < 10MB.fa > 10MB.fa.gz
397```
398
399[Download ODS file with benchmarks](/dna-sequence/benchmarks.ods).
400
401![Sample binary file 1KB](/assets/dna-sequence/chart-1.png)
402
403![Sample binary file 1KB](/assets/dna-sequence/chart-2.png)
404
405## References
406
407- https://www.techopedia.com/definition/948/encoding
408- https://www.dna-worldwide.com/resource/160/history-dna-timeline
409- https://opentextbc.ca/biology/chapter/9-1-the-structure-of-dna/
410- https://arxiv.org/abs/1801.04774
411- https://en.wikipedia.org/wiki/FASTA_format