-
Notifications
You must be signed in to change notification settings - Fork 0
/
code_error_correction.html
474 lines (473 loc) · 21.5 KB
/
code_error_correction.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="[MAZ01001.github.io] Automatic error correction with Hamming codes - self-correcting text">
<meta name="author" content="MAZ01001">
<link rel="apple-touch-icon" sizes="180x180" href="../img/apple-touch-icon.png">
<link rel="icon" type="image/x-icon" href="../img/MAZ_logo.svg">
<link rel="icon" type="image/png" sizes="32x32" href="../img/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="../img/favicon-16x16.png">
<link rel="manifest" href="../img/site.webmanifest">
<link rel="mask-icon" href="../img/safari-pinned-tab.svg" color="#ff9900">
<link rel="shortcut icon" href="../img/favicon.ico">
<meta name="msapplication-TileColor" content="#da532c">
<meta name="msapplication-config" content="../img/browserconfig.xml">
<meta name="theme-color" content="#ffffff">
<title>Error correction</title>
<!--
TODO refactoring/-formating code & documentation
TODO add Golay Code ~ https://youtu.be/Tmx-v4FiP6I & https://en.wikipedia.org/wiki/Binary_Golay_code & https://mathworld.wolfram.com/GolayCode.html
Thanks to:
3b1b (theory): https://youtu.be/X8jsijhllIA
3b1b (part 2 code): https://youtu.be/b3NxrZOu_CE
ben eater (practice): https://youtu.be/h0jloehRKas
> interactive web js: https://harryli0088.github.io/hamming-code/
> minecraft redstone: https://www.reddit.com/r/3Blue1Brown/comments/iochkl/
-->
<style>
body{
background-color: #000;
color: #0f0;
padding: 0;
font-family: 'Times New Roman', Times, serif;
font-size: large;
}
h1{text-align: center;}
input#txtIn,input#txtOut{width: 60%;}
input#noise{width: 3em;}
div#reg div{display: inline-block;}
textarea,input,select{
background-color: #000;
color: #0f0;
}
div#byteSizeBlock{
background-color: #111;
padding-left: 1em;
}
div#useTxtBlock{
background-color: #020;
padding-left: 1em;
}
select#method{
width: fit-content;
font-size: large;
vertical-align: middle;
}
div.bit{
text-align: center;
width: 100%;
background-color: #333;
}
div.txt{
text-align: center;
width: 100%;
background-color: #030;
}
div#rerunBlock{
padding-bottom: 3px;
text-align: center;
width: 100%;
}
input#rerun{
border-color: #f90;
border-radius: 8px;
border-width: 4px;
}
select#regByte{
border-color: #000;
border-radius: 8px;
border-width: 3px;
}
div#bitErrNoteBlock{
padding-top: 3px;
background-color: #600;
text-align: center;
width: 100%;
}
div#noiseBlock{
position: relative;
transform: translateX(-50%);
width: max-content;
left: 50%;
}
div#reg{
display: inline-block;
width: calc(100% - 3em);
background-color: #000;
font-family: consolas, 'Courier New', Courier, monospace;
border: 1px solid #777;
}
textarea#bitErrNote{
width: min(505px, 90%);
height: 1.5em;
min-height: 1.5em;
max-height: 32em;
resize: vertical;
}
div#regBlock{
padding-top: 3px;
padding-bottom: 3px;
text-align: center;
width: 100%;
background-color: #770;
}
textarea#bitIn, textarea#bitOut{
width: calc(100% - 4em);
height: 1.5em;
min-height: 1.5em;
max-height: 16em;
resize: vertical;
font-family: consolas, 'Courier New', Courier, monospace;
font-size: x-small;
}
</style>
<script>
/*
([bit; address_pattern] (check all binary 1's and 'even the total count' by changing self))
parrity bits in binary:
0 (xxxxxxxx) (check all) [gets ignored by the other checks]
1 (xxxxxxx1) (check 1 every 2)
2 (xxxxxx1x) (check 2 every 4)
4 (xxxxx1xx) (check 4 every 8)
8 (xxxx1xxx) (check 8 every 16)
16 (xxx1xxxx) (check 16 every 32)
32 (xx1xxxxx) (check 32 every 64)
64 (x1xxxxxx) (check 64 every 128)
128 (1xxxxxxx) (check 128 every 256)
256....
*/
let method,useTxt,txtIn,txtOut,noise,bitIn,bitOut,byteSize,bitErrNote,reg,rerun,
clog=[{"byte":0,"random":"","og":"","h_encode":"","errFlip":"","h_decode":"","h_extract":""}];
function setup(){
method = document.getElementById('method');
useTxt = document.getElementById('useTxt');
txtIn = document.getElementById('txtIn');
txtOut = document.getElementById('txtOut');
noise = document.getElementById('noise');
bitIn = document.getElementById('bitIn');
bitOut = document.getElementById('bitOut');
byteSize = document.getElementById('byteSize');
bitErrNote = document.getElementById('bitErrNote');
reg = document.getElementById('reg');
regByte =document.getElementById('regByte');
rerun = document.getElementById('rerun');
useTxt.addEventListener('change',e=>{
if (useTxt.checked){
document.getElementById('txtInBlock').hidden=false;
document.getElementById('txtOutBlock').hidden=false;
} else {
document.getElementById('txtInBlock').hidden=true;
document.getElementById('txtOutBlock').hidden=true;
}
});
txtIn.addEventListener('input',e=>{
bitIn.value=txtIn.value.split('').map(ee=>{return unicodeToBinary(ee)}).join(' ');
if(byteSize.value>'0'){
let tmp = bitIn.value.split(" ");
for (let i = 0; i < tmp.length; i++) {
tmp[i] = tmp[i].padStart(byteSize.value,'0');
if(tmp[i].length > byteSize.value){
tmp.splice(i,1);
i--;
}
}
bitIn.value = tmp.join(" ");
txtIn.value=bitIn.value.split(' ').map(ee=>{let tmpp=[];for(let ii=0;ii<e.length;ii++){tmpp.push(parseInt(ee[ii],2))}return binaryToUnicode(tmpp)}).join('');
}
recode(method.value,bitIn.value,byteSize.value,noise.value);
});
bitIn.addEventListener('change',e=>{
bitIn.value = bitIn.value.replace(/[^01 ]+/gm," ").replace(/(?:\s0+|^0+)/g," ")
.replace(/\s\s+/g," ").replace(/^\s?/,"").replace(/\s?$/,"");
if(byteSize.value>'0'){
let tmp = bitIn.value.split(" ");
for (let i = 0; i < tmp.length; i++) {
tmp[i] = tmp[i].padStart(byteSize.value,'0');
if(tmp[i].length > byteSize.value){
tmp.splice(i,1);
i--;
}
}
bitIn.value = tmp.join(" ");
}
txtIn.value=bitIn.value.split(' ').map(e=>{let tmp=[];for(let i=0;i<e.length;i++){tmp.push(parseInt(e[i],2))}return binaryToUnicode(tmp)}).join('');
recode(method.value,bitIn.value,byteSize.value,noise.value);
});
byteSize.addEventListener('change',e=>{
let tmp = bitIn.value.split(" ");
for (let i = 0; i < tmp.length; i++) {
tmp[i] = tmp[i].replace(/(?:\s0+|^0+)/g," ").replace(/^\s?/,"");
if(byteSize.value>'0'){
tmp[i] = tmp[i].padStart(byteSize.value,'0');
if(tmp[i].length > byteSize.value){
tmp.splice(i,1);
i--;
}
}
}
bitIn.value = tmp.join(" ");
txtIn.value=bitIn.value.split(' ').map(e=>{let tmp=[];for(let i=0;i<e.length;i++){tmp.push(parseInt(e[i],2))}return binaryToUnicode(tmp)}).join('');
recode(method.value,bitIn.value,byteSize.value,noise.value);
});
noise.addEventListener('change',e=>{
let tmp = bitIn.value.split(" ");
for (let i = 0; i < tmp.length; i++) {
tmp[i] = tmp[i].replace(/(?:\s0+|^0+)/g," ").replace(/^\s?/,"");
if(byteSize.value>'0'){
tmp[i] = tmp[i].padStart(byteSize.value,'0');
if(tmp[i].length > byteSize.value){
tmp.splice(i,1);
i--;
}
}
}
bitIn.value = tmp.join(" ");
txtIn.value=bitIn.value.split(' ').map(e=>{let tmp=[];for(let i=0;i<e.length;i++){tmp.push(parseInt(e[i],2))}return binaryToUnicode(tmp)}).join('');
recode(method.value,bitIn.value,byteSize.value,noise.value);
});
rerun.addEventListener('click',e=>{
let tmp = bitIn.value.split(" ");
for (let i = 0; i < tmp.length; i++) {
tmp[i] = tmp[i].replace(/(?:\s0+|^0+)/g," ").replace(/^\s?/,"");
if(byteSize.value>'0'){
tmp[i] = tmp[i].padStart(byteSize.value,'0');
if(tmp[i].length > byteSize.value){
tmp.splice(i,1);
i--;
}
}
}
bitIn.value = tmp.join(" ");
txtIn.value=bitIn.value.split(' ').map(e=>{let tmp=[];for(let i=0;i<e.length;i++){tmp.push(parseInt(e[i],2))}return binaryToUnicode(tmp)}).join('');
recode(method.value,bitIn.value,byteSize.value,noise.value);
});
regByte.addEventListener('change',e=>{
let tmp4={"h_encode":clog[regByte.value].h_encode,"h_decode":clog[regByte.value].h_decode,"errFlip":clog[regByte.value].errFlip},
tmp4ln1 = "",
tmp4ln2 = "";
for (let i = 0; i < (tmp4.h_encode).length; i++) {
tmp4ln1 += ` ${tmp4.h_encode[i]}`;
if (tmp4.h_encode[i] == tmp4.h_decode.str[i]){
if (tmp4.h_encode[i]==tmp4.errFlip[i]){tmp4ln2 += ` ${tmp4.h_decode.str[i]}`;}
else {tmp4ln2 += ` <div style="color: #f0f;">${tmp4.h_decode.str[i]}</div>`;}
} else {tmp4ln2 += ` <div style="color: #f00;">${tmp4.h_decode.str[i]}</div>`;}
}
tmp4ln1 = tmp4ln1.replaceIndex(0,'',1);
tmp4ln2 = tmp4ln2.replaceIndex(0,'',1);
reg.innerHTML=`${tmp4ln1}<hr>${tmp4ln2}`;
});
}
//recodes the bytes incl. noise
function recode(type="",dataBits="",bitPerByte=0,errVal=0.0){
switch (type) {
case "hamming":
{
/*{
let testString = "rfukdbgu🤣🤦♂️😒🌚👌😂🤔😉₯﷼૱௹⨌௹﷼⨻";
let bitString=testString.split('').map(ee=>{return unicodeToBinary(ee)}).join(' ');
let backToText=bitString.split(' ').map(ee=>{let tmpp=[];for(let ii=0;ii<e.length;ii++){tmpp.push(parseInt(ee[ii],2))}return binaryToUnicode(tmpp)}).join('');
console.log(`${testString}\n${bitString}\n${backToText}`);
}*/
//log2(totalsize)=paritysize
let bitStream = dataBits.split(" "),tmp,tmp2,tmp3,tmpErr;
tmpErr="";
clog=[];
for (let i = 0; i < bitStream.length; i++) {
clog[i]={"byte":i,"random":"","og":"","h_encode":"","errFlip":"","h_decode":"","h_extract":""};
tmp3=hamming_encode(bitStream[i]);
clog[i].random=errVal*Math.random()
tmp2=randomBit(tmp3,clog[i].random);
tmp=hamming_decode(tmp2);
tmpErr+="\nByte["+i+"] \tErr("+Math.round(clog[i].random)+"%) \t"+tmp.err;
clog[i].og=bitStream[i];
clog[i].h_encode=tmp3;
clog[i].errFlip=tmp2;
clog[i].h_decode=tmp;
bitStream[i] = hamming_extractStr(tmp.str);
clog[i].h_extract=bitStream[i];
}
//log all details in the console
console.log(Date.now(),clog);
bitErrNote.value = tmpErr.substr(1);
dataBits=bitStream.join(" ");
bitOut.value=dataBits;
txtOut.value=dataBits.split(' ').map(e=>{let tmp=[];for(let i=0;i<e.length;i++){tmp.push(parseInt(e[i],2))}return binaryToUnicode(tmp)}).join('');
{
regByte.innerHTML="";
for (let i = 0; i < clog.length; i++) {
if (i==0) regByte.innerHTML+=`\n<option selected value="0">Byte[0]</option>`;
else regByte.innerHTML+=`\n<option value="${i}">Byte[${i}]</option>`;
}
let tmp4={"h_encode":clog[regByte.value].h_encode,"h_decode":clog[regByte.value].h_decode,"errFlip":clog[regByte.value].errFlip},
tmp4ln1 = "",
tmp4ln2 = "";
for (let i = 0; i < (tmp4.h_encode).length; i++) {
tmp4ln1 += ` ${tmp4.h_encode[i]}`;
if (tmp4.h_encode[i] == tmp4.h_decode.str[i]){
if (tmp4.h_encode[i]==tmp4.errFlip[i]){tmp4ln2 += ` ${tmp4.h_decode.str[i]}`;}
else {tmp4ln2 += ` <div style="color: #f0f;">${tmp4.h_decode.str[i]}</div>`;}
} else {tmp4ln2 += ` <div style="color: #f00;">${tmp4.h_decode.str[i]}</div>`;}
}
tmp4ln1 = tmp4ln1.replaceIndex(0,'',1);
tmp4ln2 = tmp4ln2.replaceIndex(0,'',1);
reg.innerHTML=`${tmp4ln1}<hr>${tmp4ln2}`;
}
}
break;
default:
break;
}
}
// flips bits randomly by % per byte/bit-string
function randomBit(byte = "", error = 0) {
if(error<=0) return byte;
let errNum = Math.round(byte.length*(error/100)),
errId = [],
tmp,exists;
for (let i = 0; i < errNum; i++) {
tmp = Math.round(Math.random()*(byte.length-1));
exists=false;
for(const id of errId){if(id==tmp){exists=true;break;}}
if (exists) i--;
else errId.push(tmp);
}
errId.sort((a, b) => a - b);
for (const id of errId) {
byte=byte.replaceIndex(id,(byte[id]=='0'?'1':'0'),1);
}
return byte;
}
//hamming_encode (bit string)
function hamming_encode(str = "01101001") {
str = str.replaceIndex(0,'0',0);
for (let i = 1; i < str.length; i*=2) {
str = str.replaceIndex(i,'0',0);
}
for (let i = 1; i < str.length; i*=2) {
let tmp = 0,
c=i;
for (let j = i; j < str.length; j += (c*2)) {
for (let k = 0; k < c; k++) {
if (str[j+k] == '1') tmp++;
}
}
if (tmp % 2 == 1) { str = str.replaceIndex(i, '1', 1) }
}
{
let tmp = 0;
for (let i = 0; i < str.length; i++) {
if (str[i] == '1') tmp++;
}
if (tmp % 2 == 1) { str = str.replaceIndex(0, '1', 1) }
}
return str;
}
//hamming_decode (corrects up to 1 error and returns object with "str" and "err" detected)
function hamming_decode(str = "01101011") {
/*
insert by 0 > 1 > 2 > 4 > 8 > 16 > 32 > 2^i < str.length
0^2^2 = 0 (0000 xor 0010 xor 0010 = 0000)
*/
let a = 0,
c = 0;
for (let i = 0; i < str.length; i++) {
if (str[i] === '1') {
a = a ^ i;
c++;
}
}
if (a==0 && c%2==0) {
return {"str":str,"err":"0 errors detected","bitAdress":a};
} else if (c%2==1) {
return {"str":str.replaceIndex(a, str[a] == '0' ? '1' : '0', 1),"err":"1 (or more (odd)) error corrected","bitAdress":a};
} else if (a!=0 && c%2==0) {
return {"str":str,"err":"2 (or more (even)) errors detected","bitAdress":a};
} else {
return {"str":str,"err":"undefined","bitAdress":a};
}
}
//hamming_extractStr (removes parity bits and returns original bit string)
function hamming_extractStr(str="01101011"){
for(let i=str.length;i>0;i--){
//powerOfTwo?
if(Math.log2(i)%1===0) str = str.replaceIndex(i, '', 1);
}
return str.replaceIndex(0, '', 1);
}
//converts text to binary string
function unicodeToBinary(char) {
return char.split('').map(function(codepoint) {
return codepoint.charCodeAt(0).toString(2);
}).join('');
}
//converts binary string to text
function binaryToUnicode(binaryList,UTF_BITS=32) {
var codepointsAsNumbers = [];
while( binaryList.length>0 ){
var codepointBits = binaryList.slice(0,UTF_BITS);
binaryList = binaryList.slice(UTF_BITS);
codepointsAsNumbers.push( parseInt(codepointBits.join(''),2) );
}
return String.fromCharCode.apply(this,codepointsAsNumbers);
}
//for adding characters at a specific index to a string, replacing a set amount of characters
String.prototype.replaceIndex = function(index,char,length=1){
return this.substr(0,index)+char+this.substr(index+length);
}
</script>
</head>
<body onload="setup()">
<div id="content">
<h1><select id="method">
<option selected value="hamming">Hamming</option>
<option disabled>WIP</option>
</select> error correction codes</h1><br>
<div id="useTxtBlock">use ASCII text<input type="checkbox" id="useTxt"></div>
<div id="byteSizeBlock">byte size <select id="byteSize">
<option selected value="0">auto</option>
<!-- could be any number > 0 -->
<option value="8">8-bit</option>
<option value="16">16-bit</option>
<option value="32">32-bit</option>
</select></div>
<div id="txtInBlock" class="txt" hidden>
Text input (sender)<br>
<input type="text" spellcheck="true" id="txtIn" placeholder="input ascii text"><br>
↓↓↓↓↓↓↓↓
</div>
<div id="bitInBlock" class="bit">
Binary Input (sender)<br>
<textarea id="bitIn" placeholder="binary input"></textarea><br>
↓↓↓↓↓↓↓↓
</div>
<hr>
<div id="noiseBlock">
random flips (per bytes) up to<input type="number" id="noise" value="0" step="1" min="0" max="100">%
</div>
<div id="rerunBlock"><input type="button" id="rerun" value="R U N"></div>
<div id="bitErrNoteBlock">
<textarea rows="2" readonly id="bitErrNote" placeholder="error note"></textarea>
</div>
<!-- maybe add custom bit errors (in far future) -->
<div id="regBlock">
<select id="regByte">
<option selected disabled>Byte</option>
</select>
<div id="reg"><div style="color: #555;">shows selected encoded byte and highlights errors</div></div>
</div>
<hr>
<div id="bitOutBlock" class="bit">
↓↓↓↓↓↓↓↓<br>
Binary Output (receiver)<br>
<textarea id="bitOut" readonly placeholder="binary output"></textarea>
</div>
<div id="txtOutBlock" class="txt" hidden>
↓↓↓↓↓↓↓↓<br>
<input type="text" id="txtOut" readonly placeholder="output ascii text"><br>
Text output (receiver)
</div>
</div>
</body>
</html>