-
Notifications
You must be signed in to change notification settings - Fork 16
/
BWT.go
573 lines (471 loc) · 13.2 KB
/
BWT.go
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
/*
Copyright 2011-2024 Frederic Langlet
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
you may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package transform
import (
"errors"
"fmt"
"sync"
internal "github.com/flanglet/kanzi-go/v2/internal"
)
const (
_BWT_MAX_BLOCK_SIZE = 1024 * 1024 * 1024 // 1 GB
_BWT_NB_FASTBITS = 17
_BWT_MASK_FASTBITS = (1 << _BWT_NB_FASTBITS) - 1
_BWT_BLOCK_SIZE_THRESHOLD1 = 256
_BWT_BLOCK_SIZE_THRESHOLD2 = 8 * 1024 * 1024
)
// The Burrows-Wheeler Transform is a reversible transform based on
// permutation of the data in the original message to reduce the entropy.
// The initial text can be found here:
// Burrows M and Wheeler D, [A block sorting lossless data compression algorithm]
// Technical Report 124, Digital Equipment Corporation, 1994
// See also Peter Fenwick, [Block sorting text compression - final report]
// Technical Report 130, 1996
// This implementation replaces the 'slow' sorting of permutation strings
// with the construction of a suffix array (faster but more complex).
// The suffix array contains the indexes of the sorted suffixes.
//
// E.G. 0123456789A
// Source: mississippi\0
// mississippi\0 0 -> 4 i\0
// ississippi\0 1 -> 3 ippi\0
// ssissippi\0 2 -> 10 issippi\0
// sissippi\0 3 -> 8 ississippi\0
// issippi\0 4 -> 2 mississippi\0
// ssippi\0 5 -> 9 pi\0
// sippi\0 6 -> 7 ppi\0
// ippi\0 7 -> 1 sippi\0
// ppi\0 8 -> 6 sissippi\0
// pi\0 9 -> 5 ssippi\0
// i\0 10 -> 0 ssissippi\0
// Suffix array SA : 10 7 4 1 0 9 8 6 3 5 2
// BWT[i] = input[SA[i]-1] => BWT(input) = ipssmpissii (+ primary index 5)
// The suffix array and permutation vector are equal when the input is 0 terminated
// The insertion of a guard is done internally and is entirely transparent.
//
// This implementation extends the canonical algorithm to use up to MAX_CHUNKS primary
// indexes (based on input block size). Each primary index corresponds to a data chunk.
// Chunks may be inverted concurrently.
// BWT Burrows Wheeler Transform
type BWT struct {
buffer []int32
primaryIndexes [8]uint
saAlgo *DivSufSort
jobs uint
}
// NewBWT creates a new BWT instance with 1 job
func NewBWT() (*BWT, error) {
this := &BWT{}
this.buffer = make([]int32, 0)
this.primaryIndexes = [8]uint{}
this.jobs = 1
return this, nil
}
// NewBWTWithCtx creates a new BWT instance. The number of jobs is extracted
// from the provided map or arguments.
func NewBWTWithCtx(ctx *map[string]any) (*BWT, error) {
this := &BWT{}
this.buffer = make([]int32, 0)
this.primaryIndexes = [8]uint{}
if _, containsKey := (*ctx)["jobs"]; containsKey {
this.jobs = (*ctx)["jobs"].(uint)
if this.jobs == 0 {
return nil, errors.New("The number of jobs must be at least 1")
}
} else {
this.jobs = 1
}
return this, nil
}
// PrimaryIndex returns the primary index for the n-th chunk
func (this *BWT) PrimaryIndex(n int) uint {
return this.primaryIndexes[n]
}
// SetPrimaryIndex sets the primary index for of n-th chunk
func (this *BWT) SetPrimaryIndex(n int, primaryIndex uint) bool {
if n < 0 || n >= len(this.primaryIndexes) {
return false
}
this.primaryIndexes[n] = primaryIndex
return true
}
// Forward applies the function to the src and writes the result
// to the destination. Returns number of bytes read, number of bytes
// written and possibly an error.
func (this *BWT) Forward(src, dst []byte) (uint, uint, error) {
if len(src) == 0 {
return 0, 0, nil
}
if &src[0] == &dst[0] {
return 0, 0, errors.New("Input and output buffers cannot be equal")
}
if n := this.MaxEncodedLen(len(src)); len(dst) < n {
return 0, 0, fmt.Errorf("Output buffer is too small - size: %d, required %d", len(dst), n)
}
count := len(src)
if count > _BWT_MAX_BLOCK_SIZE {
return 0, 0, fmt.Errorf("The max BWT block size is %d, got %d", _BWT_MAX_BLOCK_SIZE, count)
}
if count == 1 {
dst[0] = src[0]
return uint(count), uint(count), nil
}
if this.saAlgo == nil {
var err error
if this.saAlgo, err = NewDivSufSort(); err != nil {
return 0, 0, err
}
}
// Lazy dynamic memory allocation
if len(this.buffer) < count {
this.buffer = make([]int32, count)
}
this.saAlgo.ComputeBWT(src[0:count], dst, this.buffer[0:count], this.primaryIndexes[:], GetBWTChunks(count))
return uint(count), uint(count), nil
}
// Inverse applies the reverse function to the src and writes the result
// to the destination. Returns number of bytes read, number of bytes
// written and possibly an error.
func (this *BWT) Inverse(src, dst []byte) (uint, uint, error) {
if len(src) == 0 {
return 0, 0, nil
}
if &src[0] == &dst[0] {
return 0, 0, errors.New("Input and output buffers cannot be equal")
}
count := len(src)
if count > _BWT_MAX_BLOCK_SIZE {
return 0, 0, fmt.Errorf("The max BWT block size is %d, got %d", _BWT_MAX_BLOCK_SIZE, count)
}
if count > len(dst) {
return 0, 0, fmt.Errorf("BWT inverse failed: output buffer size is %d, expected %d", count, len(dst))
}
if count == 1 {
dst[0] = src[0]
return uint(count), uint(count), nil
}
// Find the fastest way to implement inverse based on block size
if count <= _BWT_BLOCK_SIZE_THRESHOLD2 {
return this.inverseMergeTPSI(src, dst, count)
}
return this.inverseBiPSIv2(src, dst, count)
}
// When count <= _BWT_BLOCK_SIZE_THRESHOLD2, mergeTPSI algo. Always in one chunk
func (this *BWT) inverseMergeTPSI(src, dst []byte, count int) (uint, uint, error) {
// Lazy dynamic memory allocation
if len(this.buffer) < count {
if count <= 64 {
this.buffer = make([]int32, 64)
} else {
this.buffer = make([]int32, count)
}
}
// Aliasing
data := this.buffer
// Build array of packed index + value (assumes block size < 2^24)
pIdx := int(this.PrimaryIndex(0))
if pIdx > len(src) {
return 0, 0, errors.New("Invalid input: corrupted BWT primary index")
}
buckets := [256]int{}
internal.ComputeHistogram(src[0:count], buckets[:], true, false)
sum := 0
for i, b := range &buckets {
tmp := b
buckets[i] = sum
sum += tmp
}
for i := 0; i < pIdx; i++ {
val := int32(src[i])
data[buckets[val]] = int32((i-1)<<8) | val
buckets[val]++
}
for i := pIdx; i < count; i++ {
val := int32(src[i])
data[buckets[val]] = int32((i)<<8) | val
buckets[val]++
}
if count < _BWT_BLOCK_SIZE_THRESHOLD1 {
t := int32(pIdx - 1)
for i := range src {
ptr := data[t]
dst[i] = byte(ptr)
t = ptr >> 8
}
} else {
ckSize := count >> 3
if ckSize*8 != count {
ckSize++
}
t0 := int32(this.PrimaryIndex(0) - 1)
t1 := int32(this.PrimaryIndex(1) - 1)
t2 := int32(this.PrimaryIndex(2) - 1)
t3 := int32(this.PrimaryIndex(3) - 1)
t4 := int32(this.PrimaryIndex(4) - 1)
t5 := int32(this.PrimaryIndex(5) - 1)
t6 := int32(this.PrimaryIndex(6) - 1)
t7 := int32(this.PrimaryIndex(7) - 1)
n := 0
for {
ptr0 := data[t0]
dst[n] = byte(ptr0)
t0 = ptr0 >> 8
ptr1 := data[t1]
dst[n+ckSize*1] = byte(ptr1)
t1 = ptr1 >> 8
ptr2 := data[t2]
dst[n+ckSize*2] = byte(ptr2)
t2 = ptr2 >> 8
ptr3 := data[t3]
dst[n+ckSize*3] = byte(ptr3)
t3 = ptr3 >> 8
ptr4 := data[t4]
dst[n+ckSize*4] = byte(ptr4)
t4 = ptr4 >> 8
ptr5 := data[t5]
dst[n+ckSize*5] = byte(ptr5)
t5 = ptr5 >> 8
ptr6 := data[t6]
dst[n+ckSize*6] = byte(ptr6)
t6 = ptr6 >> 8
ptr7 := data[t7]
dst[n+ckSize*7] = byte(ptr7)
t7 = ptr7 >> 8
n++
if ptr7 < 0 {
break
}
}
for n < ckSize {
ptr0 := data[t0]
dst[n] = byte(ptr0)
t0 = ptr0 >> 8
ptr1 := data[t1]
dst[n+ckSize*1] = byte(ptr1)
t1 = ptr1 >> 8
ptr2 := data[t2]
dst[n+ckSize*2] = byte(ptr2)
t2 = ptr2 >> 8
ptr3 := data[t3]
dst[n+ckSize*3] = byte(ptr3)
t3 = ptr3 >> 8
ptr4 := data[t4]
dst[n+ckSize*4] = byte(ptr4)
t4 = ptr4 >> 8
ptr5 := data[t5]
dst[n+ckSize*5] = byte(ptr5)
t5 = ptr5 >> 8
ptr6 := data[t6]
dst[n+ckSize*6] = byte(ptr6)
t6 = ptr6 >> 8
n++
}
}
return uint(count), uint(count), nil
}
// When count > _BWT_BLOCK_SIZE_THRESHOLD2, biPSIv2 algo
func (this *BWT) inverseBiPSIv2(src, dst []byte, count int) (uint, uint, error) {
// Lazy dynamic memory allocations
if len(this.buffer) < count+1 {
this.buffer = make([]int32, max(count+1, 256))
} else {
for i := range this.buffer {
this.buffer[i] = 0
}
}
pIdx := int(this.PrimaryIndex(0))
if pIdx > len(src) {
return 0, 0, errors.New("Invalid input: corrupted BWT primary index")
}
freqs := [256]int{}
internal.ComputeHistogram(src[0:count], freqs[:], true, false)
buckets := make([]int, 65536)
for c, sum := 0, 1; c < 256; c++ {
f := sum
sum += int(freqs[c])
freqs[c] = f
if f != sum {
ptr := buckets[c<<8 : (c+1)<<8]
hi := min(sum, pIdx)
lo := max(f-1, pIdx)
for i := f; i < hi; i++ {
ptr[src[i]]++
}
for i := lo; i < sum-1; i++ {
ptr[src[i]]++
}
}
}
lastc := int(src[0])
fastBits := make([]uint16, _BWT_MASK_FASTBITS+1)
shift := uint(0)
for (count >> shift) > _BWT_MASK_FASTBITS {
shift++
}
for c, v, sum := 0, 0, 1; c < 256; c++ {
if c == lastc {
sum++
}
ptr := buckets[c:]
for d := 0; d < 256; d++ {
s := sum
sum += ptr[d<<8]
ptr[d<<8] = s
if s != sum {
fb := uint16((c << 8) | d)
ve := (sum - 1) >> shift
for v <= ve {
fastBits[v] = fb
v++
}
}
}
}
data := this.buffer
for i := 0; i < pIdx; i++ {
c := int(src[i])
p := freqs[c]
freqs[c]++
if p < pIdx {
idx := (c << 8) | int(src[p])
data[buckets[idx]] = int32(i)
buckets[idx]++
} else if p > pIdx {
idx := (c << 8) | int(src[p-1])
data[buckets[idx]] = int32(i)
buckets[idx]++
}
}
for i := pIdx; i < count; i++ {
c := int(src[i])
p := freqs[c]
freqs[c]++
if p < pIdx {
idx := (c << 8) | int(src[p])
data[buckets[idx]] = int32(i + 1)
buckets[idx]++
} else if p > pIdx {
idx := (c << 8) | int(src[p-1])
data[buckets[idx]] = int32(i + 1)
buckets[idx]++
}
}
for c := 0; c < 256; c++ {
c256 := c << 8
for d := 0; d < c; d++ {
buckets[(d<<8)|c], buckets[c256|d] = buckets[c256|d], buckets[(d<<8)|c]
}
}
chunks := GetBWTChunks(count)
// Build inverse
// Several chunks may be decoded concurrently (depending on the availability
// of jobs for this block).
ckSize := count / chunks
if ckSize*chunks != count {
ckSize++
}
nbTasks := min(int(this.jobs), chunks)
jobsPerTask, _ := internal.ComputeJobsPerTask(make([]uint, nbTasks), uint(chunks), uint(nbTasks))
var wg sync.WaitGroup
for j, c := 0, 0; j < nbTasks; j++ {
wg.Add(1)
start := c * ckSize
go func(dst []byte, buckets []int, fastBits []uint16, indexes []uint, total, start, ckSize, firstChunk, lastChunk int) {
this.inverseBiPSIv2Task(dst, buckets, fastBits, indexes, total, start, ckSize, firstChunk, lastChunk)
wg.Done()
}(dst, buckets[:], fastBits, this.primaryIndexes[:], count, start, ckSize, c, c+int(jobsPerTask[j]))
c += int(jobsPerTask[j])
}
wg.Wait()
dst[count-1] = byte(lastc)
return uint(count), uint(count), nil
}
func (this *BWT) inverseBiPSIv2Task(dst []byte, buckets []int, fastBits []uint16, indexes []uint, total, start, ckSize, firstChunk, lastChunk int) {
data := this.buffer
shift := uint(0)
for (total >> shift) > _BWT_MASK_FASTBITS {
shift++
}
c := firstChunk
dst0 := dst[0:]
dst1 := dst[ckSize:]
dst2 := dst[2*ckSize:]
dst3 := dst[3*ckSize:]
if start+4*ckSize < total {
for c+3 < lastChunk {
end := start + ckSize
p0 := int(indexes[c])
p1 := int(indexes[c+1])
p2 := int(indexes[c+2])
p3 := int(indexes[c+3])
for i := start + 1; i <= end; i += 2 {
s0 := fastBits[p0>>shift]
s1 := fastBits[p1>>shift]
s2 := fastBits[p2>>shift]
s3 := fastBits[p3>>shift]
for buckets[s0] <= p0 {
s0++
}
for buckets[s1] <= p1 {
s1++
}
for buckets[s2] <= p2 {
s2++
}
for buckets[s3] <= p3 {
s3++
}
dst0[i-1] = byte(s0 >> 8)
dst0[i] = byte(s0)
dst1[i-1] = byte(s1 >> 8)
dst1[i] = byte(s1)
dst2[i-1] = byte(s2 >> 8)
dst2[i] = byte(s2)
dst3[i-1] = byte(s3 >> 8)
dst3[i] = byte(s3)
p0 = int(data[p0])
p1 = int(data[p1])
p2 = int(data[p2])
p3 = int(data[p3])
}
start = end + 3*ckSize
c += 4
}
}
for c < lastChunk {
end := min(start+ckSize, total-1)
p := int(indexes[c])
for i := start + 1; i <= end; i += 2 {
s := fastBits[p>>shift]
for buckets[s] <= p {
s++
}
dst[i-1] = byte(s >> 8)
dst[i] = byte(s)
p = int(data[p])
}
start = end
c++
}
}
// GetBWTChunks returns the number of chunks for a given block size
func GetBWTChunks(size int) int {
if size < _BWT_BLOCK_SIZE_THRESHOLD1 {
return 1
}
return 8
}
// MaxEncodedLen returns the max size required for the encoding output buffer
func (this *BWT) MaxEncodedLen(srcLen int) int {
return srcLen
}