-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
810 lines (695 loc) · 25.8 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
import datetime
from flask import Flask, render_template_string, request, jsonify
import os
import psutil
from dna_storage import (
DNAStorageSystem,
ErrorCorrection,
DNAPosition,
ModificationState,
)
app = Flask(__name__)
# Initialize the storage system
storage_system = DNAStorageSystem()
error_correction = ErrorCorrection()
# Store the current DNA sequence in memory
current_dna_sequence = None
@app.route("/")
def index():
return render_template_string(TEMPLATE)
@app.route("/health")
def health_check():
return {
"status": "healthy",
"timestamp": datetime.datetime.now().isoformat(),
"memory_usage": psutil.Process().memory_info().rss / 1024 / 1024, # MB
"cpu_percent": psutil.cpu_percent(),
}
@app.route("/ping")
def ping():
# Lightweight endpoint just for uptime monitoring
return {"status": "ok"}, 200
@app.route("/encode", methods=["POST"])
def encode():
global current_dna_sequence
data = request.json.get("data", "")
# Add error correction
encoded_data = error_correction.encode(data)
# Convert to DNA
current_dna_sequence = storage_system.encode_to_dna(encoded_data)
# Prepare sequence for visualization
sequence_viz = []
for pos in current_dna_sequence:
mods = []
if pos.modifications.methylated:
mods.append("Me")
if pos.modifications.hydroxymethylated:
mods.append("hMe")
if pos.modifications.formylated:
mods.append("fC")
sequence_viz.append(
{"base": pos.base, "modifications": mods, "backbone": pos.backbone}
)
return jsonify(
{
"original_data": data,
"encoded_data": encoded_data,
"dna_sequence": sequence_viz,
}
)
@app.route("/decode", methods=["GET"])
def decode():
global current_dna_sequence
if current_dna_sequence is None:
return jsonify({"error": "No DNA sequence to decode"}), 400
# Decode DNA back to binary
decoded_data = storage_system.decode_from_dna(current_dna_sequence)
final_data = error_correction.decode(decoded_data)
return jsonify({"decoded_data": final_data})
@app.route("/reverse", methods=["POST"])
def reverse():
try:
data = request.json.get("dna_sequence", [])
print("Received DNA sequence:", data)
if not data:
return jsonify({"error": "No DNA sequence provided"}), 400
# Convert the JSON DNA sequence to proper DNAPosition objects
dna_sequence = []
for pos in data:
# Create DNA position
dna_pos = DNAPosition(pos["base"])
# Set modifications
dna_pos.modifications = ModificationState(
methylated="Me" in pos["modifications"],
hydroxymethylated="hMe" in pos["modifications"],
formylated="fC" in pos["modifications"],
)
# Set backbone
dna_pos.backbone = pos.get("backbone", "standard")
dna_sequence.append(dna_pos)
print("Created DNA sequence objects:", [str(pos) for pos in dna_sequence])
# Decode DNA back to binary
binary_data = storage_system.decode_from_dna(dna_sequence)
if binary_data is None:
return jsonify({"error": "Failed to decode DNA sequence"}), 400
print("Binary data after decoding:", binary_data)
# Apply error correction decoding
error_corrected_data = error_correction.decode(binary_data)
if error_corrected_data is None:
return jsonify({"error": "Failed to apply error correction"}), 400
print(
"Final decoded result:",
{"binary_data": binary_data, "error_corrected_data": error_corrected_data},
)
return jsonify(
{"binary_data": binary_data, "error_corrected_data": error_corrected_data}
)
except Exception as e:
print("Error during decoding:", str(e))
return jsonify({"error": f"Failed to decode DNA sequence: {str(e)}"}), 400
# HTML template as a string with animation
TEMPLATE = """
<!DOCTYPE html>
<html>
<head>
<title>DNA Storage Interface</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 900px;
margin: 0 auto;
padding: 20px;
background-color: #f5f5f5;
}
.container {
background-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.animation-container {
margin: 20px 0;
padding: 20px;
background-color: #f8f9fa;
border-radius: 4px;
min-height: 200px;
}
.dna-position {
display: inline-block;
margin: 5px;
padding: 10px;
background-color: #e9ecef;
border-radius: 4px;
position: relative;
transition: all 0.5s ease;
opacity: 0;
}
.dna-position.visible {
opacity: 1;
}
.methyl-group {
position: absolute;
top: -10px;
right: -5px;
color: red;
font-size: 20px;
opacity: 0;
transition: opacity 0.5s ease;
}
.methyl-group.visible {
opacity: 1;
}
.binary-bit {
display: inline-block;
margin: 5px;
padding: 10px;
background-color: #e9ecef;
border-radius: 4px;
transition: all 0.5s ease;
}
.conversion-arrow {
display: block;
text-align: center;
font-size: 24px;
margin: 10px 0;
color: #007bff;
}
.btn {
background-color: #007bff;
color: white;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
}
.btn:hover {
background-color: #0056b3;
}
.step-display {
margin: 10px 0;
font-weight: bold;
color: #007bff;
}
.result {
margin-top: 20px;
padding: 10px;
background-color: #e9ecef;
border-radius: 4px;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
}
.animate-in {
animation: fadeIn 0.5s ease forwards;
}
/* New styles for density visualization */
.density-container {
margin: 20px 0;
padding: 20px;
background-color: #fff;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.storage-layer {
margin: 15px 0;
padding: 10px;
border: 1px solid #dee2e6;
border-radius: 4px;
}
.layer-title {
font-weight: bold;
margin-bottom: 10px;
color: #0056b3;
}
.density-bit {
display: inline-block;
width: 30px;
height: 30px;
margin: 2px;
line-height: 30px;
text-align: center;
border-radius: 4px;
font-family: monospace;
transition: all 0.3s ease;
}
.base-bit {
background-color: #e9ecef;
}
.methyl-bit {
background-color: #f8d7da;
}
.combined-container {
position: relative;
margin-top: 20px;
padding: 15px;
background-color: #f8f9fa;
border-radius: 4px;
}
.density-explanation {
margin: 10px 0;
padding: 10px;
background-color: #e7f5ff;
border-radius: 4px;
font-size: 0.9em;
}
.density-stats {
margin-top: 15px;
padding: 10px;
background-color: #d4edda;
border-radius: 4px;
}
.arrow-connector {
text-align: center;
color: #6c757d;
margin: 10px 0;
}
/* New styles for enzyme animation */
.enzyme {
width: 40px;
height: 40px;
background-color: #007bff;
border-radius: 50%;
position: absolute;
display: flex;
align-items: center;
justify-content: center;
color: white;
font-size: 12px;
transition: all 0.5s ease;
cursor: pointer;
z-index: 100;
}
.methyl-group {
position: absolute;
top: -10px;
right: -5px;
color: red;
font-size: 20px;
opacity: 0;
transition: opacity 0.3s ease;
}
.dna-sequence {
position: relative;
min-height: 100px;
margin: 40px 0;
padding: 20px;
background-color: #f8f9fa;
border-radius: 8px;
}
.dna-position {
display: inline-block;
margin: 5px;
padding: 15px;
background-color: #e9ecef;
border-radius: 4px;
position: relative;
font-size: 18px;
font-weight: bold;
}
.enzyme-info {
margin: 20px 0;
padding: 15px;
background-color: #e7f5ff;
border-radius: 8px;
font-size: 0.9em;
}
.step-explanation {
margin: 10px 0;
padding: 10px;
background-color: #fff3cd;
border-radius: 4px;
display: none;
}
@keyframes pulse {
0% { transform: scale(1); }
50% { transform: scale(1.1); }
100% { transform: scale(1); }
}
.enzyme.active {
animation: pulse 1s infinite;
}
.control-panel {
margin: 20px 0;
padding: 10px;
background-color: #f8f9fa;
border-radius: 4px;
}
</style>
</head>
<body>
<div class="container">
<h1>DNA Storage System</h1>
<!-- Binary to DNA Section -->
<div class="form-group">
<h2>Binary to DNA: Encode Data</h2>
<form id="encodeForm">
<input type="text" id="inputData" placeholder="Enter binary data (e.g., 10110010)"
pattern="[01]+" required style="width: 300px; padding: 5px;">
<button type="submit" class="btn">Encode</button>
</form>
</div>
<!-- DNA to Binary Section -->
<div class="dna-input-container">
<h2>DNA to Binary: Reverse Operation</h2>
<div id="dnaInputContainer">
<!-- DNA positions will be added here -->
</div>
<button onclick="addDNAPosition()" class="add-position-btn">Add DNA Position</button>
<button onclick="convertDNAToBinary()" class="btn">Convert to Binary</button>
<div class="validation-message" id="validationMessage"></div>
</div>
<div class="animation-container">
<div class="step-display" id="stepDisplay">Step: Input Data</div>
<div id="binaryContainer"></div>
<div class="conversion-arrow">↓</div>
<div id="errorCorrectionContainer"></div>
<div class="conversion-arrow">↓</div>
<div id="dnaContainer"></div>
</div>
<div class="result" id="result"></div>
<div class="density-container">
<h3>Information Density Visualization</h3>
<div class="storage-layer">
<div class="layer-title">Layer 1: Base Sequence Storage</div>
<div id="baseLayer"></div>
<div class="density-explanation">
Each DNA base (A, T, C, G) can store 2 bits of information (2² = 4 possibilities)
</div>
</div>
<div class="arrow-connector">+</div>
<div class="storage-layer">
<div class="layer-title">Layer 2: Methylation State</div>
<div id="methylLayer"></div>
<div class="density-explanation">
Each position can be methylated (1) or unmethylated (0), adding 1 extra bit per position
</div>
</div>
<div class="arrow-connector">↓</div>
<div class="combined-container">
<div class="layer-title">Combined Storage Density</div>
<div id="combinedLayer"></div>
<div class="density-explanation">
Total bits per position = 2 (base) + 1 (methylation) = 3 bits
</div>
</div>
<div class="density-stats" id="densityStats">
Loading density statistics...
</div>
</div>
</div>
</div>
<script>
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function animateConversion(originalData, encodedData, dnaSequence) {
// Clear previous animations
document.getElementById('binaryContainer').innerHTML = '';
document.getElementById('errorCorrectionContainer').innerHTML = '';
document.getElementById('dnaContainer').innerHTML = '';
// Step 1: Show original binary
document.getElementById('stepDisplay').textContent = 'Step 1: Original Binary Data';
const binaryContainer = document.getElementById('binaryContainer');
for (let bit of originalData) {
const bitElement = document.createElement('div');
bitElement.className = 'binary-bit';
bitElement.textContent = bit;
binaryContainer.appendChild(bitElement);
await sleep(200);
}
// Step 2: Show error correction
await sleep(500);
document.getElementById('stepDisplay').textContent = 'Step 2: Error Correction (3x Redundancy)';
const errorContainer = document.getElementById('errorCorrectionContainer');
for (let bit of encodedData) {
const bitElement = document.createElement('div');
bitElement.className = 'binary-bit';
bitElement.textContent = bit;
errorContainer.appendChild(bitElement);
await sleep(100);
}
// Step 3: Convert to DNA
await sleep(500);
document.getElementById('stepDisplay').textContent = 'Step 3: DNA Encoding with Modifications';
const dnaContainer = document.getElementById('dnaContainer');
for (let pos of dnaSequence) {
const posElement = document.createElement('div');
posElement.className = 'dna-position';
posElement.innerHTML = `<strong>${pos.base}</strong>`;
dnaContainer.appendChild(posElement);
await sleep(200);
posElement.classList.add('visible');
if (pos.modifications.includes('Me')) {
const methylGroup = document.createElement('div');
methylGroup.className = 'methyl-group';
methylGroup.innerHTML = '•';
posElement.appendChild(methylGroup);
await sleep(200);
methylGroup.classList.add('visible');
}
}
document.getElementById('stepDisplay').textContent = 'Encoding Complete!';
}
// Event listener for the encode form
document.addEventListener('DOMContentLoaded', function() {
const encodeForm = document.getElementById('encodeForm');
if (encodeForm) {
encodeForm.onsubmit = function(e) {
e.preventDefault();
const data = document.getElementById('inputData').value;
fetch('/encode', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({data: data}),
})
.then(response => response.json())
.then(data => {
animateConversion(data.original_data, data.encoded_data, data.dna_sequence);
updateDensityVisualization(data.dna_sequence);
document.getElementById('result').innerHTML =
`<strong>Encoded Data:</strong><br>Original: ${data.original_data}<br>` +
`With Error Correction: ${data.encoded_data}`;
})
.catch(error => {
console.error('Encoding error:', error);
document.getElementById('result').innerHTML =
`<strong>Error:</strong><br>Failed to encode data: ${error.message}`;
});
};
}
});
async function decodeCurrentSequence() {
document.getElementById('stepDisplay').textContent = 'Decoding DNA Sequence...';
try {
const response = await fetch('/decode', {
method: 'GET',
});
const data = await response.json();
document.getElementById('result').innerHTML +=
`<br><strong>Decoded Data:</strong><br>${data.decoded_data}`;
document.getElementById('stepDisplay').textContent = 'Decoding Complete!';
} catch (error) {
console.error('Decoding error:', error);
document.getElementById('result').innerHTML +=
`<br><strong>Error:</strong><br>Failed to decode sequence: ${error.message}`;
}
}
async function updateDensityVisualization(dnaSequence) {
if (!dnaSequence) return;
const baseLayer = document.getElementById('baseLayer');
const methylLayer = document.getElementById('methylLayer');
const combinedLayer = document.getElementById('combinedLayer');
const statsDiv = document.getElementById('densityStats');
baseLayer.innerHTML = '';
methylLayer.innerHTML = '';
combinedLayer.innerHTML = '';
let totalBits = 0;
for (let pos of dnaSequence) {
// Base layer (2 bits)
const baseBits = document.createElement('div');
baseBits.className = 'density-bit base-bit';
baseBits.textContent = pos.base;
baseLayer.appendChild(baseBits);
// Methylation layer (1 bit)
const methylBit = document.createElement('div');
methylBit.className = 'density-bit methyl-bit';
methylBit.textContent = pos.modifications.includes('Me') ? '1' : '0';
methylLayer.appendChild(methylBit);
// Combined visualization
const combinedBit = document.createElement('div');
combinedBit.className = 'density-bit';
combinedBit.style.backgroundColor = pos.modifications.includes('Me') ? '#f8d7da' : '#e9ecef';
combinedBit.textContent = pos.base;
combinedLayer.appendChild(combinedBit);
totalBits += 3; // 2 from base + 1 from methylation
await sleep(100);
}
statsDiv.innerHTML = `
<strong>Storage Density Analysis:</strong><br>
Base Sequence: ${dnaSequence.length * 2} bits<br>
Methylation Layer: ${dnaSequence.length} bits<br>
Total Storage: ${totalBits} bits<br>
Density Increase: +50% from methylation
`;
}
function addDNAPosition() {
const container = document.createElement('div');
container.className = 'dna-position-container';
const input = document.createElement('input');
input.type = 'text';
input.className = 'dna-base-input';
input.maxLength = 1;
input.pattern = '[ACGTacgt]';
input.required = true;
input.placeholder = 'A';
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.className = 'methylation-checkbox';
checkbox.title = 'Methylated';
const removeBtn = document.createElement('button');
removeBtn.className = 'remove-position-btn';
removeBtn.textContent = '×';
removeBtn.onclick = function() {
container.remove();
};
container.appendChild(input);
container.appendChild(checkbox);
container.appendChild(document.createElement('br'));
container.appendChild(removeBtn);
document.getElementById('dnaInputContainer').appendChild(container);
}
function validateDNAInput() {
const validBases = ['A', 'C', 'G', 'T'];
const inputs = document.getElementsByClassName('dna-base-input');
const validationMessage = document.getElementById('validationMessage');
for (let input of inputs) {
const base = input.value.toUpperCase();
if (!validBases.includes(base)) {
validationMessage.textContent = 'Invalid base detected. Please use only A, C, G, or T.';
return false;
}
}
if (inputs.length === 0) {
validationMessage.textContent = 'Please add at least one DNA position.';
return false;
}
validationMessage.textContent = '';
return true;
}
async function animateReverseConversion(dnaSequence, binaryData, errorCorrectedData) {
// Add safety checks
if (!binaryData || !errorCorrectedData) {
console.log('Missing data for animation:', { binaryData, errorCorrectedData });
return;
}
try {
// Clear previous animations
document.getElementById('binaryContainer').innerHTML = '';
document.getElementById('errorCorrectionContainer').innerHTML = '';
document.getElementById('dnaContainer').innerHTML = '';
// Step 1: Show DNA sequence
document.getElementById('stepDisplay').textContent = 'Step 1: DNA Sequence';
const dnaContainer = document.getElementById('dnaContainer');
for (let pos of dnaSequence) {
const posElement = document.createElement('div');
posElement.className = 'dna-position';
posElement.innerHTML = `<strong>${pos.base}</strong>`;
dnaContainer.appendChild(posElement);
await sleep(200);
posElement.classList.add('visible');
if (pos.modifications.includes('Me')) {
const methylGroup = document.createElement('div');
methylGroup.className = 'methyl-group';
methylGroup.innerHTML = '•';
posElement.appendChild(methylGroup);
await sleep(200);
methylGroup.classList.add('visible');
}
}
// Step 2: Show raw binary
await sleep(500);
document.getElementById('stepDisplay').textContent = 'Step 2: Raw Binary Data';
const errorContainer = document.getElementById('errorCorrectionContainer');
for (let bit of binaryData.toString()) {
const bitElement = document.createElement('div');
bitElement.className = 'binary-bit';
bitElement.textContent = bit;
errorContainer.appendChild(bitElement);
await sleep(100);
}
// Step 3: Show error corrected binary
await sleep(500);
document.getElementById('stepDisplay').textContent = 'Step 3: Error Corrected Binary';
const binaryContainer = document.getElementById('binaryContainer');
for (let bit of errorCorrectedData.toString()) {
const bitElement = document.createElement('div');
bitElement.className = 'binary-bit';
bitElement.textContent = bit;
binaryContainer.appendChild(bitElement);
await sleep(200);
}
document.getElementById('stepDisplay').textContent = 'Reverse Conversion Complete!';
} catch (error) {
console.error('Animation error:', error);
document.getElementById('stepDisplay').textContent = 'Animation failed: ' + error.message;
}
}
function convertDNAToBinary() {
if (!validateDNAInput()) {
return;
}
const dnaSequence = [];
const containers = document.getElementsByClassName('dna-position-container');
for (let container of containers) {
const base = container.querySelector('.dna-base-input').value.toUpperCase();
const isMethylated = container.querySelector('.methylation-checkbox').checked;
dnaSequence.push({
base: base,
modifications: isMethylated ? ['Me'] : [],
backbone: 'standard'
});
}
console.log('Sending DNA sequence:', dnaSequence);
fetch('/reverse', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({dna_sequence: dnaSequence}),
})
.then(response => response.json())
.then(data => {
console.log('Received data:', data);
if (data.error) {
document.getElementById('result').innerHTML =
`<strong>Error:</strong><br>${data.error}`;
return;
}
if (data.binary_data && data.error_corrected_data) {
document.getElementById('result').innerHTML =
`<strong>Decoded Binary Data:</strong><br>` +
`Raw Binary: ${data.binary_data}<br>` +
`Error Corrected: ${data.error_corrected_data}`;
animateReverseConversion(dnaSequence, data.binary_data, data.error_corrected_data);
} else {
document.getElementById('result').innerHTML =
`<strong>Error:</strong><br>Failed to decode DNA sequence: Invalid response data`;
}
})
.catch(error => {
console.error('Error:', error);
document.getElementById('result').innerHTML =
`<strong>Error:</strong><br>Failed to decode DNA sequence: ${error.message}`;
});
}
</script>
</body>
</html>
"""
if __name__ == "__main__":
print("Starting DNA Storage Web Interface...")
port = os.environ.get("PORT", 8080)
app.run(host="0.0.0.0", port=port)