-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbbi.go
2486 lines (2274 loc) · 67.4 KB
/
bbi.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
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
/* Copyright (C) 2016 Philipp Benner
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package gonetics
/* -------------------------------------------------------------------------- */
// Methods for reading and writing Big Binary Indexed files such as bigWig
// and bigBed
/* -------------------------------------------------------------------------- */
import "bytes"
import "compress/zlib"
import "fmt"
import "math"
import "encoding/binary"
import "io"
import "io/ioutil"
import "github.com/pbenner/gonetics/lib/bufferedReadSeeker"
/* -------------------------------------------------------------------------- */
const CIRTREE_MAGIC = 0x78ca8c91
const IDX_MAGIC = 0x2468ace0
const BbiMaxZoomLevels = 10 /* Max number of zoom levels */
const BbiResIncrement = 4 /* Amount to reduce at each zoom level */
const BbiTypeFixed = 3
const BbiTypeVariable = 2
const BbiTypeBedGraph = 1
/* -------------------------------------------------------------------------- */
func fileReadAt(file io.ReadSeeker, order binary.ByteOrder, offset int64, data interface{}) error {
currentPosition, _ := file.Seek(0, 1)
if _, err := file.Seek(offset, 0); err != nil {
return err
}
if err := binary.Read(file, order, data); err != nil {
return err
}
if _, err := file.Seek(currentPosition, 0); err != nil {
return err
}
return nil
}
func fileWriteAt(file io.WriteSeeker, order binary.ByteOrder, offset int64, data interface{}) error {
currentPosition, _ := file.Seek(0, 1)
if _, err := file.Seek(offset, 0); err != nil {
return err
}
if err := binary.Write(file, order, data); err != nil {
return err
}
if _, err := file.Seek(currentPosition, 0); err != nil {
return err
}
return nil
}
func uncompressSlice(data []byte) ([]byte, error) {
b := bytes.NewReader(data)
z, err := zlib.NewReader(b)
if err != nil {
return nil, err
}
defer z.Close()
return ioutil.ReadAll(z)
}
func compressSlice(data []byte) ([]byte, error) {
var b bytes.Buffer
z, err := zlib.NewWriterLevel(&b, zlib.BestCompression)
if err != nil {
panic(err)
}
_, err = z.Write(data)
if err != nil {
return nil, err
}
z.Close()
return b.Bytes(), nil
}
/* -------------------------------------------------------------------------- */
type BbiZoomRecord struct {
ChromId uint32
Start uint32
End uint32
Valid uint32
Min float32
Max float32
Sum float32
SumSquares float32
}
func (record *BbiZoomRecord) AddValue(x float64) {
if math.IsNaN(x) {
return
}
if math.IsNaN(float64(record.Min)) || record.Min > float32(x) {
record.Min = float32(x)
}
if math.IsNaN(float64(record.Max)) || record.Max < float32(x) {
record.Max = float32(x)
}
record.Valid += 1
record.Sum += float32(x)
record.SumSquares += float32(x*x)
}
func (record *BbiZoomRecord) Read(reader io.Reader, order binary.ByteOrder) error {
if err := binary.Read(reader, order, &record.ChromId); err != nil {
return err
}
if err := binary.Read(reader, order, &record.Start); err != nil {
return err
}
if err := binary.Read(reader, order, &record.End); err != nil {
return err
}
if err := binary.Read(reader, order, &record.Valid); err != nil {
return err
}
if err := binary.Read(reader, order, &record.Min); err != nil {
return err
}
if err := binary.Read(reader, order, &record.Max); err != nil {
return err
}
if err := binary.Read(reader, order, &record.Sum); err != nil {
return err
}
if err := binary.Read(reader, order, &record.SumSquares); err != nil {
return err
}
return nil
}
func (record BbiZoomRecord) Write(writer io.Writer, order binary.ByteOrder) error {
if err := binary.Write(writer, order, record.ChromId); err != nil {
return err
}
if err := binary.Write(writer, order, record.Start); err != nil {
return err
}
if err := binary.Write(writer, order, record.End); err != nil {
return err
}
if err := binary.Write(writer, order, record.Valid); err != nil {
return err
}
if err := binary.Write(writer, order, record.Min); err != nil {
return err
}
if err := binary.Write(writer, order, record.Max); err != nil {
return err
}
if err := binary.Write(writer, order, record.Sum); err != nil {
return err
}
if err := binary.Write(writer, order, record.SumSquares); err != nil {
return err
}
return nil
}
/* -------------------------------------------------------------------------- */
type BbiSummaryStatistics struct {
Valid float64
Min float64
Max float64
Sum float64
SumSquares float64
}
func (obj *BbiSummaryStatistics) Reset() {
obj.Valid = 0.0
obj.Min = math.Inf( 1)
obj.Max = math.Inf(-1)
obj.Sum = 0.0
obj.SumSquares = 0.0
}
func (obj *BbiSummaryStatistics) AddValue(x float64) {
if math.IsNaN(x) {
return
}
obj.Valid += 1.0
obj.Min = math.Min(obj.Min, x)
obj.Max = math.Max(obj.Max, x)
obj.Sum += x
obj.SumSquares += x*x
}
func (obj *BbiSummaryStatistics) Add(x BbiSummaryStatistics) {
obj.Valid += x.Valid
obj.Min = math.Min(obj.Min, x.Min)
obj.Max = math.Max(obj.Max, x.Max)
obj.Sum += x.Sum
obj.SumSquares += x.SumSquares
}
/* -------------------------------------------------------------------------- */
type BbiSummaryRecord struct {
ChromId int
From int
To int
BbiSummaryStatistics
}
func NewBbiSummaryRecord() BbiSummaryRecord {
record := BbiSummaryRecord{}
record.Reset()
return record
}
func (record *BbiSummaryRecord) Reset() {
record.ChromId = -1
record.From = 0
record.To = 0
record.BbiSummaryStatistics.Reset()
}
func (record *BbiSummaryRecord) AddRecord(x BbiSummaryRecord) {
if record.ChromId == -1 {
record.ChromId = x.ChromId
record.From = x.From
record.To = x.To
}
if record.To < x.From {
// fill gaps with zeros
record.Valid += float64(x.From - record.To)
if record.Min > 0.0 {
record.Min = 0.0
}
if record.Max < 0.0 {
record.Max = 0.0
}
}
record.To = x.To
record.BbiSummaryStatistics.Add(x.BbiSummaryStatistics)
}
/* -------------------------------------------------------------------------- */
type BbiBlockDecoder interface {
Decode() BbiBlockDecoderIterator
}
type BbiBlockDecoderIterator interface {
Get () *BbiBlockDecoderType
Ok () bool
Next()
}
type BbiBlockDecoderType struct {
BbiSummaryRecord
}
/* -------------------------------------------------------------------------- */
type BbiRawBlockDecoder struct {
Header BbiDataHeader
Buffer []byte
order binary.ByteOrder
}
type BbiRawBlockDecoderIterator struct {
*BbiRawBlockDecoder
i int
r BbiBlockDecoderType
}
func NewBbiRawBlockDecoder(buffer []byte, order binary.ByteOrder) (*BbiRawBlockDecoder, error) {
if len(buffer) < 24 {
return nil, fmt.Errorf("block length is shorter than 24 bytes")
}
reader := BbiRawBlockDecoder{}
// parse header
reader.Header.ReadBuffer(buffer, order)
// crop header from buffer
reader.Buffer = buffer[24:]
reader.order = order
switch reader.Header.Type {
default:
return nil, fmt.Errorf("unsupported block type")
case BbiTypeBedGraph:
if len(reader.Buffer) % 12 != 0 {
return nil, fmt.Errorf("bedGraph data block has invalid length")
}
case BbiTypeVariable:
if len(buffer) % 8 != 0 {
return nil, fmt.Errorf("variable step data block has invalid length")
}
case BbiTypeFixed:
if len(buffer) % 4 != 0 {
return nil, fmt.Errorf("fixed step data block has invalid length")
}
}
return &reader, nil
}
func (reader *BbiRawBlockDecoder) readFixed(r *BbiBlockDecoderType, i int) {
r.ChromId = int(reader.Header.ChromId)
r.From = int(reader.Header.Start + uint32(i/4)*reader.Header.Step)
r.To = r.From + int(reader.Header.Span)
r.Valid = 1.0
r.Sum = float64(math.Float32frombits(reader.order.Uint32(reader.Buffer[i:i+4])))
r.SumSquares = r.Sum*r.Sum
r.Min = r.Sum
r.Max = r.Sum
}
func (reader *BbiRawBlockDecoder) readVariable(r *BbiBlockDecoderType, i int) {
r.ChromId = int(reader.Header.ChromId)
r.From = int(reader.order.Uint32(reader.Buffer[i+0:i+4]))
r.To = r.From + int(reader.Header.Span)
r.Valid = 1.0
r.Sum = float64(math.Float32frombits(reader.order.Uint32(reader.Buffer[i+4:i+8])))
r.SumSquares = r.Sum*r.Sum
r.Min = r.Sum
r.Max = r.Sum
}
func (reader *BbiRawBlockDecoder) readBedGraph(r *BbiBlockDecoderType, i int) {
r.ChromId = int(reader.Header.ChromId)
r.From = int(reader.order.Uint32(reader.Buffer[i+0:i+4]))
r.To = int(reader.order.Uint32(reader.Buffer[i+4:i+8]))
r.Valid = 1.0
r.Sum = float64(math.Float32frombits(reader.order.Uint32(reader.Buffer[i+8:i+12])))
r.SumSquares = r.Sum*r.Sum
r.Min = r.Sum
r.Max = r.Sum
}
func (reader *BbiRawBlockDecoder) GetDataType() byte {
return reader.Header.Type
}
func (reader *BbiRawBlockDecoder) Decode() BbiBlockDecoderIterator {
it := BbiRawBlockDecoderIterator{}
it.BbiRawBlockDecoder = reader
it.i = 0
it.Next()
return &it
}
func (it *BbiRawBlockDecoderIterator) Get() *BbiBlockDecoderType {
return &it.r
}
func (it *BbiRawBlockDecoderIterator) Ok() bool {
return it.i != -1
}
func (it *BbiRawBlockDecoderIterator) Next() {
if it.i >= len(it.Buffer) {
it.i = -1
return
}
switch it.Header.Type {
default:
// this shouldn't happen
panic("internal error (unsupported block type)")
case BbiTypeBedGraph:
it.readBedGraph(&it.r, it.i)
it.i += 12
case BbiTypeVariable:
it.readVariable(&it.r, it.i)
it.i += 8
case BbiTypeFixed:
it.readFixed(&it.r, it.i)
it.i += 4
}
}
/* -------------------------------------------------------------------------- */
type BbiZoomBlockDecoder struct {
Buffer []byte
order binary.ByteOrder
}
type BbiZoomBlockDecoderIterator struct {
*BbiZoomBlockDecoder
b *bytes.Reader
k bool
t BbiZoomRecord
r BbiBlockDecoderType
}
func NewBbiZoomBlockDecoder(buffer []byte, order binary.ByteOrder) *BbiZoomBlockDecoder {
return &BbiZoomBlockDecoder{buffer, order}
}
func (reader *BbiZoomBlockDecoder) Decode() BbiBlockDecoderIterator {
it := BbiZoomBlockDecoderIterator{}
it.BbiZoomBlockDecoder = reader
it.b = bytes.NewReader(reader.Buffer)
it.k = true
it.Next()
return &it
}
func (it *BbiZoomBlockDecoderIterator) Get() *BbiBlockDecoderType {
return &it.r
}
func (it *BbiZoomBlockDecoderIterator) Ok() bool {
return it.k
}
func (it *BbiZoomBlockDecoderIterator) Next() {
// read BbiZoomRecord
if err := it.t.Read(it.b, it.order); err != nil {
// end of block reached
it.k = false
} else {
// convert result to BbiZoomBlockDecoderType
it.r.ChromId = int (it.t.ChromId)
it.r.From = int (it.t.Start)
it.r.To = int (it.t.End)
it.r.Valid = float64(it.t.Valid)
it.r.Min = float64(it.t.Min)
it.r.Max = float64(it.t.Max)
it.r.Sum = float64(it.t.Sum)
it.r.SumSquares = float64(it.t.SumSquares)
}
}
/* -------------------------------------------------------------------------- */
type BbiBlockEncoder interface {
Encode(chromid int, sequence []float64, binSize int) BbiBlockEncoderIterator
}
type BbiBlockEncoderType struct {
From int
To int
Block []byte
}
type BbiBlockEncoderIterator interface {
Get () *BbiBlockEncoderType
Ok () bool
Next()
}
/* -------------------------------------------------------------------------- */
type BbiZoomBlockEncoder struct {
ItemsPerSlot int
reductionLevel int
order binary.ByteOrder
}
type BbiZoomBlockEncoderIterator struct {
*BbiZoomBlockEncoder
chromid int
sequence []float64
binSize int
position int
// result
r BbiBlockEncoderType
}
type BbiZoomBlockEncoderType struct {
From int
To int
Block []byte
}
func NewBbiZoomBlockEncoder(itemsPerSlot, reductionLevel int, order binary.ByteOrder) (*BbiZoomBlockEncoder, error) {
r := BbiZoomBlockEncoder{}
r.ItemsPerSlot = itemsPerSlot
r.reductionLevel = reductionLevel
r.order = order
return &r, nil
}
func (encoder *BbiZoomBlockEncoder) Encode(chromid int, sequence []float64, binSize int) BbiBlockEncoderIterator {
r := BbiZoomBlockEncoderIterator{}
r.BbiZoomBlockEncoder = encoder
r.chromid = chromid
r.sequence = sequence
r.binSize = binSize
r.position = 0
r.Next()
return &r
}
func (it *BbiZoomBlockEncoderIterator) Get() *BbiBlockEncoderType {
return &it.r
}
func (it *BbiZoomBlockEncoderIterator) Ok() bool {
return it.r.Block != nil
}
func (it *BbiZoomBlockEncoderIterator) Next() {
// create a new buffer (the returned block should not be overwritten by later calls)
b := new(bytes.Buffer)
// number of bins covered by each record
n := divIntUp(it.reductionLevel, it.binSize)
// beginning of region covered by a single block
f := -1
t := -1
// number of records written to block
m := 0
// reset result
it.r.From = 0
it.r.To = 0
it.r.Block = nil
// loop over sequence and generate records
for p := it.position; p < it.binSize*len(it.sequence); p += it.reductionLevel {
// p: position in base pairs
// i: position in bins
i := p/it.binSize
// reset record
record := BbiZoomRecord{}
record.ChromId = uint32(it.chromid)
record.Start = uint32(p)
record.End = uint32(p + it.reductionLevel)
record.Min = float32(math.NaN())
record.Max = float32(math.NaN())
// crop record end if it is longer than the actual sequence
if record.End > uint32(it.binSize*len(it.sequence)) {
record.End = uint32(it.binSize*len(it.sequence))
}
// add records
for j := 0; j < n && i+j < len(it.sequence); j++ {
record.AddValue(it.sequence[i+j])
}
// check if there was some data
if record.Valid > 0 {
// if yes, save record
if err := record.Write(b, it.order); err != nil {
panic(err)
}
// if this is the first record in a block
if f == -1 {
// save position
f = int(record.Start)
}
t = int(record.End)
m += 1
}
// check if block is full or if the end of the
// sequence is reached
if m == it.ItemsPerSlot || p + it.reductionLevel >= it.binSize*len(it.sequence) {
if tmp := b.Bytes(); len(tmp) > 0 {
// save result
it.r.From = f
it.r.To = t
it.r.Block = tmp
// update position
it.position = p + it.reductionLevel
// return result
break
}
}
}
}
/* -------------------------------------------------------------------------- */
type BbiRawBlockEncoder struct {
ItemsPerSlot int
tmp []byte
fixedStep bool
order binary.ByteOrder
}
type BbiRawBlockEncoderIterator struct {
*BbiRawBlockEncoder
chromid int
sequence []float64
binSize int
position int
record BbiZoomRecord
// result
r BbiBlockEncoderType
}
func NewBbiRawBlockEncoder(itemsPerSlot int, fixedStep bool, order binary.ByteOrder) (*BbiRawBlockEncoder, error) {
r := BbiRawBlockEncoder{}
r.ItemsPerSlot = itemsPerSlot
r.tmp = make([]byte, 24)
r.fixedStep = fixedStep
r.order = order
return &r, nil
}
func (encoder *BbiRawBlockEncoder) encodeVariable(buffer []byte, position uint32, value float64) {
encoder.order.PutUint32(buffer[0:4], position)
encoder.order.PutUint32(buffer[4:8], math.Float32bits(float32(value)))
}
func (encoder *BbiRawBlockEncoder) encodeFixed(buffer []byte, value float64) {
encoder.order.PutUint32(buffer[0:4], math.Float32bits(float32(value)))
}
func (encoder *BbiRawBlockEncoder) Encode(chromid int, sequence []float64, binSize int) BbiBlockEncoderIterator {
r := BbiRawBlockEncoderIterator{}
r.BbiRawBlockEncoder = encoder
r.chromid = chromid
r.sequence = sequence
r.binSize = binSize
r.position = 0
r.Next()
return &r
}
func (it *BbiRawBlockEncoderIterator) Get() *BbiBlockEncoderType {
return &it.r
}
func (it *BbiRawBlockEncoderIterator) Ok() bool {
return it.r.Block != nil
}
func (it *BbiRawBlockEncoderIterator) Next() {
// create a new buffer (the returned block should not be overwritten by later calls)
b := new(bytes.Buffer)
// skip NaN values
for it.position < len(it.sequence) && math.IsNaN(it.sequence[it.position]) {
it.position++
}
// reset result
it.r.From = 0
it.r.To = 0
it.r.Block = nil
// create header for this block
header := BbiDataHeader{}
header.ChromId = uint32(it.chromid)
header.Start = uint32(it.binSize*it.position)
header.End = uint32(it.binSize*it.position)
header.Step = uint32(it.binSize)
header.Span = uint32(it.binSize)
if it.fixedStep {
header.Type = 3
} else {
header.Type = 2
}
// write header
header.WriteBuffer(it.tmp[0:24], it.order)
if _, err := b.Write(it.tmp[0:24]); err != nil {
panic(err)
}
// fill buffer with data
if it.fixedStep {
// fixed step
for ; it.position < len(it.sequence); it.position++ {
// end this block if there is a NaN value
if math.IsNaN(it.sequence[it.position]) {
for it.position < len(it.sequence) && math.IsNaN(it.sequence[it.position]) {
it.position++
}
break
}
it.encodeFixed(it.tmp[0:4], it.sequence[it.position])
if _, err := b.Write(it.tmp[0:4]); err != nil {
panic(err)
}
header.ItemCount++
header.End += header.Step
// check if maximum number of items per block is reached
if int(header.ItemCount) == it.ItemsPerSlot {
it.position++
break
}
}
} else {
// variable step
for ; it.position < len(it.sequence); it.position++ {
if !math.IsNaN(it.sequence[it.position]) {
it.encodeVariable(it.tmp[0:8], header.End, it.sequence[it.position])
if _, err := b.Write(it.tmp[0:8]); err != nil {
panic(err)
}
header.ItemCount++
header.End = uint32(it.binSize*it.position) + header.Step
}
// check if maximum number of items per block is reached
if int(header.ItemCount) == it.ItemsPerSlot {
it.position++
break
}
}
}
if block := b.Bytes(); len(block) > 24 {
// update header (end position and ItemCount have changed)
header.WriteBuffer(block[0:24], it.order)
// save result
it.r.From = int(header.Start)
it.r.To = int(header.End)
it.r.Block = block
}
}
/* -------------------------------------------------------------------------- */
type BTree struct {
KeySize uint32
ValueSize uint32
ItemsPerBlock uint32
ItemCount uint64
Root BVertex
}
type BVertex struct {
IsLeaf uint8
Keys [][]byte
Values [][]byte
Children []BVertex
}
func NewBTree(data *BData) *BTree {
tree := BTree{}
tree.KeySize = data.KeySize
tree.ValueSize = data.ValueSize
tree.ItemsPerBlock = data.ItemsPerBlock
tree.ItemCount = data.ItemCount
// compute tree depth
if data.ItemCount == 1 {
tree.Root.BuildTree(data, 0, data.ItemCount, 0)
} else {
d := int(math.Ceil(math.Log(float64(data.ItemCount))/math.Log(float64(data.ItemsPerBlock))))
tree.Root.BuildTree(data, 0, data.ItemCount, d-1)
}
return &tree
}
func (vertex *BVertex) BuildTree(data *BData, from, to uint64, level int) (uint64, error) {
// number of values below this node
i := uint64(0)
if level == 0 {
vertex.IsLeaf = 1
for nVals := uint16(0); uint32(nVals) < data.ItemsPerBlock && from+i < to; nVals++ {
if uint32(len(data.Keys[from+i])) != data.KeySize {
return 0, fmt.Errorf("key number `%d' has invalid size", i)
}
if uint32(len(data.Values[from+i])) != data.ValueSize {
return 0, fmt.Errorf("value number `%d' has invalid size", i)
}
vertex.Keys = append(vertex.Keys, data.Keys [from+i])
vertex.Values = append(vertex.Values, data.Values[from+i])
i++
}
} else {
vertex.IsLeaf = 0
for nVals := uint16(0); uint32(nVals) < data.ItemsPerBlock && from+i < to; nVals++ {
// append first key
vertex.Keys = append(vertex.Keys, data.Keys[from+i])
// create new child vertex
v := BVertex{}
if j, err := v.BuildTree(data, from+i, to, level-1); err != nil {
return 0, err
} else {
i += j
}
// append child
vertex.Children = append(vertex.Children, v)
}
}
return i, nil
}
func (vertex *BVertex) writeLeaf(file io.Writer, order binary.ByteOrder) error {
padding := uint8(0)
nVals := uint16(len(vertex.Keys))
if err := binary.Write(file, order, vertex.IsLeaf); err != nil {
return err
}
if err := binary.Write(file, order, padding); err != nil {
return err
}
if err := binary.Write(file, order, nVals); err != nil {
return err
}
for i := 0; i < len(vertex.Keys); i++ {
if err := binary.Write(file, order, vertex.Keys[i]); err != nil {
return err
}
if err := binary.Write(file, order, vertex.Values[i]); err != nil {
return err
}
}
return nil
}
func (vertex *BVertex) writeIndex(file io.WriteSeeker, order binary.ByteOrder) error {
isLeaf := uint8(0)
padding := uint8(0)
nVals := uint16(len(vertex.Keys))
offsets := make([]int64, nVals)
if err := binary.Write(file, order, isLeaf); err != nil {
return err
}
if err := binary.Write(file, order, padding); err != nil {
return err
}
if err := binary.Write(file, order, nVals); err != nil {
return err
}
for i := 0; i < int(nVals); i++ {
if err := binary.Write(file, order, vertex.Keys[i]); err != nil {
return err
}
// save current file offset
offsets[i], _ = file.Seek(0, 1)
// offset of the ith child vertex (first set to zero)
if err := binary.Write(file, order, uint64(0)); err != nil {
return err
}
}
// write child vertices
for i := 0; i < int(nVals); i++ {
// get current file offset (where the ith child vertex begins)
offset, _ := file.Seek(0, 1)
// and write it at the expected position
if err := fileWriteAt(file, order, offsets[i], uint64(offset)); err != nil {
return err
}
// write ith child
if err := vertex.Children[i].write(file, order); err != nil {
return err
}
}
return nil
}
func (vertex *BVertex) write(file io.WriteSeeker, order binary.ByteOrder) error {
if vertex.IsLeaf != 0 {
return vertex.writeLeaf(file, order)
} else {
return vertex.writeIndex(file, order)
}
return nil
}
func (tree *BTree) Write(file io.WriteSeeker, order binary.ByteOrder) error {
magic := uint32(CIRTREE_MAGIC)
// ItemsPerBlock has 32 bits but nVals has only 16 bits, check for overflow
if tree.ItemsPerBlock > uint32(^uint16(0)) {
return fmt.Errorf("ItemsPerBlock too large (maximum value is `%d')", ^uint16(0))
}
if err := binary.Write(file, order, magic); err != nil {
return err
}
if err := binary.Write(file, order, tree.ItemsPerBlock); err != nil {
return err
}
if err := binary.Write(file, order, tree.KeySize); err != nil {
return err
}
if err := binary.Write(file, order, tree.ValueSize); err != nil {
return err
}
if err := binary.Write(file, order, tree.ItemCount); err != nil {
return err
}
// padding
if err := binary.Write(file, order, uint64(0)); err != nil {
return err
}
return tree.Root.write(file, order)
}
/* -------------------------------------------------------------------------- */
type BData struct {
KeySize uint32
ValueSize uint32
ItemsPerBlock uint32
ItemCount uint64
Keys [][]byte
Values [][]byte
PtrKeys []int64
PtrValues []int64
}
func NewBData() *BData {
data := BData{}
// default values
data.KeySize = 0
data.ValueSize = 0
data.ItemsPerBlock = 0
data.ItemCount = 0
return &data
}
func (data *BData) Add(key, value []byte) error {
if uint32(len(key)) != data.KeySize {
return fmt.Errorf("BData.Add(): key has invalid length")
}
if uint32(len(value)) != data.ValueSize {
return fmt.Errorf("BData.Add(): value has invalid length")
}
data.Keys = append(data.Keys, key)
data.Values = append(data.Values, value)
data.ItemsPerBlock++
data.ItemCount++
return nil
}
func (data *BData) readVertexLeaf(file io.ReadSeeker, order binary.ByteOrder) error {
var nVals uint16
var key []byte
var value []byte
if err := binary.Read(file, order, &nVals); err != nil {
return err
}
for i := 0; i < int(nVals); i++ {
key = make([]byte, data.KeySize)
value = make([]byte, data.ValueSize)
ptrKey, _ := file.Seek(0, 1)
if err := binary.Read(file, order, &key); err != nil {
return err
}
ptrValue, _ := file.Seek(0, 1)
if err := binary.Read(file, order, &value); err != nil {
return err
}
data.Keys = append(data.Keys, key)
data.Values = append(data.Values, value)
data.PtrKeys = append(data.PtrKeys, ptrKey)
data.PtrValues = append(data.PtrValues, ptrValue)
}
return nil
}
func (data *BData) readVertexIndex(file io.ReadSeeker, order binary.ByteOrder) error {
var nVals uint16
var key []byte
var position uint64
key = make([]byte, data.KeySize)
if err := binary.Read(file, order, &nVals); err != nil {
return err
}
for i := 0; i < int(nVals); i++ {
if err := binary.Read(file, order, &key); err != nil {
return err
}
if err := binary.Read(file, order, &position); err != nil {
return err
}
// save current position and jump to child vertex
currentPosition, _ := file.Seek(0, 1)
if _, err := file.Seek(int64(position), 0); err != nil {
return err
}
data.readVertex(file, order)
if _, err := file.Seek(currentPosition, 0); err != nil {
return err
}
}
return nil
}
func (data *BData) readVertex(file io.ReadSeeker, order binary.ByteOrder) error {
var isLeaf uint8
var padding uint8