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