-
Notifications
You must be signed in to change notification settings - Fork 1
/
PEFGraph.java
1790 lines (1569 loc) · 71.9 KB
/
PEFGraph.java
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
package it.unimi.dsi.webgraph;
import com.gioaudino.thesis.ApproximatedPartition;
import com.gioaudino.thesis.CostEvaluation;
import com.gioaudino.thesis.Partition;
import com.martiansoftware.jsap.*;
import it.unimi.dsi.Util;
import it.unimi.dsi.bits.Fast;
import it.unimi.dsi.bits.LongArrayBitVector;
import it.unimi.dsi.fastutil.BigArrays;
import it.unimi.dsi.fastutil.io.BinIO;
import it.unimi.dsi.fastutil.longs.*;
import it.unimi.dsi.io.InputBitStream;
import it.unimi.dsi.io.OutputBitStream;
import it.unimi.dsi.lang.ObjectParser;
import it.unimi.dsi.logging.ProgressLogger;
import it.unimi.dsi.sux4j.util.EliasFanoMonotoneLongBigList;
import it.unimi.dsi.util.ByteBufferLongBigList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.LongBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import static it.unimi.dsi.bits.Fast.*;
/**
* An immutable graph based on the Partitioned Elias–Fano representation of monotone sequences.
*/
public class PEFGraph extends ImmutableGraph {
private static final Logger LOGGER = LoggerFactory.getLogger(PEFGraph.class);
/**
* The standard extension for the graph longword bit stream.
*/
public static final String GRAPH_EXTENSION = ".graph";
/**
* The standard extension for the graph-offsets bit stream.
*/
public static final String OFFSETS_EXTENSION = ".offsets";
/**
* The standard extension for the cached {@link LongBigList} containing the graph offsets.
*/
public static final String OFFSETS_BIG_LIST_EXTENSION = ".obl";
/**
* The default size of the bit cache.
*/
public final static int DEFAULT_CACHE_SIZE = 16 * 1024 * 1024;
/**
* This number classifies the present graph format. When new features require introducing binary
* incompatibilities, this number is bumped so to ensure that old classes do not try to read
* graphs they cannot understand.
*/
public final static int EFGRAPH_VERSION = 0;
/**
* The default base-two logarithm of the quantum.
*/
public static final int DEFAULT_LOG_2_QUANTUM = 8;
/**
* The standard extension for the graph longowrd first-level bit stream
*/
private static final String FIRST_LEVEL_EXTENSION = ".fst";
/**
* If set, the compression method will write some data in .txt files to analyse data distribution
*/
private static final boolean WRITE_DATA_DISTRIBUTION = false;
/**
* The number of nodes of the graph.
*/
protected final int n;
/**
* The upper bound used during the graph construction (greater than or equal to {@link #n}.
*/
protected final int upperBound;
/**
* The number of arcs of the graph.
*/
protected final long m;
/**
* The list containing the graph.
*/
protected final LongBigList graph;
/**
* An Elias–Fano monotone list containing the pointers of the bit streams stored in
* {@link #graph}.
*/
protected final LongBigList offsets;
/**
* First level data for the compressed Partitioned Elias-Fano graph
*/
protected final LongBigList firstlevels;
/**
* The basename of this graph (or possibly <code>null</code>).
*/
protected final CharSequence basename;
/**
* A longword bit reader used to read outdegrees.
*/
protected final LongWordBitReader outdegreeLongWordBitReader;
/**
*
*/
protected final LongWordBitReader algorithmLongWordBitReader;
/**
* The base-two logarithm of the indexing quantum.
*/
protected final int log2Quantum;
/**
* If not {@link Integer#MIN_VALUE}, the node whose degree is cached in {@link #cachedOutdegree}.
*/
protected int cachedNode;
/**
* If {@link #cachedNode} is not {@link Integer#MIN_VALUE}, its cached outdegree.
*/
protected int cachedOutdegree;
/**
* If {@link #cachedNode} is not {@link Integer#MIN_VALUE}, the position immediately after the
* coding of the outdegree of {@link #cachedNode}.
*/
protected long cachedPointer;
protected PEFGraph(final CharSequence basename, final int n, final long m, final int upperBound, final int log2Quantum, LongBigList graph, LongBigList offsets, LongBigList firstlevels) {
this.basename = basename;
this.n = n;
this.m = m;
this.upperBound = upperBound;
this.log2Quantum = log2Quantum;
this.graph = graph;
this.offsets = offsets;
cachedNode = Integer.MIN_VALUE;
this.firstlevels = firstlevels;
outdegreeLongWordBitReader = new LongWordBitReader(this.firstlevels, 0);
algorithmLongWordBitReader = new LongWordBitReader(this.graph, 0);
}
@Override
public CharSequence basename() {
return basename;
}
/**
* Returns the number of lower bits for the Elias–Fano encoding of a list of given length,
* upper bound and strictness.
*
* @param length the number of elements of the list.
* @param upperBound an upper bound for the elements of the list.
* @return the number of bits for the Elias–Fano encoding of a list with the specified
* parameters.
*/
public static int lowerBits(final long length, final long upperBound) {
return length == 0 ? 0 : Math.max(0, Fast.mostSignificantBit(upperBound / length));
}
/**
* Returns the size in bits of forward or skip pointers to the Elias–Fano encoding of a
* list of given length, upper bound and strictness.
*
* @param length the number of elements of the list.
* @param upperBound an upper bound for the elements of the list.
* @return the size of bits of forward or skip pointers the Elias–Fano encoding of a list
* with the specified parameters.
*/
public static int pointerSize(final long length, final long upperBound) {
return Math.max(0, Fast.ceilLog2(length + (upperBound >>> lowerBits(length, upperBound))));
}
/**
* Returns the number of forward or skip pointers to the Elias–Fano encoding of a list of
* given length, upper bound and strictness.
*
* @param length the number of elements of the list.
* @param upperBound an upper bound for the elements of the list.
* @param log2Quantum the logarithm of the quantum size.
* @return an upper bound on the number of skip pointers or the (exact) number of forward
* pointers.
*/
public static long numberOfPointers(final long length, final long upperBound, final int log2Quantum) {
if (length == 0) return 0;
return (upperBound >>> lowerBits(length, upperBound)) >>> log2Quantum;
}
protected final static class LongWordCache implements Closeable {
/**
* The spill file.
*/
private final File spillFile;
/**
* A channel opened on {@link #spillFile}.
*/
private final FileChannel spillChannel;
/**
* A cache for longwords. Will be spilled to {@link #spillChannel} in case more than
* {@link #cacheLength} bits are added.
*/
private final ByteBuffer cache;
/**
* The current bit buffer.
*/
private long buffer;
/**
* The current number of free bits in {@link #buffer}.
*/
private int free;
/**
* The length of the cache, in bits.
*/
private final long cacheLength;
/**
* The number of bits currently stored.
*/
private long length;
/**
* Whether {@link #spillChannel} should be repositioned at 0 before usage.
*/
private boolean spillMustBeRewind;
@SuppressWarnings("resource")
public LongWordCache(final int cacheSize, final String suffix) throws IOException {
spillFile = File.createTempFile(PEFGraph.class.getName(), suffix);
spillFile.deleteOnExit();
spillChannel = new RandomAccessFile(spillFile, "rw").getChannel();
cache = ByteBuffer.allocateDirect(cacheSize).order(ByteOrder.nativeOrder());
cacheLength = cacheSize * 8L;
free = Long.SIZE;
}
private void flushBuffer() throws IOException {
cache.putLong(buffer);
if (!cache.hasRemaining()) {
if (spillMustBeRewind) {
spillMustBeRewind = false;
spillChannel.position(0);
}
cache.flip();
spillChannel.write(cache);
cache.clear();
}
}
public int append(final long value, final int width) throws IOException {
assert width == Long.SIZE || (-1L << width & value) == 0;
buffer |= value << (Long.SIZE - free);
length += width;
if (width < free) free -= width;
else {
flushBuffer();
if (width == free) {
buffer = 0;
free = Long.SIZE;
} else {
// free < Long.SIZE
buffer = value >>> free;
free = Long.SIZE - width + free; // width > free
}
}
return width;
}
public void clear() {
length = buffer = 0;
free = Long.SIZE;
cache.clear();
spillMustBeRewind = true;
}
@Override
public void close() throws IOException {
spillChannel.close();
spillFile.delete();
}
public long length() {
return length;
}
public void writeUnary(int l) throws IOException {
if (l >= free) {
// Phase 1: align
l -= free;
length += free;
flushBuffer();
// Phase 2: jump over longwords
buffer = 0;
free = Long.SIZE;
while (l >= Long.SIZE) {
flushBuffer();
l -= Long.SIZE;
length += Long.SIZE;
}
}
append(1L << l, l + 1);
}
public long readLong() throws IOException {
if (!cache.hasRemaining()) {
cache.clear();
spillChannel.read(cache);
cache.flip();
}
return cache.getLong();
}
public void rewind() throws IOException {
if (free != Long.SIZE) cache.putLong(buffer);
if (length > cacheLength) {
cache.flip();
spillChannel.write(cache);
spillChannel.position(0);
cache.clear();
spillChannel.read(cache);
cache.flip();
} else cache.rewind();
}
}
public final static class LongWordOutputBitStream {
private static final int BUFFER_SIZE = 64 * 1024;
/**
* The 64-bit buffer, whose upper {@link #free} bits do not contain data.
*/
private long buffer;
/**
* The Java nio buffer used to write with prescribed endianness.
*/
private final ByteBuffer byteBuffer;
/**
* The number of upper free bits in {@link #buffer} (strictly positive).
*/
private int free;
/**
* The output channel.
*/
private final WritableByteChannel writableByteChannel;
public LongWordOutputBitStream(final WritableByteChannel writableByteChannel, final ByteOrder byteOrder) {
this.writableByteChannel = writableByteChannel;
byteBuffer = ByteBuffer.allocateDirect(BUFFER_SIZE).order(byteOrder);
free = Long.SIZE;
}
public int append(final long value, final int width) throws IOException {
assert width == Long.SIZE || (-1L << width & value) == 0;
buffer |= value << (Long.SIZE - free);
if (width < free) free -= width;
else {
byteBuffer.putLong(buffer); // filled
if (!byteBuffer.hasRemaining()) {
byteBuffer.flip();
writableByteChannel.write(byteBuffer);
byteBuffer.clear();
}
if (width == free) {
buffer = 0;
free = Long.SIZE;
} else {
// free < Long.SIZE
buffer = value >>> free;
free = Long.SIZE - width + free; // width > free
}
}
return width;
}
public long append(final long[] value, final long length) throws IOException {
long l = length;
for (int i = 0; l > 0; i++) {
final int width = (int) Math.min(l, Long.SIZE);
append(value[i], width);
l -= width;
}
return length;
}
public long append(final LongBigList value, final long length) throws IOException {
long l = length;
for (long i = 0; l > 0; i++) {
final int width = (int) Math.min(l, Long.SIZE);
append(value.getLong(i), width);
l -= width;
}
return length;
}
public long append(final LongArrayBitVector bv) throws IOException {
return append(bv.bits(), bv.length());
}
public long append(final LongWordCache cache) throws IOException {
long l = cache.length();
cache.rewind();
while (l > 0) {
final int width = (int) Math.min(l, Long.SIZE);
append(cache.readLong(), width);
l -= width;
}
return cache.length();
}
public int align() throws IOException {
if (free != Long.SIZE) {
byteBuffer.putLong(buffer); // partially filled
if (!byteBuffer.hasRemaining()) {
byteBuffer.flip();
writableByteChannel.write(byteBuffer);
byteBuffer.clear();
}
final int result = free;
buffer = 0;
free = Long.SIZE;
return result;
}
return 0;
}
public int writeNonZeroGamma(long value) throws IOException {
if (value <= 0) throw new IllegalArgumentException("The argument " + value + " is not strictly positive.");
final int msb = Fast.mostSignificantBit(value);
final long unary = 1L << msb;
append(unary, msb + 1);
append(value ^ unary, msb);
return 2 * msb + 1;
}
public int writeGamma(long value) throws IOException {
if (value < 0) throw new IllegalArgumentException("The argument " + value + " is negative.");
return writeNonZeroGamma(value + 1);
}
public void close() throws IOException {
byteBuffer.putLong(buffer);
byteBuffer.flip();
writableByteChannel.write(byteBuffer);
writableByteChannel.close();
}
}
protected final static class Accumulator implements Closeable {
/**
* The minimum size in bytes of a {@link LongWordCache}.
*/
private static final int MIN_CACHE_SIZE = 16;
/**
* The accumulator for successors (to zeros or ones).
*/
private final LongWordCache successors;
/**
* The accumulator for high bits.
*/
private final LongWordCache upperBits;
/**
* The accumulator for low bits.
*/
private final LongWordCache lowerBits;
/**
* The number of lower bits.
*/
private int l;
/**
* A mask extracting the {@link #l} lower bits.
*/
private long lowerBitsMask;
/**
* The number of elements that will be added to this list.
*/
private long length;
/**
* The current length of the list.
*/
private long currentLength;
/**
* The current prefix sum (decremented by {@link #currentLength} if {@link #strict} is
* true).
*/
private long currentPrefixSum;
/**
* An upper bound to the sum of all values that will be added to the list (decremented by
* {@link #currentLength} if {@link #strict} is true).
*/
private long correctedUpperBound;
/**
* The logarithm of the indexing quantum.
*/
private int log2Quantum;
/**
* The indexing quantum.
*/
private long quantum;
/**
* The size of a pointer (the ceiling of the logarithm of {@link #maxUpperBits}).
*/
private int pointerSize;
/**
* The last position where a one was set.
*/
private long lastOnePosition;
/**
* The expected number of points.
*/
private long expectedNumberOfPointers;
/**
* The number of bits used for the upper-bits array.
*/
public long bitsForUpperBits;
/**
* The number of bits used for the lower-bits array.
*/
public long bitsForLowerBits;
/**
* The number of bits used for forward/skip pointers.
*/
public long bitsForPointers;
public Accumulator(int bufferSize, int log2Quantum) throws IOException {
// A reasonable logic to allocate space.
bufferSize = bufferSize & -bufferSize; // Ensure power of 2.
/* Very approximately, half of the cache for lower, half for upper, and a small fraction
* (8/quantum) for pointers. This will generate a much larger cache than expected if
* quantum is very small. */
successors = new LongWordCache(Math.max(MIN_CACHE_SIZE, bufferSize >>> Math.max(3, log2Quantum - 3)), "pointers");
lowerBits = new LongWordCache(Math.max(MIN_CACHE_SIZE, bufferSize / 2), "lower");
upperBits = new LongWordCache(Math.max(MIN_CACHE_SIZE, bufferSize / 2), "upper");
}
public int lowerBits() {
return l;
}
public int pointerSize() {
return pointerSize;
}
public long numberOfPointers() {
return expectedNumberOfPointers;
}
public void init(final long length, final long upperBound, final boolean strict, final boolean indexZeroes, final int log2Quantum) {
this.log2Quantum = log2Quantum;
this.length = length;
quantum = 1L << log2Quantum;
successors.clear();
lowerBits.clear();
upperBits.clear();
correctedUpperBound = upperBound - (strict ? length : 0);
final long correctedLength = length + (!strict && indexZeroes ? 1 : 0); // The length, including the final terminator
if (correctedUpperBound < 0) throw new IllegalArgumentException();
currentPrefixSum = 0;
currentLength = 0;
lastOnePosition = -1;
l = PEFGraph.lowerBits(correctedLength, upperBound);
lowerBitsMask = (1L << l) - 1;
pointerSize = PEFGraph.pointerSize(correctedLength, upperBound);
expectedNumberOfPointers = PEFGraph.numberOfPointers(correctedLength, upperBound, log2Quantum);
// System.err.println("l = " + l + " numberOfPointers = " + expectedNumberOfPointers +
// " pointerSize = " + pointerSize);
}
public void add(final long x) throws IOException {
if (currentLength != 0 && x == 0) throw new IllegalArgumentException();
// System.err.println("add(" + x + "), l = " + l + ", length = " + length);
currentPrefixSum += x;
if (currentPrefixSum > correctedUpperBound)
throw new IllegalArgumentException("Too large prefix sum: " + currentPrefixSum + " >= " + correctedUpperBound);
if (l != 0) lowerBits.append(currentPrefixSum & lowerBitsMask, l);
final long onePosition = (currentPrefixSum >>> l) + currentLength;
upperBits.writeUnary((int) (onePosition - lastOnePosition - 1));
long zeroesBefore = lastOnePosition - currentLength + 1;
for (long position = lastOnePosition + (zeroesBefore & -1L << log2Quantum) + quantum - zeroesBefore; position < onePosition; position += quantum, zeroesBefore += quantum)
successors.append(position + 1, pointerSize);
lastOnePosition = onePosition;
currentLength++;
}
public long dump(final LongWordOutputBitStream lwobs) throws IOException {
if (currentLength != length) throw new IllegalStateException();
// Add last fictional document pointer equal to the number of documents.
add(correctedUpperBound - currentPrefixSum);
assert pointerSize == 0 || successors.length() / pointerSize == expectedNumberOfPointers : "Expected " + expectedNumberOfPointers + " pointers, found " + successors.length() / pointerSize;
// System.err.println("pointerSize :" + pointerSize);
bitsForPointers = lwobs.append(successors);
// System.err.println("pointers: " + bitsForPointers);
bitsForLowerBits = lwobs.append(lowerBits);
// System.err.println("lower: " + bitsForLowerBits);
bitsForUpperBits = lwobs.append(upperBits);
// System.err.println("upper: " + bitsForUpperBits);
return bitsForLowerBits + bitsForUpperBits + bitsForPointers;
}
@Override
public void close() throws IOException {
successors.close();
upperBits.close();
lowerBits.close();
}
}
/**
* Creates a new {@link PEFGraph} by loading a compressed graph file from disk to memory, with no
* progress logger and all offsets.
*
* @param basename the basename of the graph.
* @return a {@link PEFGraph} containing the specified graph.
* @throws IOException if an I/O exception occurs while reading the graph.
*/
public static PEFGraph load(CharSequence basename) throws IOException {
return loadInternal(basename, false, null);
}
/**
* Creates a new {@link PEFGraph} by loading a compressed graph file from disk to memory, with
* all offsets.
*
* @param basename the basename of the graph.
* @param pl a progress logger used while loading the graph, or <code>null</code>.
* @return a {@link PEFGraph} containing the specified graph.
* @throws IOException if an I/O exception occurs while reading the graph.
*/
public static PEFGraph load(CharSequence basename, ProgressLogger pl) throws IOException {
return loadInternal(basename, false, pl);
}
/**
* Creates a new {@link PEFGraph} by memory-mapping a graph file.
*
* @param basename the basename of the graph.
* @return an {@link PEFGraph} containing the specified graph.
* @throws IOException if an I/O exception occurs while memory-mapping the graph or reading the
* offsets.
*/
public static PEFGraph loadMapped(CharSequence basename) throws IOException {
return loadInternal(basename, true, null);
}
/**
* Creates a new {@link PEFGraph} by memory-mapping a graph file.
*
* @param basename the basename of the graph.
* @param pl a progress logger used while loading the offsets, or <code>null</code>.
* @return an {@link PEFGraph} containing the specified graph.
* @throws IOException if an I/O exception occurs while memory-mapping the graph or reading the
* offsets.
*/
public static PEFGraph loadMapped(CharSequence basename, ProgressLogger pl) throws IOException {
return loadInternal(basename, true, pl);
}
/**
* Creates a new {@link PEFGraph} by loading a compressed graph file from disk to memory, without
* offsets.
*
* @param basename the basename of the graph.
* @param pl a progress logger used while loading the graph, or <code>null</code>.
* @return a {@link PEFGraph} containing the specified graph.
* @throws IOException if an I/O exception occurs while reading the graph.
* @deprecated Use {@link #loadOffline(CharSequence, ProgressLogger)} or {@link #loadMapped(CharSequence, ProgressLogger)} instead.
*/
@Deprecated
public static PEFGraph loadSequential(CharSequence basename, ProgressLogger pl) throws IOException {
return PEFGraph.load(basename, pl);
}
/**
* Creates a new {@link PEFGraph} by loading a compressed graph file from disk to memory, with no
* progress logger and without offsets.
*
* @param basename the basename of the graph.
* @return a {@link PEFGraph} containing the specified graph.
* @deprecated Use {@link #loadOffline(CharSequence)} or {@link #loadMapped(CharSequence)} instead.
*/
@Deprecated
public static PEFGraph loadSequential(CharSequence basename) throws IOException {
return PEFGraph.load(basename);
}
/**
* Creates a new {@link PEFGraph} by loading just the metadata of a compressed graph file.
*
* @param basename the basename of the graph.
* @param pl a progress logger, or <code>null</code>.
* @return a {@link PEFGraph} containing the specified graph.
* @throws IOException if an I/O exception occurs while reading the metadata.
*/
public static PEFGraph loadOffline(CharSequence basename, ProgressLogger pl) throws IOException {
return PEFGraph.loadMapped(basename, pl);
}
/**
* Creates a new {@link PEFGraph} by loading just the metadata of a compressed graph file.
*
* @param basename the basename of the graph.
* @return a {@link PEFGraph} containing the specified graph.
* @throws IOException if an I/O exception occurs while reading the metadata.
*/
public static PEFGraph loadOffline(CharSequence basename) throws IOException {
return PEFGraph.loadMapped(basename, null);
}
/**
* An iterator returning the offsets.
*/
private final static class OffsetsLongIterator implements LongIterator {
private final InputBitStream offsetIbs;
private final long n;
private long offset;
private long i;
private OffsetsLongIterator(final InputBitStream offsetIbs, final long n) {
this.offsetIbs = offsetIbs;
this.n = n;
}
@Override
public boolean hasNext() {
return i <= n;
}
@Override
public long nextLong() {
if (!hasNext()) throw new NoSuchElementException();
i++;
try {
return offset += offsetIbs.readLongDelta();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
/**
* Commodity method for loading a big list of binary longs with specified endianness into a
* {@linkplain LongBigArrays long big array}.
*
* @param filename the file containing the longs.
* @param byteOrder the endianness of the longs.
* @return a big list of longs containing the longs in <code>filename</code>.
*/
public static LongBigArrayBigList loadLongBigList(final CharSequence filename, final ByteOrder byteOrder) throws IOException {
final long length = new File(filename.toString()).length() / (Long.SIZE / Byte.SIZE);
@SuppressWarnings("resource") final ReadableByteChannel channel = new FileInputStream(filename.toString()).getChannel();
final ByteBuffer byteBuffer = ByteBuffer.allocateDirect(64 * 1024).order(byteOrder);
final LongBuffer longBuffer = byteBuffer.asLongBuffer();
final long[][] array = LongBigArrays.newBigArray(length);
long pos = 0;
while (channel.read(byteBuffer) > 0) {
byteBuffer.flip();
final int remainingLongs = byteBuffer.remaining() / (Long.SIZE / Byte.SIZE);
longBuffer.clear();
longBuffer.limit(remainingLongs);
longBuffer.get(array[BigArrays.segment(pos)], BigArrays.displacement(pos), remainingLongs);
pos += remainingLongs;
byteBuffer.clear();
}
channel.close();
return LongBigArrayBigList.wrap(array);
}
/**
* Loads a compressed graph file from disk into this graph. Note that this method should be
* called <em>only</em> on a newly created graph.
*
* @param basename the basename of the graph.
* @param mapped whether we want to memory-map the file.
* @param pl a progress logger used while loading the graph, or <code>null</code>.
* @return this graph.
*/
protected static PEFGraph loadInternal(final CharSequence basename, final boolean mapped, final ProgressLogger pl) throws IOException {
// First of all, we read the property file to get the relevant data.
final FileInputStream propertyFile = new FileInputStream(basename + PROPERTIES_EXTENSION);
final Properties properties = new Properties();
properties.load(propertyFile);
propertyFile.close();
// Soft check--we accept big stuff, too.
if (!PEFGraph.class.getName().equals(properties.getProperty(ImmutableGraph.GRAPHCLASS_PROPERTY_KEY).replace("it.unimi.dsi.big.webgraph", "it.unimi.dsi.webgraph")))
throw new IOException(
"This class (" + PEFGraph.class.getName() + ") cannot load a graph stored using class \"" + properties.getProperty(ImmutableGraph.GRAPHCLASS_PROPERTY_KEY) + "\"");
if (properties.getProperty("version") == null) throw new IOException("Missing format version information");
else if (Integer.parseInt(properties.getProperty("version")) > EFGRAPH_VERSION)
throw new IOException("This graph uses format " + properties.getProperty("version")
+ ", but this class can understand only graphs up to format " + EFGRAPH_VERSION);
final long nodes = Long.parseLong(properties.getProperty("nodes"));
if (nodes > Integer.MAX_VALUE)
throw new IllegalArgumentException("The standard version of WebGraph cannot handle graphs with " + nodes + " (>2^31) nodes");
final int n = (int) nodes;
final long m = Long.parseLong(properties.getProperty("arcs"));
final int upperBound = properties.containsKey("upperbound") ? Integer.parseInt(properties.getProperty("upperbound")) : n;
final long quantum = Long.parseLong(properties.getProperty("quantum"));
final int log2Quantum = Fast.mostSignificantBit(quantum);
if (1L << log2Quantum != quantum)
throw new IllegalArgumentException("Illegal quantum (must be a power of 2): " + quantum);
final ByteOrder byteOrder;
if (properties.get("byteorder").equals(ByteOrder.BIG_ENDIAN.toString())) byteOrder = ByteOrder.BIG_ENDIAN;
else if (properties.get("byteorder").equals(ByteOrder.LITTLE_ENDIAN.toString()))
byteOrder = ByteOrder.LITTLE_ENDIAN;
else throw new IllegalArgumentException("Unknown byte order " + properties.get("byteorder"));
final FileInputStream graphIs = new FileInputStream(basename + GRAPH_EXTENSION);
final LongBigList graph;
if (mapped) graph = ByteBufferLongBigList.map(graphIs.getChannel(), byteOrder);
else {
if (pl != null) {
pl.itemsName = "bytes";
pl.start("Loading graph...");
}
graph = loadLongBigList(basename + GRAPH_EXTENSION, byteOrder);
if (pl != null) {
pl.count = graph.size64() * (Long.SIZE / Byte.SIZE);
pl.done();
}
graphIs.close();
}
if (pl != null) {
pl.itemsName = "deltas";
pl.start("Loading offsets...");
}
// Loading first level bitstream
final LongBigList firstLevels;
final FileInputStream fstIs = new FileInputStream(basename + FIRST_LEVEL_EXTENSION);
if (mapped) firstLevels = ByteBufferLongBigList.map(fstIs.getChannel(), byteOrder);
else {
firstLevels = loadLongBigList(basename + FIRST_LEVEL_EXTENSION, byteOrder);
fstIs.close();
}
// We try to load a cached big list.
final File offsetsBigListFile = new File(basename + OFFSETS_BIG_LIST_EXTENSION);
LongBigList offsets = null;
if (offsetsBigListFile.exists()) {
if (new File(basename + OFFSETS_EXTENSION).lastModified() > offsetsBigListFile.lastModified()) LOGGER
.warn("A cached long big list of offsets was found, but the corresponding offsets file has a later modification time");
else try {
offsets = (LongBigList) BinIO.loadObject(offsetsBigListFile);
} catch (ClassNotFoundException e) {
LOGGER.warn("A cached long big list of offsets was found, but its class is unknown", e);
}
}
if (offsets == null) {
final InputBitStream offsetIbs = new InputBitStream(basename + OFFSETS_EXTENSION);
offsets = new EliasFanoMonotoneLongBigList(n + 1, firstLevels.size64() * Long.SIZE + 1, new OffsetsLongIterator(offsetIbs, n));
offsetIbs.close();
}
if (pl != null) {
pl.count = n + 1;
pl.done();
if (offsets instanceof EliasFanoMonotoneLongBigList)
pl.logger().info("Pointer bits per node: " + Util.format(((EliasFanoMonotoneLongBigList) offsets).numBits() / (n + 1.0)));
}
return new PEFGraph(basename, n, m, upperBound, log2Quantum, graph, offsets, firstLevels);
}
public static void store(ImmutableGraph graph, final int upperBound, final CharSequence basename, final ProgressLogger pl) throws IOException {
store(graph, upperBound, basename, DEFAULT_LOG_2_QUANTUM, DEFAULT_CACHE_SIZE, ByteOrder.nativeOrder(), pl);
}
public static void store(ImmutableGraph graph, final CharSequence basename, final ProgressLogger pl) throws IOException {
store(graph, basename, DEFAULT_LOG_2_QUANTUM, DEFAULT_CACHE_SIZE, ByteOrder.nativeOrder(), pl);
}
public static void store(ImmutableGraph graph, final CharSequence basename) throws IOException {
store(graph, basename, null);
}
private static double stirling(double n) {
return n * Math.log(n) - n + (1. / 2) * Math.log(2 * Math.PI * n);
}
public static void store(ImmutableGraph graph, final CharSequence basename, final int log2Quantum, final int cacheSize, final ByteOrder byteOrder, final ProgressLogger pl) throws IOException {
store(graph, graph.numNodes(), basename, log2Quantum, cacheSize, byteOrder, pl);
}
public static void store(ImmutableGraph graph, final int upperBound, final CharSequence basename, final int log2Quantum, final int cacheSize, final ByteOrder byteOrder, final ProgressLogger pl)
throws IOException {
if (log2Quantum < 0) throw new IllegalArgumentException(Integer.toString(log2Quantum));
final Accumulator successorsAccumulator = new Accumulator(cacheSize, log2Quantum);
final FileOutputStream graphOs = new FileOutputStream(basename + GRAPH_EXTENSION);
final FileChannel graphChannel = graphOs.getChannel();
final LongWordOutputBitStream graphStream = new LongWordOutputBitStream(graphChannel, byteOrder);
final OutputBitStream offsets = new OutputBitStream(basename + OFFSETS_EXTENSION);
long numberOfArcs = 0;
long bitsForOutdegrees = 0;
long bitsForSuccessors = 0;
long deltaBitsForFirstLevel;
offsets.writeLongDelta(0);
final FileOutputStream fstOs = new FileOutputStream(basename + FIRST_LEVEL_EXTENSION);
final FileChannel fstChannel = fstOs.getChannel();
final LongWordOutputBitStream fstStream = new LongWordOutputBitStream(fstChannel, byteOrder);
PrintWriter maxWriter;
PrintWriter offsetWriter;
if (WRITE_DATA_DISTRIBUTION) {
maxWriter = new PrintWriter(new FileWriter(basename + "-max.txt"));
offsetWriter = new PrintWriter(new FileWriter(basename + "-offset.txt"));
}
long bitsForLowerbound = 0;
long bitsForMax = 0;
long bitsForOffset = 0;
long bitsForSize = 0;
long noneChunks = 0;
long bitVectorChunks = 0;
long eliasFanoChunks = 0;
long chunksWithOffset = 0;
if (pl != null) {
pl.itemsName = "nodes";
try {
pl.expectedUpdates = graph.numNodes();
} catch (UnsupportedOperationException ignore) {
}
pl.start("Storing...");
}
final long n = graph.numNodes();
for (NodeIterator nodeIterator = graph.nodeIterator(); nodeIterator.hasNext(); ) {
int node = nodeIterator.nextInt();
final long outdegree = nodeIterator.outdegree();
numberOfArcs += outdegree;
int[] successors = nodeIterator.successorArray();
successors = Arrays.copyOf(successors, nodeIterator.outdegree());
List<Partition> partition = ApproximatedPartition.createApproximatedPartition(successors, log2Quantum);
final int outDegreeBits = fstStream.writeGamma(outdegree);
bitsForOutdegrees += outDegreeBits;
deltaBitsForFirstLevel = outDegreeBits;
if (outdegree == 0) {
offsets.writeLongDelta(deltaBitsForFirstLevel);
if (pl != null) pl.lightUpdate();
continue;
}
long lowerbound = successors[0];
long lastmax = lowerbound;
int size;
long offset = -1;
final int lowerboundBits = fstStream.writeGamma(int2nat(lowerbound - node));
deltaBitsForFirstLevel += lowerboundBits;
bitsForLowerbound += lowerboundBits;
Iterator<Partition> iterator = partition.iterator();
boolean shouldWriteOffset = true;
while (iterator.hasNext()) {
Partition subset = iterator.next();