aboutsummaryrefslogtreecommitdiff
path: root/content/2019-01-03-encoding-binary-data-into-dna-sequence.md
diff options
context:
space:
mode:
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.md416
1 files changed, 0 insertions, 416 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
deleted file mode 100644
index d3c1396..0000000
--- a/content/2019-01-03-encoding-binary-data-into-dna-sequence.md
+++ /dev/null
@@ -1,416 +0,0 @@
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
6type: research
7date: 2019-01-03
8---
9
10**Table of contents**
11
121. [Initial thoughts](#initial-thoughts)
132. [Glossary](#glossary)
143. [Data encoding](#data-encoding)
154. [Quick history of DNA](#quick-history-of-dna)
165. [What is DNA?](#what-is-dna)
176. [Encode binary data into DNA sequence](#encode-binary-data-into-dna-sequence)
18 1. [Basic Encoding](#basic-encoding)
19 2. [FASTA file format](#fasta-file-format)
20 3. [PNG encoded DNA sequence](#png-encoded-dna-sequence)
217. [Encoding text file in practice](#encoding-text-file-in-practice)
228. [Toolkit for encoding data](#toolkit-for-encoding-data)
23 1. [dnae-encode](#dnae-encode)
24 2. [dnae-png](#dnae-png)
259. [Benchmarks](#benchmarks)
2610. [References](#references)
27
28## Initial thoughts
29
30Imagine 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.
31
32Encoding 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.
33
34More 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.
35
36As we currently stand this is still not viable but it is quite an amazing and cool technology.
37
38My 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.
39
40## Glossary
41
42**deoxyribose**
43: A five-carbon sugar molecule with a hydrogen atom rather than a hydroxyl group in the 2′ position; the sugar component of DNA nucleotides.
44
45**double helix**
46: The molecular shape of DNA in which two strands of nucleotides wind around each other in a spiral shape.
47
48**nitrogenous base**
49: A nitrogen-containing molecule that acts as a base; often referring to one of the purine or pyrimidine components of nucleic acids.
50
51**phosphate group**
52: A molecular group consisting of a central phosphorus atom bound to four oxygen atoms.
53
54**RGB**
55: 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.
56
57**GCC**
58: The GNU Compiler Collection is a compiler system produced by the GNU Project supporting various programming languages.
59
60## Data encoding
61
62**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].
63
64Encoding is the process of converting data into a format required for a number of 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[^1]:
71
72- 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.
73- In electronics, encoding refers to analog to digital conversion.
74
75## Quick history of DNA
76
77- **1869** - Friedrich Miescher identifies "nuclein".
78- **1900s** - The Eugenics Movement.
79- **1900** – Mendel's theories are rediscovered by researchers.
80- **1944** - Oswald Avery identifies DNA as the 'transforming principle'.
81- **1952** - Rosalind Franklin photographs crystallized DNA fibres.
82- **1953** - James Watson and Francis Crick discover the double helix structure of DNA.
83- **1965** - Marshall Nirenberg is the first person to sequence the bases in each codon.
84- **1983** - Huntington's disease is the first mapped genetic disease.
85- **1990** - The Human Genome Project begins.
86- **1995** - Haemophilus Influenzae is the first bacterium genome sequenced.
87- **1996** - Dolly the sheep is cloned.
88- **1999** - First human chromosome is decoded.
89- **2000** – Genetic code of the fruit fly is decoded.
90- **2002** – Mouse is the first mammal to have its genome decoded.
91- **2003** – The Human Genome Project is completed.
92- **2013** – DNA Worldwide and Eurofins Forensic discover identical twins have differences in their genetic makeup [^2].
93
94## What is DNA?
95
96Deoxyribonucleic 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**.
97
98> 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.
99>
100> **-- Carl Sagan, Cosmos**
101
102The 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.
103
104![DNA](/files/dna-sequence/dna-basics.jpg#center)
105
106*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]*
107
108## Encode binary data into DNA sequence
109
110As an input file you can use any file you want:
111- ASCII files,
112- Compiled programs,
113- Multimedia files (MP3, MP4, MVK, etc),
114- Images,
115- Database files,
116- etc.
117
118Note: 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.
119
120### Basic Encoding
121
122As 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
123
124$$ log_2(4) = log_2(2^2) = 2 bits $$
125
126using 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.
127
128| Two bits | Nucleotides |
129| -------- | ---------------- |
130| 00 | **A** (Adenine) |
131| 10 | **G** (Guanine) |
132| 01 | **C** (Cytosine) |
133| 11 | **T** (Thymine) |
134
135With this in mind we can simply encode any data by using two-bit to Nucleotides conversion
136
137```pascal
138{ Algorithm 1: Naive byte array to DNA encode }
139procedure EncodeToDNASequence(f) string
140begin
141 enc string
142 while not eof(f) do
143 c byte := buffer[0] { Read 1 byte from buffer }
144 bin integer := sprintf('08b', c) { Convert to string binary }
145 for e in range[0, 2, 4, 6] do
146 if e[0] == 48 and e[1] == 48 then { 0x00 - A (Adenine) }
147 enc += 'A'
148 else if e[0] == 48 and e[1] == 49 then { 0x01 - G (Guanine) }
149 enc += 'G'
150 else if e[0] == 49 and e[1] == 48 then { 0x10 - C (Cytosine) }
151 enc += 'C'
152 else if e[0] == 49 and e[1] == 49 then { 0x11 - T (Thymine) }
153 enc += 'T'
154 return enc { Return DNA sequence }
155end
156```
157
158Another 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]
159
160[Where to store big data? In DNA: Nick Goldman at TEDxPrague](https://www.youtube.com/watch?v=a4PiGWNsIEU)
161
162### FASTA file format
163
164In 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]
165
166The 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).
167
168```text
169;LCBO - Prolactin precursor - Bovine
170; a sample sequence in FASTA format
171MDSKGSSQKGSRLLLLLVVSNLLLCQGVVSTPVCPNGPGNCQVSLRDLFDRAVMVSHYIHDLSS
172EMFNEFDKRYAQGKGFITMALNSCHTSSLPTPEDKEQAQQTHHEVLMSLILGLLRSWNDPLYHL
173VTEVRGMKGAPDAILSRAIEIEEENKRLLEGMEMIFGQVIPGAKETEPYPVWSGLPSLQTKDED
174ARYSAFYNLLHCLRRDSSKIDTYLKLLNCRIIYNNNC*
175
176>MCHU - Calmodulin - Human, rabbit, bovine, rat, and chicken
177ADQLTEEQIAEFKEAFSLFDKDGDGTITTKELGTVMRSLGQNPTEAELQDMINEVDADGNGTID
178FPEFLTMMARKMKDTDSEEEIREAFRVFDKDGNGYISAAELRHVMTNLGEKLTDEEVDEMIREA
179DIDGDGQVNYEEFVQMMTAK*
180
181>gi|5524211|gb|AAD44166.1| cytochrome b [Elephas maximus maximus]
182LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV
183EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG
184LLILILLLLLLALLSPDMLGDPDNHMPADPLNTPLHIKPEWYFLFAYAILRSVPNKLGGVLALFLSIVIL
185GLMPFLHTSKHRSMMLRPLSQALFWTLTMDLLTLTWIGSQPVEYPYTIIGQMASILYFSIILAFLPIAGX
186IENY
187```
188
189FASTA format was extended by [FASTQ](https://en.wikipedia.org/wiki/FASTQ_format) format from the [Sanger Centre](https://www.sanger.ac.uk/) in Cambridge.
190
191### PNG encoded DNA sequence
192
193| Nucleotides | RGB | Color name |
194| ------------- | ----------- | ---------- |
195| A -> Adenine | (0,0,255) | Blue |
196| G -> Guanine | (0,100,0) | Green |
197| C -> Cytosine | (255,0,0) | Red |
198| T -> Thymine | (255,255,0) | Yellow |
199
200With this in mind we can create a simple algorithm to create PNG representation of a DNA sequence.
201
202```pascal
203{ Algorithm 2: Naive DNA to PNG encode from FASTA file }
204procedure EncodeDNASequenceToPNG(f)
205begin
206 i image
207 while not eof(f) do
208 c char := buffer[0] { Read 1 char from buffer }
209 case c of
210 'A': color := RGB(0, 0, 255) { Blue }
211 'G': color := RGB(0, 100, 0) { Green }
212 'C': color := RGB(255, 0, 0) { Red }
213 'T': color := RGB(255, 255, 0) { Yellow }
214 drawRect(i, [x, y], color)
215 save(i) { Save PNG image }
216end
217```
218
219## Encoding text file in practice
220
221In 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.
222
223> How wonderful that we have met with a paradox. Now we have some hope of making progress.
224> ― Niels Bohr
225
226First we encode text file into FASTA file.
227
228```bash
229./dnae-encode -i quote.txt -o quote.fa
2302019/01/10 00:38:29 Gathering input file stats
2312019/01/10 00:38:29 Starting encoding ...
232 106 B / 106 B [==================================] 100.00% 0s
2332019/01/10 00:38:29 Saving to FASTA file ...
2342019/01/10 00:38:29 Output FASTA file length is 438 B
2352019/01/10 00:38:29 Process took 987.263µs
2362019/01/10 00:38:29 Done ...
237```
238
239Output of `quote.fa` file contains the encoded DNA sequence in ASCII format.
240
241```text
242>SEQ1
243GACAGCTTGTGTACAAGTGTGCTTGCTCGCGAGCGGGTACGCGCGTGGGCTAACAAGTGA
244GCCAGCAGGTGAACAAGTGTGCGGACAAGCCAGCAGGTGCGCGGACAAGCTGGCGGGTGA
245ACAAGTGTGCCGGTGAGCCAACAAGCAGACAAGTAAGCAGGTACGCAGGCGAGCTTGTCA
246ACTCACAAGATCGCTTGTGTACAAGTGTGCGGACAAGCCAGCAGGTGCGCGGACAAGTAT
247GCTTGCTGGCGGACAAGCCAGCTTGTAAGCGGACAAGCTTGCGCACAAGCTGGCAGGCCT
248GCCGGCTCGCGTACAAATTCACAAGTAAGTACGCTTGCGTGTACGCGGGTATGTATACTC
249AACCTCACCAAACGGGACAAGATCGCCGGCGGGCTAGTATACAAGAACGCTTGCCAGTAC
250AACC
251```
252
253Then we encode FASTA file from previous operation to encode this data into PNG.
254
255```bash
256./dnae-png -i quote.fa -o quote.png
2572019/01/10 00:40:09 Gathering input file stats ...
2582019/01/10 00:40:09 Deconstructing FASTA file ...
2592019/01/10 00:40:09 Compositing image file ...
260 424 / 424 [==================================] 100.00% 0s
2612019/01/10 00:40:09 Saving output file ...
2622019/01/10 00:40:09 Output image file length is 1.1 kB
2632019/01/10 00:40:09 Process took 19.036117ms
2642019/01/10 00:40:09 Done ...
265```
266
267After encoding into PNG format this file looks like this.
268
269![Encoded Quote in PNG format](/files/dna-sequence/quote.png)
270
271The larger the input stream is the larger the PNG file would be.
272
273Compiled basic Hello World C program with [GCC](https://www.gnu.org/software/gcc/) would [look like](/files/dna-sequence/sample.png).
274
275```c
276// gcc -O3 -o sample sample.c
277#include <stdio.h>
278
279main() {
280 printf("Hello, world!\n");
281 return 0;
282}
283```
284
285## Toolkit for encoding data
286
287I have created a toolkit with two main programs:
288- dnae-encode (encodes file into FASTA file)
289- dnae-png (encodes FASTA file into PNG)
290
291Toolkit with full source code is available on [github.com/mitjafelicijan/dna-encoding](https://github.com/mitjafelicijan/dna-encoding).
292
293### dnae-encode
294
295```bash
296> ./dnae-encode --help
297usage: dnae-encode --input=INPUT [<flags>]
298
299A command-line application that encodes file into DNA sequence.
300
301Flags:
302 --help Show context-sensitive help (also try --help-long and --help-man).
303 -i, --input=INPUT Input file (ASCII or binary) which will be encoded into DNA sequence.
304 -o, --output="out.fa" Output file which stores DNA sequence in FASTA format.
305 -s, --sequence=SEQ1 The description line (defline) or header/identifier line, gives a name and/or a unique identifier for the sequence.
306 -c, --columns=60 Row characters length (no more than 120 characters). Devices preallocate fixed line sizes in software.
307 --version Show application version.
308```
309
310### dnae-png
311
312```bash
313> ./dnae-png --help
314usage: dnae-png --input=INPUT [<flags>]
315
316A command-line application that encodes FASTA file into PNG image.
317
318Flags:
319 --help Show context-sensitive help (also try --help-long and --help-man).
320 -i, --input=INPUT Input FASTA file which will be encoded into PNG image.
321 -o, --output="out.png" Output file in PNG format that represents DNA sequence in graphical way.
322 -s, --size=10 Size of pairings of DNA bases on image in pixels (lower resolution lower file size).
323 --version Show application version.
324```
325
326## Benchmarks
327
328First we generate some binary sample data with dd.
329
330```bash
331dd 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
332```
333
334Our freshly generated 1KB file looks something like this (its full of garbage data as intended).
335
336![Sample binary file 1KB](/files/dna-sequence/sample-binary-file.png)
337
338We create following binary files:
339- 1KB.bin
340- 10KB.bin
341- 100KB.bin
342- 1MB.bin
343- 10MB.bin
344- 100MB.bin
345
346After this we create FASTA files for all the binary files by encoding them into DNA sequence.
347
348```bash
349./dnae-encode -i 100MB.bin -o 100MB.fa
350```
351
352Then we GZIP all the FASTA files to see how much the can be compressed.
353
354```bash
355gzip -9 < 10MB.fa > 10MB.fa.gz
356```
357
358<script src="//cdn.plot.ly/plotly-latest.min.js"></script>
359
360**Speed of encoding binary file into FASTA format.**
361
362<div id="encoding-benchmarks"></div>
363<script>
364(function(){
365 var trace1 = {
366 x: ['1KB.bin', '10KB.bin', '100KB.bin', '1MB.bin', '10MB.bin', '100MB.bin'],
367 y: [5.625224, 32.679975, 112.864416, 872.887675, 8472.693202, 85525.178217],
368 type: 'scatter',
369 };
370 var data = [trace1];
371 Plotly.newPlot("encoding-benchmarks", data, {
372 legend: {"orientation": "h"},
373 height: 300,
374 margin: { l: 50, r: 0, b: 50, t: 30, pad: 0 },
375 yaxis: { title: "execution time in milliseconds", titlefont: { size: 12 } },
376 });
377})();
378</script>
379
380**File sizes of encoded files and also GZIP-ed variations.**
381
382<div id="size-benchmarks"></div>
383<script>
384(function(){
385 var trace1 = {
386 x: ['1KB.bin', '10KB.bin', '100KB.bin', '1MB.bin', '10MB.bin', '100MB.bin'],
387 y: [4.1, 40.7, 406.7, 4100, 40700, 406700],
388 name: 'FASTA file size',
389 type: 'bar',
390 };
391 var trace2 = {
392 x: ['1KB.bin', '10KB.bin', '100KB.bin', '1MB.bin', '10MB.bin', '100MB.bin'],
393 y: [1.4, 13, 121, 1200, 12000, 118000],
394 name: 'FASTA GZIPPED file size',
395 type: 'bar',
396 };
397 var data = [trace1, trace2];
398 Plotly.newPlot("size-benchmarks", data, {
399 legend: {"orientation": "h"},
400 height: 300,
401 margin: { l: 50, r: 0, b: 50, t: 30, pad: 0 },
402 yaxis: { title: "size in kilobytes", titlefont: { size: 12 } },
403 barmode: 'stack'
404 });
405})();
406</script>
407
408[Download ODS file with benchmarks](/files/dna-sequence/benchmarks.ods).
409
410## References
411
412[^1]: https://www.techopedia.com/definition/948/encoding
413[^2]: https://www.dna-worldwide.com/resource/160/history-dna-timeline
414[^3]: https://opentextbc.ca/biology/chapter/9-1-the-structure-of-dna/
415[^4]: https://arxiv.org/abs/1801.04774
416[^5]: https://en.wikipedia.org/wiki/FASTA_format