-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcodewords.js
1682 lines (1498 loc) · 59.4 KB
/
codewords.js
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
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Numbas.addExtension('codewords',['math','jme','jme-display'],function(codewords) {
function set(arr,sort,eq) {
return arr.slice().sort(sort).reduce(function(arr,b){
if(!arr.length || (eq ? !eq(arr[arr.length-1],b) : arr[arr.length-1]!=b)){
arr.push(b);
}
return arr;
},[]);
}
function keysort(key) {
if(typeof(key)=='string') {
return function(a,b) {
return a[key]>b[key] ? 1 : a[key]<b[key] ? -1 : 0;
}
} else {
return function(a,b) {
a = key(a);
b = key(b);
return a>b ? 1 : a<b ? -1 : 0;
}
}
}
/** Create a codeword with the given digits, belonging to the field `Z_{field_size}`.
* @constructor
* @memberof codewords
* @property {number} field_size
* @property {number[]} digits
* @property {number} length
* @property {string} asString
*
* @param {number[]} digits
* @param {number} field_size
*/
var Codeword = codewords.Codeword = function(digits,field_size) {
this.field_size = field_size || 2;
this.digits = digits || [];
this.digits = this.digits.map(function(d){return d%field_size});
this.length = this.digits.length;
this.asString = this.digits.join('');
}
Codeword.prototype = {
/** String representation of the word.
* @returns {string}
*/
toString: function() {
return this.asString;
},
/** LaTeX representation of the word.
* @returns {string}
*/
toLaTeX: function() {
return '\\mathtt{'+this.asString+'}';
},
/** JME representation of the word.
* @returns {string}
*/
toJME: function() {
return 'codeword("'+this.asString+'",'+this.field_size+')';
},
/** Is the word zero (are all its digits 0)?
* @returns {boolean}
*/
isZero: function() {
for(var i=0;i<this.length;i++) {
if(this.digits[i]!==0) {
return false;
}
}
return true;
},
/** Is this word the same as `word2`?
* @returns {boolean}
*/
eq: function(b) {
var a = this;
return a.field_size==b.field_size && a.length==b.length && a+''==b+'';
},
/** Return a new word which is the sum of this word and `word2`.
* @param {codewords.Codeword} w2
* @returns {codewords.Codeword}
*/
add: function(w2) {
var field_size = this.field_size;
var digits = this.digits.map(function(d1,i) {
return (d1+w2.digits[i]) % field_size;
});
return new Codeword(digits,field_size);
},
/** Subtract `word2` from this word (returns a new codeword object).
* @param {codewords.Codeword} w2
* @returns {codewords.Codeword}
*/
sub: function(w2) {
var field_size = this.field_size;
var digits = this.digits.map(function(d1,i) {
var r = (d1-w2.digits[i]) % field_size;
if(r<0) {
r += field_size;
}
return r;
});
return new Codeword(digits,field_size);
},
/** Negate this word: `w.add(w.negate()) = 0`.
* @returns {codewords.Codeword}
*/
negate: function() {
var field_size = this.field_size;
var digits = this.digits.map(function(d) {
return (field_size - d) % field_size;
});
return new Codeword(digits,field_size);
},
/** Scale this word by `n` - multiply every digit by `n`.
* @param {number} n
* @returns {codewords.Codeword}
*/
scale: function(n) {
var field_size = this.field_size;
n = n % field_size;
if(n<0) {
n += field_size;
}
var digits = this.digits.map(function(d) {
return (n*d)%field_size;
});
return new Codeword(digits,this.field_size);
},
/** Hamming weight of this word - number of non-zero digits.
* @returns {number}
*/
weight: function() {
return this.digits.reduce(function(a,b){return a+(b>0?1:0)},0);
},
/** LaTeX rendering of a Hamming square code check array for this word (only makes sense if this word is a 9-digit binary word)
* @returns {string}
*/
LaTeX_check_array: function() {
var n = Math.sqrt(this.length);
var out = '\\begin{array}{';
for(var i=0;i<n-1;i++) {
out += 'c';
}
out += '|c}\n';
for(var i=0;i<n-1;i++) {
out+=this.digits.slice(i*n,(i+1)*n).join(' & ')+' \\\\\n';
}
out += '\\hline\n';
out += this.digits.slice((n-1)*n).join(' & ')+'\n';
out += '\\end{array}';
return out;
},
/** Find all words within `radius` Hamming distance of this word.
* @param {number} radius
* @returns {codewords.Codeword[]}
*/
hamming_ball: function(radius) {
var field_size = this.field_size;
function ball(digits,radius) {
if(radius==0) {
return [digits.slice()];
}
if(digits.length==1) {
var o = [];
for(var i=0;i<field_size;i++) {
o.push([i]);
}
return o;
}
var out = [];
// for each choice of the first digit
for(var i=0;i<field_size;i++) {
var next_digits = ball(digits.slice(1),i==digits[0] ? radius : radius-1);
out = out.concat(next_digits.map(function(d) {
d.splice(0,0,i);
return d;
}));
}
return out;
}
return ball(this.digits,radius).map(function(digits){ return new Codeword(digits,field_size) });
},
/** Find all words with Hamming distance exactly `radius` from this word.
* @param {number} radius
* @returns {codewords.Codeword[]}
*/
hamming_sphere: function(radius) {
var field_size = this.field_size;
function ball(digits,radius) {
if(radius==0) {
return [digits.slice()];
}
if(digits.length==1) {
if(radius==1) {
var o = [];
for(var i=0;i<field_size;i++) {
if(i!=digits[0]) {
o.push([i]);
}
}
return o;
} else {
return [];
}
}
var out = [];
// for each choice of the first digit
for(var i=0;i<field_size;i++) {
var next_digits = ball(digits.slice(1),i==digits[0] ? radius : radius-1);
out = out.concat(next_digits.map(function(d) {
d.splice(0,0,i);
return d;
}));
}
return out;
}
return ball(this.digits,radius).map(function(digits){ return new Codeword(digits,field_size) });
}
}
/** Create a codeword object from a string representation, e.g. `Codeword.fromString("01001",2)`.
* @param {string} w
* @param {number} field_size
* @returns {codewords.Codeword}
*/
Codeword.fromString = function(w,field_size) {
w = w || '';
var ow = w;
w = w.replace(/[, ]/g,'');
if(!w.match(/^\d*$/)) {
throw(new Error(ow+" is not a valid codeword"));
}
var digits = w.split('').map(function(d){ return parseInt(d) });
if(digits.some(function(d){ return d>=field_size; })) {
throw(new Error(ow+" is not a valid codeword"));
}
return new Codeword(digits,field_size);
}
/** Comparison function to sort codewords lexicographically.
* @param {codeword.Codeword} a
* @param {codeword.Codeword} b
* @returns {number}
*/
Codeword.sort = function(a,b){
a = a+'';
b = b+'';
return a>b ? 1 : a<b ? -1 : 0
};
/** Equivalent to `w1.eq(w2)`.
* @param {codeword.Codeword} a
* @param {codeword.Codeword} b
* @returns {number}
*/
Codeword.eq = function(a,b) { return a.eq(b); }
var sort_by_weight = keysort(function(w){return w.weight()});
/** Create a zero word with the given length in the field `Z_{field_size}`.
* @param {number} word_length
* @param {number} field_size
* @returns {codewords.Codeword}
*/
var zero_word = codewords.zero_word = function(word_length,field_size) {
var digits = [];
for(var i=0;i<word_length;i++) {
digits.push(0);
}
return new Codeword(digits,field_size);
}
/** Get all words of the given length in the field `Z_{field_size}`.
* @param {number} word_length
* @param {number} field_size
* @returns {codewords.Codeword[]}
*/
var allwords = codewords.allwords = function(word_length,field_size) {
var l = [''];
for(var i=0;i<word_length;i++) {
var nl = [];
l.map(function(w) {
for(var j=0;j<field_size;j++) {
nl.push(j+''+w);
}
});
l = nl;
}
return l.map(function(w){ return Codeword.fromString(w,field_size) });
}
/** Get a random word of the given length in the field `Z_{field_size}`.
* @param {number} word_length
* @param {number} field_size
* @returns {codewords.Codeword}
*/
var random_word = codewords.random_word = function(word_length,field_size) {
var digits = [];
for(var i=0;i<word_length;i++) {
digits.push(Numbas.math.randomint(field_size));
}
return new Codeword(digits,field_size);
}
/** A random linear combination of the given words (from the field `Z_p`), i.e. `a_0*w_0 + a_1*w_1 + ... + a_n*w_n` where the `a_i` are elements of the field `Z_p`.
* @param {codewords.Codeword} basis
* @returns {codewords.Codeword}
*/
var random_combination = codewords.random_combination = function(basis) {
var field_size = basis[0].field_size;
var word_length = basis[0].length;
var t = zero_word(word_length,field_size);
for(var i=0;i<basis.length;i++) {
t = t.add(basis[i].scale(Numbas.math.randomint(field_size)));
}
return t;
}
/** Get all words generated by the given basis set.
* @param {codewords.Codeword[]} basis
* @returns {codewords.Codeword[]}
*/
var set_generated_by = codewords.set_generated_by = function(basis) {
if(!basis.length) {
return [];
}
var length = basis[0].length;
var field_size = basis[0].field_size;
var choices = allwords(basis.length,field_size);
generated = choices.map(function(choice) {
var r = zero_word(length,field_size);
choice.digits.map(function(f,i) {
r = r.add(basis[i].scale(f));
});
return r;
});
return set(generated,Codeword.sort,Codeword.eq);
}
/** Are the given list of codewords all generated by the given basis?
* False if some word is not in the set generated by basis
* @param {codewords.Codeword[]} basis
* @param {codewords.Codeword[]} codewords
* @returns {Boolean}
*/
var is_generated_by = codewords.is_generated_by = function(basis,codewords) {
if(!basis.length) {
return [];
}
var length = basis[0].length;
var field_size = basis[0].field_size;
var choices = allwords(basis.length,field_size);
for(var i=0;i<choices.length && codewords.length;i++) {
var choice = choices[i];
var r = zero_word(length,field_size);
choice.digits.map(function(f,i) {
r = r.add(basis[i].scale(f));
});
codewords = codewords.filter(function(x){return !r.eq(x)});
}
return codewords.length == 0;
}
/** Are all of the given words linearly independent of each other?
* words are linearly independent if l1w1 + l2w2 + .. +lnwn = 0 has no solution other than l1=l2=...=ln=0
* @param {codewords.Codeword[]} words
* @returns {boolean}
*/
var linearly_independent = codewords.linearly_independent = function(words) {
var coefficients = [];
for(var i=0;i<words.length;i++) {
coefficients.push(0);
}
var field_size = words[0].field_size;
var word_length = words[0].length;
var num_combinations = Math.pow(field_size,words.length);
var z = zero_word(word_length,field_size);
for(var i=1;i<num_combinations;i++) {
coefficients[0] += 1;
var j = 0;
while(coefficients[j]==field_size) {
coefficients[j] = 0;
if(j<words.length-1) {
coefficients[j+1] += 1;
}
j+=1;
}
var c = z;
for(var n=0;n<words.length;n++) {
c = c.add(words[n].scale(coefficients[n]));
}
if(c.eq(z)) {
return false;
}
}
return true;
}
/** Generate the coset containing the given word, with respect to the given generating set.
* @param {codewords.Codeword} word
* @param {codewords.Codeword[]} basis
* @returns {codewords.Codeword[]}
*/
var coset_containing = codewords.coset_containing = function(word,basis) {
var field_size = word.field_size;
var length = word.length;
var combs = set_generated_by(basis);
return combs.map(function(w2) {
return word.add(w2);
});
}
/** Generate the Slepian array corresponding to the given basis set. Each row in the result is a coset, sorted by weight.
* @param {codewords.Codeword[]} basis
* @returns {codewords.Codeword[][]}
*/
var slepian_array = codewords.slepian_array = function(basis) {
if(!basis.length) {
return [];
}
var field_size = basis[0].field_size;
var length = basis[0].length;
var base = set_generated_by(basis);
var sets = [base];
var seen = base.map(function(w){return w+''});
var all = allwords(length,field_size);
all.sort(function(r1,r2) {
var a = r1+'';
var b = r2+'';
var w1 = r1.weight();
var w2 = r2.weight();
return w1>w2 ? 1 : w1<w2 ? -1 : a>b ? 1 : a<b ? -1 : 0;
})
all.map(function(w) {
if(seen.indexOf(w+'')==-1) {
var cs = coset_containing(w,basis);
sets.push(cs);
seen = seen.concat(cs.map(function(w){return w+''}));
}
});
return sets;
}
/** Is the given word a coset leader in its coset? That is, does it have the minimum weight?
* @param {codewords.Codeword} word
* @param {codewords.Codeword[]} basis
* @returns {boolean}
*/
var is_coset_leader = codewords.is_coset_leader = function(word,basis) {
var coset = coset_containing(word,basis);
coset.sort(sort_by_weight);
return word.weight()==coset[0].weight();
}
/** Hamming distance between two words.
* @param {codewords.Codeword} a
* @param {codewords.Codeword} b
* @returns {number}
*/
var hamming_distance = codewords.hamming_distance = function(a,b) {
if(a.length!=b.length) {
return;
}
var d = 0;
for(var i=0;i<a.length;i++) {
if(a.digits[i]!=b.digits[i]) {
d += 1;
}
}
return d;
}
/** swap the ith and jth positions in array a
* @param {Array} a
* @param {number} i
* @param {number} j
*/
function swap(a,i,j){
if(i==j) {
return;
}
var x=Math.min(i,j);
var y=Math.max(i,j);
a.splice(y,0,a.splice(x,1,a.splice(y,1)[0])[0]);
}
/** Compute the multiplicative inverses of the elements of the field Z_{field_size}
* @param {number} field_size
* @returns {number[]}
*/
function get_inverses(field_size) {
var inverses = [0,1];
for(var i=2;i<field_size;i++) {
for(var j=1;j<field_size;j++) {
if((i*j)%field_size==1) {
inverses[i]=j;
break;
}
}
}
return inverses;
}
/** Put the given list of words (interpreted as a matrix) into reduced row-echelon form by reordering and taking linear combinations.
* @param {codewords.Codeword[]} basis
* @returns {codewords.Codeword[]}
*/
var reduced_row_echelon_form = codewords.reduced_row_echelon_form = function(basis) {
var field_size = basis[0].field_size;
var matrix = basis.slice();
var rows = matrix.length;
var columns = matrix[0].length;
// calculate inverses in field
var inverses = [0,1];
for(var i=2;i<field_size;i++) {
for(var j=1;j<field_size;j++) {
if((i*j)%field_size==1) {
inverses[i]=j;
break;
}
}
}
var current_row = 0;
// for each column, there should be at most one row with a 1 in that column, and every other row should have 0 in that column
for(var leader_column=0;leader_column<columns;leader_column++) {
// find the first row with a non-zero in that column
for(var row=current_row;row<rows;row++) {
if(matrix[row].digits[leader_column]!=0) {
break;
}
}
// if we found a row with a non-zero in the leader column
if(row<rows) {
// swap that row with the <leader_column>th one
if(row!=current_row) {
var tmp = matrix[row];
matrix[row] = matrix[current_row];
matrix[current_row] = tmp;
}
// multiply this row so the leader column has a 1 in it
var inverse = inverses[matrix[current_row].digits[leader_column]];
matrix[current_row] = matrix[current_row].scale(inverse);
// subtract multiples of this row from every other row so they all have a 0 in this column
for(var row=0;row<rows;row++) {
if(row!=current_row) {
var original = matrix[row];
matrix[row] = matrix[row].sub(matrix[current_row].scale(matrix[row].digits[leader_column]));
}
}
current_row += 1;
}
}
return matrix;
}
/** A minimal set of generators for the linear code generated by the given words. If the words are linearly independent, you'll get the same number of words back, otherwise you'll get fewer.
* @param {codewords.Codeword[]} words
* @returns {codewords.Codeword[]}
*/
var generator_matrix = codewords.generator_matrix = function(words) {
var matrix = reduced_row_echelon_form(words);
matrix = matrix.filter(function(w){return !w.isZero()});
return matrix;
}
/* Is the given generator matrix in standard form?
* A matrix is standard if it's of the form Id(n)|A.
*/
var generator_matrix_is_standard = codewords.generator_matrix_is_standard = function(matrix) {
var columns = matrix[0].length;
var rows = matrix.length;
if(rows>columns) {
return false;
}
for(var x=0;x<rows;x++) {
for(var y=0;y<rows;y++) {
if(matrix[y].digits[x]!=(y==x?1:0)) {
return false;
}
}
}
return true;
}
/** A parity check matrix for the given generating set (which should be linearly independent)
* @param {codewords.Codeword[]} basis
* @returns {codewords.Codeword[]}
*/
var parity_check_matrix = codewords.parity_check_matrix = function(basis) {
var field_size = basis[0].field_size;
var g = reduced_row_echelon_form(basis);
var A = g.map(function(c){ return c.digits.slice(g.length)});
var columns = A[0].length;
var rows = A.length;
var m = [];
for(var i=0;i<columns;i++) {
var row = [];
for(var j=0;j<rows;j++) {
row.push((field_size - A[j][i]) % field_size);
}
for(var j=0;j<columns;j++) {
row.push(j==i ? 1 : 0);
}
m.push(new Codeword(row,field_size));
}
return m;
}
/** A parity check matrix for the given generating set, with columns in lexicographic order.
* @param {codewords.Codeword[]} basis
* @returns {codewords.Codeword}
*/
var lexicographic_parity_check_matrix = codewords.lexicographic_parity_check_matrix = function(basis) {
var field_size = basis[0].field_size;
var pcm = parity_check_matrix(basis);
// transpose the matrix, because we're going to work with columns
var columns = [];
for(var i=0;i<basis[0].length;i++) {
var column = pcm.map(function(row){return row.digits[i];});
columns.push(new Codeword(column,field_size));
}
// ensure the first non-zero digit of each column is 1
var inverses = get_inverses(field_size);
columns = columns.map(function(column) {
for(var i=0;i<column.length;i++) {
if(column.digits[i]!=0) {
return column.scale(inverses[column.digits[i]]);
}
}
return column;
});
// sort columns lexicographically
columns.sort(function(c1,c2) {
var s1 = c1+'';
var s2 = c2+'';
return s1>s2 ? 1 : s1<s2 ? -1 : 0;
});
var rows = [];
for(var i=0;i<columns[0].length;i++) {
var row = columns.map(function(column){return column.digits[i];});
rows.push(new Codeword(row,field_size));
}
return rows;
}
/** Encode `word` using Hamming's square code.
* @param {codewords.Codeword} words
* @returns {codewords.Codeword}
*/
codewords.hamming_square_encode = function(words) {
var n = 2;
var out = [];
for(var start=0;start<words.length;start+=n*n) {
var word = words.digits.slice(start,start+n*n);
var column_sums = [];
var total = 0;
for(var i=0;i<n;i++) {
var row_sum = 0;
var column_sum = 0;
for(var j=0;j<n;j++) {
row_sum += word[n*i+j];
column_sum += word[n*j+i];
out.push(word[n*i+j]);
}
out.push(row_sum % 2);
total += row_sum;
column_sums.push(column_sum % 2);
}
out = out.concat(column_sums);
out.push(total % 2);
}
return new Codeword(out,2);
}
/** Decode (and correct up to one error in) `word` using Hamming's square code.
* @param {codewords.Codeword} encoded_word
* @returns {codewords.Codeword}
*/
codewords.hamming_square_decode = function(encoded_word) {
var n = 3;
var out = [];
for(var start=0;start<encoded_word.length;start+=n*n) {
var word = encoded_word.digits.slice(start,start+n*n);
var row_errors = [];
var column_errors = [];
for(var i=0;i<n-1;i++) {
var row_sum = 0;
var column_sum = 0;
for(var j=0;j<n-1;j++) {
row_sum += word[n*i+j];
column_sum += word[n*j+i];
}
row_errors.push(row_sum % 2 != word[n*i+n-1]);
column_errors.push(column_sum % 2 != word[n*(n-1)+i]);
}
for(var i=0;i<n-1;i++) {
for(var j=0;j<n-1;j++) {
var c = word[n*i+j];
if(row_errors[i] && column_errors[j]) {
c = 1-c;
}
out.push(c);
}
}
}
return new Codeword(out,2);
};
/** integer log_2
* @param {number} n
* @returns {number}
*/
function log2(n) {
var i = 1;
var p = 0;
while(i<=n) {
i*=2;
p += 1;
}
return p-1;
}
/** Encode `word` using the general Hamming code.
* @param {codewords.Codeword} word
* @returns {codewords.Codeword}
*/
codewords.hamming_encode = function(word) {
var word_length = word.length;
var pow = Math.ceil(log2(word_length))+1;
var powers_of_two = [];
var p = 1;
var out = [];
for(var i=0;i<pow;i++) {
powers_of_two.push(p);
out[p-1] = 0;
p *= 2;
}
var off = 0;
for(var i=0;i<word_length;i++) {
while(i+off==powers_of_two[off]-1) {
off += 1;
}
var j = i+off;
for(var p=0;p<pow;p++) {
var power_of_two = powers_of_two[p];
if((j+1) & power_of_two) {
out[power_of_two-1] = (out[power_of_two-1] + word.digits[i]) % 2;
}
}
out[j] = word.digits[i];
}
return new Codeword(out,2);
};
/** Decode (and correct up to one error in) `word` using the general Hamming code.
* @param {codewords.Codeword} word
* @returns {codewords.Codeword}
*/
codewords.hamming_decode = function(word) {
var word_length = word.length;
var pow = Math.ceil(log2(word_length));
var powers_of_two = [];
var check_digits = [];
var digits = word.digits.slice();
var p = 1;
for(var i=0;i<pow;i++) {
powers_of_two.push(p);
check_digits.push(0);
p *= 2;
}
var n = p >> 1;
var off = 0;
var out = [];
for(var i=0;i<word_length;i++) {
for(var p=0;p<pow;p++) {
var power_of_two = powers_of_two[p];
if((i+1) & power_of_two) {
check_digits[p] = (check_digits[p] + digits[i]) % 2;
}
}
}
var error = 0;
for(var i=0;i<pow;i++) {
if(check_digits[i]) {
error += powers_of_two[i];
}
}
digits[error-1] = 1 - digits[error-1];
var off = 0;
for(var i=0;i<n;i++) {
while(i+off==powers_of_two[off]-1) {
off += 1;
}
var j = i+off;
if(j<word_length) {
out.push(digits[j]);
}
}
return new Codeword(out,2);
}
/** Compute the syndrome of the given word with respect to the given parity check matrix.
* @param {codewords.Codeword} word
* @param {codewords.Codeword[]} pcm
* @returns {codewords.Codeword}
*/
var syndrome = codewords.syndrome = function(word,pcm) {
var word_length = word.length;
var field_size = word.field_size;
var digits = pcm.map(function(row) {
var t = 0;
for(var i=0;i<word_length;i++) {
t += word.digits[i]*row.digits[i];
}
return Numbas.math.mod(t,field_size);
});
return new Codeword(digits,field_size);
}
/** Create a parity check matrix for the Hamming code `Ham_p(r)`. (`p` must be prime)
* @param {number} p
* @param {number} r
* @returns {codewords.Codeword[]}
*/
var hamming_parity_check_matrix = codewords.hamming_parity_check_matrix = function(p,r) {
// each column starts with a 1
// every possible column appears once, and columns are in lexicographic order
var columns = [];
var ends = [[]];
// i is the number of zeros at the start of the column
for(var i=r-1;i>=0;i--) {
//each column starts with i zeros followed by a 1
var start = [];
for(var j=0;j<i;j++) {
start.push(0);
}
start.push(1);
// for each possible p-ary string after the 1, make a column
var i_columns = ends.map(function(digits) {
return start.concat(digits);
});
columns = columns.concat(i_columns);
if(i>0) {
// for the next step, compute the possible ends of columns (strings after the first 1)
// by taking the Cartesian product (0,1,2)x(ends)
var nends = [];
for(var j=0;j<p;j++) {
ends.map(function(end) {
nends.push([j].concat(end));
});
}
ends = nends;
}
}
var out = [];
for(var i=0;i<r;i++) {
var row = columns.map(function(column){return column[i]});
out.push(new Codeword(row,p));
}
return out;
}
/** Create a generating matrix for the Hamming code `Ham_p(r)`. (`p` must be prime)
* Ham_p(r) is the p-ary Hamming code whose PCM has r rows
*
* @param {number} p
* @param {number} r
* @returns {codewords.Codeword}
*/
var hamming_generating_matrix = codewords.hamming_generating_matrix = function(p,r) {
// Generate the parity-check matrix
var pcm = hamming_parity_check_matrix(p,r);
function swap_digits(row) {
var digits = row.digits.slice();
var off = 1;
var t = 1;
for(var i=1;i<r;i++) {
var b = digits[i];
digits[i] = digits[off];
digits[off] = b;
t *= p;
off += t;
}
return new Codeword(digits,p);
}
// swap the columns so the leftmost columns of the PCM are the identity matrix (backwards, but that doesn't matter)
var rows = pcm.map(swap_digits);
// find a generating matrix for the dual code (i.e., the actual Hamming code, but with columns swapped)
var dual = parity_check_matrix(rows);
// swap the columns back
var gen = dual.map(swap_digits);
return gen;
}
/** A wrapper object for the code containing the given words.
* @constructor
* @memberof codewords
* @property {codewords.Codeword[]} words
* @property {number} length
* @property {number} word_length
* @property {number} field_size
*
* @param {codewords.Code} words
*/
var Code = codewords.Code = function(words) {
this.words = words;
this.length = this.words.length;
this.word_length = this.length>0 ? this.words[0].length : 0;
this.field_size = this.length>0 ? this.words[0].field_size : 0;
}
Code.prototype = {
/** String representation of the code - list all its words.
* @returns {string}
*/
toString: function() {
return '{'+this.words.map(function(word){return word+''}).join(', ')+'}';
},
/** LaTeX representation of the code.
* @returns {string}
*/
toLaTeX: function() {
return '\\{'+this.words.map(function(word){return word.toLaTeX()}).join(', ')+'\\}';
},
/** JME representation of the code.
* @returns {string}
*/
toJME: function() {
return 'code(['+this.words.map(function(word){return word.toJME()}).join(', ')+'])';
},
sort_words: function() {
if(this.sorted_words===undefined) {
var words = this.words.slice();
function compare_words(a,b) {
a=a.toString();
b=b.toString();
return a<b ? -1 : a>b ? 1 : 0;
}
words.sort(compare_words);
this.sorted_words = words;
}
return this.sorted_words;
},
/** Is this code the same as `code2`? True if they have exactly the same words.
* @param {codewords.Code} b
* @returns {boolean}
*/
eq: function(b) {
if(this.length!=b.length || this.field_size!=b.field_size) {
return false;
}
this.sort_words();
b.sort_words();
for(var i=0;i<this.length;i++) {
if(!this.sorted_words[i].eq(b.sorted_words[i])) {
return false;
}
}
return true;
},
/** Does this code contain `word`?
* @param {codewords.Codeword} word
* @returns {boolean}