This repository was archived by the owner on May 10, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBTree.java
More file actions
761 lines (661 loc) · 19.7 KB
/
BTree.java
File metadata and controls
761 lines (661 loc) · 19.7 KB
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
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.io.Serializable;
import java.util.Stack;
public class BTree implements Serializable {
private BTreeNode root, currentNode, nextNode; //The root, current, next node in this BTree
private static Cache<BTreeNode> cache = null;
private int degree, nodeCount;
private static RandomAccessFile raf; //The file we are writing to and reading from
private static int maxBTreeNodeSize = 0; //The largest expected size in bytes of a BTree Node
private static int optimal = 4096;
private static final long serialVersionUID = 1L;
private static final int intMetadata = 4;
private static final int booleanMetadata = 4;
public BTree(int sequenceLength, int cacheSize, int degree, int debugLevel, String gbkFileName) throws IOException {
if (degree == 0) {
this.degree = getOptimalDegree();
} else {
this.degree = degree;
}
if(cacheSize != 0) {
cache = new Cache<BTreeNode>(cacheSize);
}
nodeCount = 1;
maxBTreeNodeSize = findGoodSize(this.degree);
String btreeFileName = gbkFileName+".btree.data."+sequenceLength+"."+this.degree;
File file = new File(btreeFileName);
if(!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try { //make raf
raf = new RandomAccessFile(btreeFileName, "rw");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
root = new BTreeNode(this.degree, true, true, 0);
diskWrite(root, root.getOffset());
}
public BTree(String btreeFileName, int debugLevel, int cacheSize) throws ClassNotFoundException, IOException {
String[] sa = btreeFileName.split("\\."); //split the file name by .'s
degree = Integer.parseInt(sa[5]); //get degree
maxBTreeNodeSize = findGoodSize(degree);
//make cache
if(cacheSize != 0) {
cache = new Cache<BTreeNode>(cacheSize);
}
//make a raf
File file = new File(btreeFileName);
try {
raf = new RandomAccessFile(btreeFileName, "rw");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//find the root node
boolean foundRoot = false;
int i = 0;
while(!foundRoot) {
root = diskRead(i*maxBTreeNodeSize);
foundRoot = root.isRoot();
i = root.getParentIndex();
}
currentNode = root;
}
public void finish() throws IOException {
nodeWrite(root);
if(cache != null)
writeCache();
}
public int search(long key) throws ClassNotFoundException, IOException {
if(cache != null) {
return searchWithCache(key);
} else {
return searchNoCache(key);
}
}
public int searchNoCache(long key) throws ClassNotFoundException, IOException {
currentNode = root;
while (true) {
int i = 0;
while (i < currentNode.getNumKeys() && Long.compare(key, currentNode.getKey(i).getKey()) > 0){
i++;
}
if (i < currentNode.getNumKeys() && Long.compare(key, currentNode.getKey(i).getKey()) == 0)
{
return currentNode.getKey(i).getFreq();
}
if (currentNode.isLeaf()) {
return 0;
} else {
currentNode = diskRead(currentNode.getChild(i)*maxBTreeNodeSize);
}
}
}
public int searchWithCache(long key) throws ClassNotFoundException, IOException {
//check cache first
TreeObject cacheReturn = searchCache(key);
if(cacheReturn != null) {
return cacheReturn.getFreq();
}
currentNode = root;
while (true) {
int i = 0;
while (i < currentNode.getNumKeys() && Long.compare(key, currentNode.getKey(i).getKey()) > 0){
i++;
}
if (i < currentNode.getNumKeys() && Long.compare(key, currentNode.getKey(i).getKey()) == 0)
{
cache.add(currentNode);
return currentNode.getKey(i).getFreq();
}
if (currentNode.isLeaf()) {
return 0;
} else {
currentNode = diskRead(currentNode.getChild(i)*maxBTreeNodeSize);
}
}
}
public TreeObject searchCache(long key) {
if(cache != null) { //there is a cache
for (int i = 0; i < cache.size(); i++) { //Searching cache for BTreeNode
BTreeNode cacheNode = (BTreeNode) cache.get(i);
for(int j = 0; j < cacheNode.getNumKeys(); j++) {
if(cacheNode.getKey(j).getKey() == key) {
cache.add(cacheNode, i); //key was found, add node back to original place
return cacheNode.getKey(j); //return TreeObject
} //end if
} //end for
cache.add(cacheNode, i); //key was not found, add node back to original place
}
return null;
} else { //no cache
return null;
}
}
public void insert(TreeObject to) throws ClassNotFoundException, IOException {
if(root.isFull()) { //root node is full
nextNode = root; //create node to be parent of root after split
root = new BTreeNode(degree, true, false, ++nodeCount); //make newParent the root
diskWrite(root, root.getOffset());
root.addChild(nextNode.getIndex(), 0);
nextNode.setParentIndex(root.getIndex());
nextNode.setRoot(false);
split(root, 0, nextNode);
}
insertNonFull(to);
}
private void split(BTreeNode parentNode, int childIndex, BTreeNode child) throws IOException {
BTreeNode newNode = new BTreeNode(degree, false, child.isLeaf(), ++nodeCount);
diskWrite(newNode, newNode.getOffset());
for(int j = 0; j < (degree-1); j++) { //move half the full node's keys to new node
newNode.addKey(child.getKey(degree));
child.removeKey(degree);
}
if(!child.isLeaf()) { //if child is not a leaf, move half the child's kids to new node
int numChildsChildren = child.getNumChildren(); //number of children in child node
for(int j = 0; j < (numChildsChildren/2); j++) {
newNode.addChild(child.getChild(degree), j);
child.removeChild(degree);
}
}
parentNode.addChild(newNode.getIndex(), childIndex+1); //add newNode after child in parent's list of children
newNode.setParentIndex(parentNode.getIndex());
int index = parentNode.getNumKeys()-1;
long key = child.getKey(degree-1).getKey();
while (index >= 0 && Long.compare(key, parentNode.getKey(index).getKey()) <= 0)
{
index--;
}
parentNode.addKey(child.removeKey(degree-1), index+1);
//write the nodes
nodeWrite(parentNode);
nodeWrite(child);
nodeWrite(newNode);
}
private void insertNonFull(TreeObject to) throws IOException, ClassNotFoundException {
Long key = to.getKey();
currentNode = root;
while (true)
{
int index = currentNode.getNumKeys() - 1;
if (currentNode.isLeaf())
{
while (index >= 0 && Long.compare(key, currentNode.getKey(index).getKey()) <= 0)
{
if (Long.compare(key, currentNode.getKey(index).getKey()) == 0)
{
currentNode.getKey(index).increaseFreq();
nodeWrite(currentNode);
return;
}
index--;
}
index++;
currentNode.addKey(to, index);
nodeWrite(currentNode);
break;
} //end if (currentNode.isLeaf())
else //not a leaf
{
while (index >= 0 && Long.compare(key, currentNode.getKey(index).getKey()) <= 0)
{
if (Long.compare(key, currentNode.getKey(index).getKey()) == 0)
{
currentNode.getKey(index).increaseFreq();
nodeWrite(currentNode);
return;
}
index--;
} //end while (index >= 0 && Long.compare(key, currentNode.keys.get(index).getKey()) <= 0)
index++;
if(index >= currentNode.getNumChildren()) {
currentNode.addKey(to, index);
nodeWrite(currentNode);
return;
}
nextNode = diskRead(currentNode.getChild(index)*maxBTreeNodeSize);
if (nextNode.isFull())
{
if(Long.compare(key, nextNode.getKey(degree/2).getKey()) == 0)
{
nextNode.getKey(degree/2).increaseFreq();
nodeWrite(nextNode);
return;
}
split(currentNode, index, nextNode);
if (Long.compare(key, currentNode.getKey(index).getKey()) > 0)
{
nextNode = diskRead(currentNode.getChild(index + 1)*maxBTreeNodeSize);
}
}
currentNode = nextNode;
} //end else for if (currentNode.isLeaf())
} //end while true
} //end insert non full
/**
* Return a good maxBTreeNodeSize
* @param degree
* @return maximum size of node
*/
private int findGoodSize(int degree) {
return 5000*degree;
}
/**
* Serializes the object by converting it into an array of bytes
* @param node The BTreeNode to be serialized
* @return The given BTreeNode as an array of bytes
* @throws IOException
*/
private static byte[] serialize(BTreeNode node) throws IOException {
//Array of bytes that store the given BTree Node as a sequence of bytes
byte[] stream = null;
//Creates a ByteArrayOutputStream to be passed as a parameter to the ObjectOutputStream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//Creates an ObjectOutputStream
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.flush();
//Writes the object to by converted into a byte array by the baos
oos.writeObject(node);
oos.close();
//Converts the written object into a byte array stored in stream
stream = baos.toByteArray();
//Returns the given node as an array of bytes
return stream;
}
/**
* Deserializes an object by converting an array of bytes into a BTreeObject
* @param byteArray The given BTreeNode as a byte array
* @return The byte array converted back into a BTreeNode
* @throws ClassNotFoundException
* @throws IOException
*/
private static BTreeNode deserialize(byte[] byteArray) throws ClassNotFoundException, IOException {
//Creates a ByteArrayInputStream to make the given byte array readable
ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
//Creates an ObjectInputStream to read the ByteArrayInputStream
ObjectInputStream ois = new ObjectInputStream(bais);
//Reads the given byteArray'd BTreeNode and converts it back into a BTreeNode
BTreeNode tmp = (BTreeNode) ois.readObject();
ois.close();
return tmp;
}
public static int getOptimalDegree() {
int metadata = (intMetadata * 4) + (booleanMetadata * 2);
int totalSize = 30;
int pointerSize = 4;
optimal -= metadata;
optimal += totalSize;
optimal -= pointerSize;
int dividedBy = ((2*totalSize)+(2*pointerSize));
optimal /= dividedBy;
return optimal;
}
/**
* Writes a BTreeNode into a Random Access File in binary
* @param node The BTreeNode to be written
* @param position The offset in the RAF to write the BTreeNode to
* @throws IOException
*/
public static void diskWrite(BTreeNode node, long position) throws IOException {
//Serializes the given BTreeNode
byte[] byteArray = serialize(node);
//Finds the position in the RandomAccessFile to write to
raf.seek(position);
//Writes the byte array to the RandomAccessFile
raf.write(byteArray);
}
/**
* Reads the binary Random Access File and converts it into a BTreeNode
* @param position
* @return
* @throws ClassNotFoundException
* @throws IOException
*/
public static BTreeNode diskRead(long position) throws ClassNotFoundException, IOException {
BTreeNode checkCache = null;
if (cache != null) {
for (int i = 0; i < cache.size(); i++) { //Searching cache for BTreeNode
BTreeNode cacheNode = (BTreeNode) cache.get(i);
if ((cacheNode.getOffset() == position)) {
checkCache = cacheNode;
} else {
cache.add(cacheNode, i);
}
}
}
if (checkCache != null) { //Found node, don't read from disk
return checkCache;
}
//Creates byte array to be read to
byte[] byteArray = new byte[maxBTreeNodeSize];
//A BTreeNode place holder
BTreeNode copyNode = null;
//Finds the starting postion in the RAF to start reading from
raf.seek(position);
//Reads from the RAF into the byte array
raf.read(byteArray);
//Deserializes the byte array into the node place holder
copyNode = deserialize(byteArray);
//Returns the node place holder
return copyNode;
}
/**
* Writes all the contents of the cache to update everything at the end
*
* @throws IOException
*/
public void writeCache() throws IOException {
for (int i = cache.size(); i > 0; i--) { //Goes through whole cache and writes and updates disk
BTreeNode node = (BTreeNode) cache.removeLast();
diskWrite(node, node.getOffset());
}
}
/**
* Adds node to the cache, if cache is full then it will return the last element
* in cache and write
*
* @param node
* Node to be written
* @throws IOException
*/
public void nodeWrite(BTreeNode node) throws IOException {
//TODO Replace diskWrite with nodeWrite so cache works
if (cache != null) {
BTreeNode checkNode = (BTreeNode) cache.add(node);
if (checkNode != null) {
diskWrite(checkNode, checkNode.getOffset());
}
} else {
diskWrite(node, node.getOffset());
}
}
/**
* Creates a dump file that contains an in-order traversal of the btree
* and prints out each tree object as DNA String: Frequency
* @throws InterruptedException
* @throws IOException
* @throws ClassNotFoundException
*/
public void makeDump() throws InterruptedException, IOException, ClassNotFoundException {
FileOutputStream outFileStream = new FileOutputStream(new File("dump"));
PrintWriter bw = new PrintWriter(outFileStream);
boolean traverse = true;
// have to traverse the tree
currentNode = root;
Stack<Integer> children = new Stack<>();
Stack<Integer> treeNodes = new Stack<>();
int childIndex = 0;
while (traverse)
{
if (childIndex == currentNode.getNumChildren() && !currentNode.isLeaf())
{
if (treeNodes.isEmpty() && children.isEmpty()) // done going thru
{
traverse = false;
continue;
}
else
{
currentNode = diskRead(treeNodes.pop()*maxBTreeNodeSize); // parameter might need modifying
childIndex = children.pop();
if (childIndex < currentNode.getNumKeys())
{
bw.write(currentNode.getKey(childIndex).toString()+"\n");
}
childIndex++;
continue;
}
}
if (currentNode.isLeaf())
{
for (int i = 0; i < currentNode.getNumKeys() ; i++)
{
bw.write(currentNode.getKey(i).toString()+"\n");
}
if (currentNode == root) {
break;
}
currentNode = diskRead(treeNodes.pop()*maxBTreeNodeSize);
childIndex = children.pop();
if (childIndex < currentNode.getNumKeys())
{
bw.write(currentNode.getKey(childIndex).toString()+"\n");
}
childIndex++;
}
else
{
treeNodes.push(currentNode.getIndex());
children.push(childIndex);
currentNode = diskRead(currentNode.getChild(childIndex)*maxBTreeNodeSize);
childIndex = 0;
}
}
bw.close();
}
/**
* Creates a BTreeNode with keys, children, and other methods.
*
* @author thomasreinking, maxrichmond
*
*/
private class BTreeNode implements Serializable {
private TreeObject[] keys; // array of keys for this node
private int[] children; // array of children for this node
private boolean isLeaf,isRoot; // boolean to keep track of this node being a leaf/root
private int numKeys; // number of keys in this node
private int numChildren;
private int index, parentIndex; // index for parent and this node
private int degree; // b tree degree
private static final long serialVersionUID = 1L;
/**
* Constructor to create BTreeNode and initialize variables
*/
public BTreeNode(int degree, boolean isRoot, boolean isLeaf, int index) {
keys = new TreeObject[(2*degree-1)];
children = new int[(2*degree)];
this.degree = degree;
this.isRoot = isRoot;
this.isLeaf = isLeaf;
this.index = index;
numKeys = 0;
numChildren = 0;
}
/**
* check if node is full
*
* @return
*/
public boolean isFull() {
return numKeys == ((2*degree)-1);
}
/**
*
* @return Number of Keys in this BTreeNode
*/
public int getNumKeys() {
return numKeys;
}
/**
*
* @return Number of children in this BTreeNode
*/
public int getNumChildren() {
return numChildren;
}
/**
* Gets the index of node
*
* @return Parent Index
*/
public int getIndex() {
return index;
}
/**
* Gets the key of TreeObject for that index
*
* @param key
* Index of key
* @return TreeObject of that index
*/
public TreeObject getKey(int index) {
return keys[index];
}
/**
* Removes the key at index
*
* @param index
* Index of key to be removed
* @return The removed TreeObject
*/
public TreeObject removeKey(int index) {
TreeObject rtn = keys[index];
int i = index;
while(i < numKeys-1) {
keys[i] = keys[i+1];
i++;
}
numKeys--;
return rtn;
}
/**
* Adds a key to the key list
*
* @param key
* Element to be added
*/
public void addKey(TreeObject key) {
keys[numKeys] = key;
numKeys++;
}
/**
* Adds a key to the key list to given index
*
* @param key
* Key to be added
* @param index
* Index to be added to it
*/
public void addKey(TreeObject key, int index) {
int i = numKeys;
while(i > index) {
keys[i] = keys[i-1];
i--;
}
keys[index] = key;
numKeys++;
}
/**
* Adds a child to the given index
*
* @param child
* Child to be add
* @param index
* Index to add child at
*/
public void addChild(Integer child, int index) {
int i = numChildren;
while(i > index) {
children[i] = children[i-1];
i--;
}
children[index] = child;
numChildren++;
}
/**
* Gets the child of the given index
*
* @param index
* Index of child
* @return The value of the int at that index
*/
public int getChild(int index) {
return children[index];
}
/**
* Removes the child at the index
*
* @param index
* The index of child
* @return The removed child value at that index
*/
public int removeChild(int index) {
int rtn = children[index];
int i = index;
while(i < numChildren-1) {
children[i] = children[i+1];
i++;
}
numChildren--;
return rtn;
}
/**
* @return True if this node is a leaf node, false otherwise
*/
public boolean isLeaf() {
return isLeaf;
}
/**
* Sets the isRoot boolean to true or false.
*
* @param leafValue
* Boolean to set the leaf value to
*/
public void setRoot(boolean isRoot) {
this.isRoot = isRoot;
}
/**
* Return if the node is the root
*/
public boolean isRoot() {
return this.isRoot;
}
/**
* Gets the offset.
*/
public int getOffset() {
return (maxBTreeNodeSize * index);
}
/**
* Gets the index of parent
*
* @return Parent Index
*/
public int getParentIndex() {
return parentIndex;
}
/**
* Sets the index of parent
*
* @param parent
*/
public void setParentIndex(int parentIndex) {
this.parentIndex = parentIndex;
}
@Override
public String toString() {
String btnstr = "";
btnstr += "Keys: ";
for (int i = 0; i < numKeys; i++) {
btnstr += keys[i] + " ";
}
btnstr += "\nChildren: ";
for (int i = 0; i < numChildren; i++) {
btnstr += children[i] + " ";
}
return btnstr;
}
}
} //End BTree