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.md346
1 files changed, 346 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..068aa32
--- /dev/null
+++ b/content/2019-01-03-encoding-binary-data-into-dna-sequence.md
@@ -0,0 +1,346 @@
1~ title: Encoding binary data into DNA sequence
2~ description: 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
3~ slug: /experiments/encoding-binary-data-into-dna-sequence.html
4~ date: 2019-01-03
5~ template: post
6~ hide: false
7
8## Initial thoughts
9
10Imagine 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.
11
12Encoding 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.
13
14More 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.
15
16As we currently stand this is still not viable but it is quite an amazing and cool technology.
17
18My 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.
19
20## Glossary
21
22**deoxyribose**
23: A five-carbon sugar molecule with a hydrogen atom rather than a hydroxyl group in the 2′ position; the sugar component of DNA nucleotides.
24
25**double helix**
26: The molecular shape of DNA in which two strands of nucleotides wind around each other in a spiral shape.
27
28**nitrogenous base**
29: A nitrogen-containing molecule that acts as a base; often referring to one of the purine or pyrimidine components of nucleic acids.
30
31**phosphate group**
32: A molecular group consisting of a central phosphorus atom bound to four oxygen atoms.
33
34**RGB**
35: 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.
36
37**GCC**
38: The GNU Compiler Collection is a compiler system produced by the GNU Project supporting various programming languages.
39
40## Data encoding
41
42**TL;DR:** Encoding involves the use of a code to change original data into a form that can be used by an external process.
43
44Encoding is the process of converting data into a format required for a number of information processing needs, including:
45
46- Program compiling and execution
47- Data transmission, storage and compression/decompression
48- Application data processing, such as file conversion
49
50Encoding can have two meanings:
51
52- 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.
53- In electronics, encoding refers to analog to digital conversion.
54
55## Quick history of DNA
56
57- **1869** - Friedrich Miescher identifies "nuclein".
58- **1900s** - The Eugenics Movement.
59- **1900** – Mendel's theories are rediscovered by researchers.
60- **1944** - Oswald Avery identifies DNA as the 'transforming principle'.
61- **1952** - Rosalind Franklin photographs crystallized DNA fibres.
62- **1953** - James Watson and Francis Crick discover the double helix structure of DNA.
63- **1965** - Marshall Nirenberg is the first person to sequence the bases in each codon.
64- **1983** - Huntington's disease is the first mapped genetic disease.
65- **1990** - The Human Genome Project begins.
66- **1995** - Haemophilus Influenzae is the first bacterium genome sequenced.
67- **1996** - Dolly the sheep is cloned.
68- **1999** - First human chromosome is decoded.
69- **2000** – Genetic code of the fruit fly is decoded.
70- **2002** – Mouse is the first mammal to have its genome decoded.
71- **2003** – The Human Genome Project is completed.
72- **2013** – DNA Worldwide and Eurofins Forensic discover identical twins have differences in their genetic makeup.
73
74## What is DNA?
75
76Deoxyribonucleic 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**.
77
78> 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.
79>
80> **-- Carl Sagan, Cosmos**
81
82The 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.
83
84![DNA](/assets/dna-sequence/dna-basics.jpg#center)
85
86*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)*
87
88## Encode binary data into DNA sequence
89
90As an input file you can use any file you want:
91- ASCII files,
92- Compiled programs,
93- Multimedia files (MP3, MP4, MVK, etc),
94- Images,
95- Database files,
96- etc.
97
98Note: 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.
99
100### Basic Encoding
101
102As 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
103
104$$ log_2(4) = log_2(2^2) = 2 bits $$
105
106using 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.
107
108| Two bits | Nucleotides |
109| -------- | ---------------- |
110| 00 | **A** (Adenine) |
111| 10 | **G** (Guanine) |
112| 01 | **C** (Cytosine) |
113| 11 | **T** (Thymine) |
114
115With this in mind we can simply encode any data by using two-bit to Nucleotides conversion
116
117```python
118{ Algorithm 1: Naive byte array to DNA encode }
119procedure EncodeToDNASequence(f) string
120begin
121 enc string
122 while not eof(f) do
123 c byte := buffer[0] { Read 1 byte from buffer }
124 bin integer := sprintf('08b', c) { Convert to string binary }
125 for e in range[0, 2, 4, 6] do
126 if e[0] == 48 and e[1] == 48 then { 0x00 - A (Adenine) }
127 enc += 'A'
128 else if e[0] == 48 and e[1] == 49 then { 0x01 - G (Guanine) }
129 enc += 'G'
130 else if e[0] == 49 and e[1] == 48 then { 0x10 - C (Cytosine) }
131 enc += 'C'
132 else if e[0] == 49 and e[1] == 49 then { 0x11 - T (Thymine) }
133 enc += 'T'
134 return enc { Return DNA sequence }
135end
136```
137
138Another 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.
139
140[Where to store big data? In DNA: Nick Goldman at TEDxPrague](https://www.youtube.com/watch?v=a4PiGWNsIEU)
141
142### FASTA file format
143
144In 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.
145
146The 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).
147
148```text
149;LCBO - Prolactin precursor - Bovine
150; a sample sequence in FASTA format
151MDSKGSSQKGSRLLLLLVVSNLLLCQGVVSTPVCPNGPGNCQVSLRDLFDRAVMVSHYIHDLSS
152EMFNEFDKRYAQGKGFITMALNSCHTSSLPTPEDKEQAQQTHHEVLMSLILGLLRSWNDPLYHL
153VTEVRGMKGAPDAILSRAIEIEEENKRLLEGMEMIFGQVIPGAKETEPYPVWSGLPSLQTKDED
154ARYSAFYNLLHCLRRDSSKIDTYLKLLNCRIIYNNNC*
155
156>MCHU - Calmodulin - Human, rabbit, bovine, rat, and chicken
157ADQLTEEQIAEFKEAFSLFDKDGDGTITTKELGTVMRSLGQNPTEAELQDMINEVDADGNGTID
158FPEFLTMMARKMKDTDSEEEIREAFRVFDKDGNGYISAAELRHVMTNLGEKLTDEEVDEMIREA
159DIDGDGQVNYEEFVQMMTAK*
160
161>gi|5524211|gb|AAD44166.1| cytochrome b [Elephas maximus maximus]
162LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV
163EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG
164LLILILLLLLLALLSPDMLGDPDNHMPADPLNTPLHIKPEWYFLFAYAILRSVPNKLGGVLALFLSIVIL
165GLMPFLHTSKHRSMMLRPLSQALFWTLTMDLLTLTWIGSQPVEYPYTIIGQMASILYFSIILAFLPIAGX
166IENY
167```
168
169FASTA format was extended by [FASTQ](https://en.wikipedia.org/wiki/FASTQ_format) format from the [Sanger Centre](https://www.sanger.ac.uk/) in Cambridge.
170
171### PNG encoded DNA sequence
172
173| Nucleotides | RGB | Color name |
174| ------------- | ----------- | ---------- |
175| A -> Adenine | (0,0,255) | Blue |
176| G -> Guanine | (0,100,0) | Green |
177| C -> Cytosine | (255,0,0) | Red |
178| T -> Thymine | (255,255,0) | Yellow |
179
180With this in mind we can create a simple algorithm to create PNG representation of a DNA sequence.
181
182```python
183{ Algorithm 2: Naive DNA to PNG encode from FASTA file }
184procedure EncodeDNASequenceToPNG(f)
185begin
186 i image
187 while not eof(f) do
188 c char := buffer[0] { Read 1 char from buffer }
189 case c of
190 'A': color := RGB(0, 0, 255) { Blue }
191 'G': color := RGB(0, 100, 0) { Green }
192 'C': color := RGB(255, 0, 0) { Red }
193 'T': color := RGB(255, 255, 0) { Yellow }
194 drawRect(i, [x, y], color)
195 save(i) { Save PNG image }
196end
197```
198
199## Encoding text file in practice
200
201In 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.
202
203> How wonderful that we have met with a paradox. Now we have some hope of making progress.
204> ― Niels Bohr
205
206First we encode text file into FASTA file.
207
208```bash
209./dnae-encode -i quote.txt -o quote.fa
2102019/01/10 00:38:29 Gathering input file stats
2112019/01/10 00:38:29 Starting encoding ...
212 106 B / 106 B [==================================] 100.00% 0s
2132019/01/10 00:38:29 Saving to FASTA file ...
2142019/01/10 00:38:29 Output FASTA file length is 438 B
2152019/01/10 00:38:29 Process took 987.263µs
2162019/01/10 00:38:29 Done ...
217```
218
219Output of `quote.fa` file contains the encoded DNA sequence in ASCII format.
220
221```text
222>SEQ1
223GACAGCTTGTGTACAAGTGTGCTTGCTCGCGAGCGGGTACGCGCGTGGGCTAACAAGTGA
224GCCAGCAGGTGAACAAGTGTGCGGACAAGCCAGCAGGTGCGCGGACAAGCTGGCGGGTGA
225ACAAGTGTGCCGGTGAGCCAACAAGCAGACAAGTAAGCAGGTACGCAGGCGAGCTTGTCA
226ACTCACAAGATCGCTTGTGTACAAGTGTGCGGACAAGCCAGCAGGTGCGCGGACAAGTAT
227GCTTGCTGGCGGACAAGCCAGCTTGTAAGCGGACAAGCTTGCGCACAAGCTGGCAGGCCT
228GCCGGCTCGCGTACAAATTCACAAGTAAGTACGCTTGCGTGTACGCGGGTATGTATACTC
229AACCTCACCAAACGGGACAAGATCGCCGGCGGGCTAGTATACAAGAACGCTTGCCAGTAC
230AACC
231```
232
233Then we encode FASTA file from previous operation to encode this data into PNG.
234
235```bash
236./dnae-png -i quote.fa -o quote.png
2372019/01/10 00:40:09 Gathering input file stats ...
2382019/01/10 00:40:09 Deconstructing FASTA file ...
2392019/01/10 00:40:09 Compositing image file ...
240 424 / 424 [==================================] 100.00% 0s
2412019/01/10 00:40:09 Saving output file ...
2422019/01/10 00:40:09 Output image file length is 1.1 kB
2432019/01/10 00:40:09 Process took 19.036117ms
2442019/01/10 00:40:09 Done ...
245```
246
247After encoding into PNG format this file looks like this.
248
249![Encoded Quote in PNG format](/assets/dna-sequence/quote.png)
250
251The larger the input stream is the larger the PNG file would be.
252
253Compiled basic Hello World C program with [GCC](https://www.gnu.org/software/gcc/) would [look like](/assets/dna-sequence/sample.png).
254
255```c
256// gcc -O3 -o sample sample.c
257#include <stdio.h>
258
259main() {
260 printf("Hello, world!\n");
261 return 0;
262}
263```
264
265## Toolkit for encoding data
266
267I have created a toolkit with two main programs:
268- dnae-encode (encodes file into FASTA file)
269- dnae-png (encodes FASTA file into PNG)
270
271Toolkit with full source code is available on [github.com/mitjafelicijan/dna-encoding](https://github.com/mitjafelicijan/dna-encoding).
272
273### dnae-encode
274
275```bash
276> ./dnae-encode --help
277usage: dnae-encode --input=INPUT [<flags>]
278
279A command-line application that encodes file into DNA sequence.
280
281Flags:
282 --help Show context-sensitive help (also try --help-long and --help-man).
283 -i, --input=INPUT Input file (ASCII or binary) which will be encoded into DNA sequence.
284 -o, --output="out.fa" Output file which stores DNA sequence in FASTA format.
285 -s, --sequence=SEQ1 The description line (defline) or header/identifier line, gives a name and/or a unique identifier for the sequence.
286 -c, --columns=60 Row characters length (no more than 120 characters). Devices preallocate fixed line sizes in software.
287 --version Show application version.
288```
289
290### dnae-png
291
292```bash
293> ./dnae-png --help
294usage: dnae-png --input=INPUT [<flags>]
295
296A command-line application that encodes FASTA file into PNG image.
297
298Flags:
299 --help Show context-sensitive help (also try --help-long and --help-man).
300 -i, --input=INPUT Input FASTA file which will be encoded into PNG image.
301 -o, --output="out.png" Output file in PNG format that represents DNA sequence in graphical way.
302 -s, --size=10 Size of pairings of DNA bases on image in pixels (lower resolution lower file size).
303 --version Show application version.
304```
305
306## Benchmarks
307
308First we generate some binary sample data with dd.
309
310```bash
311dd 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
312```
313
314Our freshly generated 1KB file looks something like this (its full of garbage data as intended).
315
316![Sample binary file 1KB](/assets/dna-sequence/sample-binary-file.png)
317
318We create following binary files:
319- 1KB.bin
320- 10KB.bin
321- 100KB.bin
322- 1MB.bin
323- 10MB.bin
324- 100MB.bin
325
326After this we create FASTA files for all the binary files by encoding them into DNA sequence.
327
328```bash
329./dnae-encode -i 100MB.bin -o 100MB.fa
330```
331
332Then we GZIP all the FASTA files to see how much the can be compressed.
333
334```bash
335gzip -9 < 10MB.fa > 10MB.fa.gz
336```
337
338[Download ODS file with benchmarks](/assets/dna-sequence/benchmarks.ods).
339
340## References
341
342- https://www.techopedia.com/definition/948/encoding
343- https://www.dna-worldwide.com/resource/160/history-dna-timeline
344- https://opentextbc.ca/biology/chapter/9-1-the-structure-of-dna/
345- https://arxiv.org/abs/1801.04774
346- https://en.wikipedia.org/wiki/FASTA_format