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