-
Notifications
You must be signed in to change notification settings - Fork 238
/
TableIR.scala
1914 lines (1532 loc) · 65.2 KB
/
TableIR.scala
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 is.hail.expr.ir
import java.io.ByteArrayInputStream
import is.hail.HailContext
import is.hail.annotations._
import is.hail.annotations.aggregators.RegionValueAggregator
import is.hail.expr.types._
import is.hail.expr.types.physical.{PArray, PBaseStruct, PInt32, PStruct, PType}
import is.hail.expr.types.virtual._
import is.hail.expr.JSONAnnotationImpex
import is.hail.expr.ir
import is.hail.expr.ir.functions.{BlockMatrixToTableFunction, MatrixToTableFunction, TableToTableFunction}
import is.hail.linalg.{BlockMatrix, BlockMatrixMetadata, BlockMatrixReadRowBlockedRDD}
import is.hail.rvd._
import is.hail.sparkextras.ContextRDD
import is.hail.table.{AbstractTableSpec, Ascending, SortField}
import is.hail.utils._
import is.hail.variant._
import java.io.{ObjectInputStream, ObjectOutputStream}
import is.hail.io._
import org.apache.spark.sql.{DataFrame, Row}
import org.apache.spark.storage.StorageLevel
import org.json4s.{CustomSerializer, Formats, JObject, ShortTypeHints}
import org.json4s.JsonAST.{JArray, JField, JInt, JNothing, JNull, JString}
import org.json4s.JsonDSL._
import org.json4s.jackson.JsonMethods
import scala.reflect.ClassTag
object TableIR {
def read(hc: HailContext, path: String, dropRows: Boolean, requestedType: Option[TableType]): TableIR = {
val successFile = path + "/_SUCCESS"
if (!hc.sFS.exists(path + "/_SUCCESS"))
fatal(s"write failed: file not found: $successFile")
val tr = TableNativeReader(path)
TableRead(requestedType.getOrElse(tr.fullType), dropRows = dropRows, tr)
}
}
abstract sealed class TableIR extends BaseIR {
def typ: TableType
def partitionCounts: Option[IndexedSeq[Long]] = None
val rowCountUpperBound: Option[Long]
protected[ir] def execute(ctx: ExecuteContext): TableValue =
fatal("tried to execute unexecutable IR:\n" + Pretty(this))
override def copy(newChildren: IndexedSeq[BaseIR]): TableIR
def persist(storageLevel: StorageLevel): TableIR = {
// FIXME: store table literal in cache, return ID
ExecuteContext.scoped { ctx =>
val tv = Interpret(this, ctx, optimize = true)
TableLiteral(tv, ctx)
}
}
def unpersist(): TableIR = {
this match {
case TableLiteral(typ, rvd, enc, encodedGlobals) => TableLiteral(typ, rvd.unpersist(), enc, encodedGlobals)
case x => x
}
}
def pyPersist(storageLevel: String): TableIR = {
val level = try {
StorageLevel.fromString(storageLevel)
} catch {
case e: IllegalArgumentException =>
fatal(s"unknown StorageLevel: $storageLevel")
}
persist(level)
}
def pyUnpersist(): TableIR = unpersist()
def pyToDF(): DataFrame = {
ExecuteContext.scoped { ctx =>
Interpret(this, ctx).toDF()
}
}
}
object TableLiteral {
def apply(value: TableValue, ctx: ExecuteContext): TableLiteral = {
val globalPType = PType.canonical(value.typ.globalType)
val enc = TypedCodecSpec(globalPType, BufferSpec.wireSpec) // use wireSpec to save memory
using(new ByteArrayEncoder(enc.buildEncoder(globalPType))) { encoder =>
TableLiteral(value.typ, value.rvd, enc,
encoder.regionValueToBytes(value.globals.value.region, value.globals.value.offset))
}
}
}
case class TableLiteral(typ: TableType, rvd: RVD, enc: AbstractTypedCodecSpec, encodedGlobals: Array[Byte]) extends TableIR {
val children: IndexedSeq[BaseIR] = Array.empty[BaseIR]
lazy val rowCountUpperBound: Option[Long] = None
def copy(newChildren: IndexedSeq[BaseIR]): TableLiteral = {
assert(newChildren.isEmpty)
TableLiteral(typ, rvd, enc, encodedGlobals)
}
protected[ir] override def execute(ctx: ExecuteContext): TableValue = {
val (globalPType: PStruct, dec) = enc.buildDecoder(typ.globalType)
val bais = new ByteArrayInputStream(encodedGlobals)
val globalOffset = dec.apply(bais).readRegionValue(ctx.r)
TableValue(typ, BroadcastRow(RegionValue(ctx.r, globalOffset), globalPType, HailContext.backend), rvd)
}
}
object TableReader {
implicit val formats: Formats = RelationalSpec.formats + ShortTypeHints(
List(classOf[TableNativeReader],
classOf[TableNativeZippedReader],
classOf[TextTableReader],
classOf[TextInputFilterAndReplace],
classOf[TableFromBlockMatrixNativeReader])
) + new NativeReaderOptionsSerializer()
}
abstract class TableReader {
def apply(tr: TableRead, ctx: ExecuteContext): TableValue
def partitionCounts: Option[IndexedSeq[Long]]
def fullType: TableType
}
case class TableNativeReader(
path: String,
options: Option[NativeReaderOptions] = None,
var _spec: AbstractTableSpec = null
) extends TableReader {
lazy val spec = if (_spec != null)
_spec
else
(RelationalSpec.read(HailContext.get, path): @unchecked) match {
case ts: AbstractTableSpec => ts
case _: AbstractMatrixTableSpec => fatal(s"file is a MatrixTable, not a Table: '$path'")
}
def partitionCounts: Option[IndexedSeq[Long]] = if (intervals.isEmpty) Some(spec.partitionCounts) else None
override lazy val fullType: TableType = spec.table_type
private val filterIntervals = options.map(_.filterIntervals).getOrElse(false)
private def intervals = options.map(_.intervals)
if (intervals.nonEmpty && !spec.indexed(path))
fatal("""`intervals` specified on an unindexed table.
|This table was written using an older version of hail
|rewrite the table in order to create an index to proceed""".stripMargin)
def apply(tr: TableRead, ctx: ExecuteContext): TableValue = {
val hc = HailContext.get
val (globalType, globalsOffset) = spec.globalsComponent.readLocalSingleRow(hc, path, tr.typ.globalType, ctx.r)
val rvd = if (tr.dropRows) {
RVD.empty(hc.sc, tr.typ.canonicalRVDType)
} else {
val partitioner = if (filterIntervals)
intervals.map(i => RVDPartitioner.union(tr.typ.keyType, i, tr.typ.key.length - 1))
else
intervals.map(i => new RVDPartitioner(tr.typ.keyType, i))
val rvd = spec.rowsComponent.read(hc, path, tr.typ.rowType, partitioner, filterIntervals)
if (rvd.typ.key startsWith tr.typ.key)
rvd
else {
log.info("Sorting a table after read. Rewrite the table to prevent this in the future.")
rvd.changeKey(tr.typ.key)
}
}
TableValue(tr.typ, BroadcastRow(RegionValue(ctx.r, globalsOffset), globalType, hc.backend), rvd)
}
}
case class TableNativeZippedReader(
pathLeft: String,
pathRight: String,
options: Option[NativeReaderOptions] = None,
var _specLeft: AbstractTableSpec = null,
var _specRight: AbstractTableSpec = null
) extends TableReader {
private def getSpec(path: String) = (RelationalSpec.read(HailContext.get, path): @unchecked) match {
case ts: AbstractTableSpec => ts
case _: AbstractMatrixTableSpec => fatal(s"file is a MatrixTable, not a Table: '$path'")
}
lazy val specLeft = if (_specLeft != null) _specLeft else getSpec(pathLeft)
lazy val specRight = if (_specRight != null) _specRight else getSpec(pathRight)
private lazy val filterIntervals = options.map(_.filterIntervals).getOrElse(false)
private def intervals = options.map(_.intervals)
require((specLeft.table_type.rowType.fieldNames ++ specRight.table_type.rowType.fieldNames).areDistinct())
require(specRight.table_type.key.isEmpty)
require(specLeft.partitionCounts sameElements specRight.partitionCounts)
require(specLeft.version == specRight.version)
def partitionCounts: Option[IndexedSeq[Long]] = if (intervals.isEmpty) Some(specLeft.partitionCounts) else None
override lazy val fullType: TableType = specLeft.table_type.copy(rowType = specLeft.table_type.rowType ++ specRight.table_type.rowType)
def apply(tr: TableRead, ctx: ExecuteContext): TableValue = {
val hc = HailContext.get
val (globalPType: PStruct, globalsOffset) = specLeft.globalsComponent.readLocalSingleRow(hc, pathLeft, tr.typ.globalType, ctx.r)
val rvd = if (tr.dropRows) {
RVD.empty(hc.sc, tr.typ.canonicalRVDType)
} else {
val partitioner = if (filterIntervals)
intervals.map(i => RVDPartitioner.union(tr.typ.keyType, i, tr.typ.key.length - 1))
else
intervals.map(i => new RVDPartitioner(tr.typ.keyType, i))
val leftFieldSet = specLeft.table_type.rowType.fieldNames.toSet
val rightFieldSet = specRight.table_type.rowType.fieldNames.toSet
if (tr.typ.rowType.fieldNames.forall(f => !rightFieldSet.contains(f))) {
specLeft.rowsComponent.read(hc, pathLeft, tr.typ.rowType, partitioner, filterIntervals)
} else if (tr.typ.rowType.fieldNames.forall(f => !leftFieldSet.contains(f))) {
specRight.rowsComponent.read(hc, pathRight, tr.typ.rowType, partitioner, filterIntervals)
} else {
val rvdSpecLeft = specLeft.rowsComponent.rvdSpec(hc.sFS, pathLeft)
val rvdSpecRight = specRight.rowsComponent.rvdSpec(hc.sFS, pathRight)
val rvdPathLeft = specLeft.rowsComponent.absolutePath(pathLeft)
val rvdPathRight = specRight.rowsComponent.absolutePath(pathRight)
val leftRType = tr.typ.rowType.filter(f => leftFieldSet.contains(f.name))._1
val rightRType = tr.typ.rowType.filter(f => rightFieldSet.contains(f.name))._1
AbstractRVDSpec.readZipped(hc,
rvdSpecLeft, rvdSpecRight,
rvdPathLeft, rvdPathRight,
tr.typ.rowType,
leftRType, rightRType,
partitioner, filterIntervals)
}
}
TableValue(tr.typ, BroadcastRow(RegionValue(ctx.r, globalsOffset), globalPType, hc.backend), rvd)
}
}
case class TableFromBlockMatrixNativeReader(path: String, nPartitions: Option[Int] = None) extends TableReader {
val metadata: BlockMatrixMetadata = BlockMatrix.readMetadata(HailContext.get, path)
val getNumPartitions: Int = nPartitions.getOrElse(HailContext.get.sc.defaultMinPartitions)
val partitionRanges = (0 until getNumPartitions).map { i =>
val nRows = metadata.nRows
val start = (i * nRows) / getNumPartitions
val end = ((i + 1) * nRows) / getNumPartitions
start until end
}
override def partitionCounts: Option[IndexedSeq[Long]] = {
Some(partitionRanges.map(r => r.end - r.start))
}
override lazy val fullType: TableType = {
val rowType = TStruct("row_idx" -> TInt64(), "entries" -> TArray(TFloat64()))
TableType(rowType, Array("row_idx"), TStruct())
}
def apply(tr: TableRead, ctx: ExecuteContext): TableValue = {
val rowsRDD = new BlockMatrixReadRowBlockedRDD(path, partitionRanges, metadata, HailContext.get)
val partitionBounds = partitionRanges.map { r => Interval(Row(r.start), Row(r.end), true, false) }
val partitioner = new RVDPartitioner(fullType.keyType, partitionBounds)
val rvd = RVD(fullType.canonicalRVDType, partitioner, ContextRDD(rowsRDD))
TableValue(fullType, BroadcastRow.empty(ctx), rvd)
}
}
case class TableRead(typ: TableType, dropRows: Boolean, tr: TableReader) extends TableIR {
assert(PruneDeadFields.isSupertype(typ, tr.fullType),
s"\n original: ${ tr.fullType }\n requested: $typ")
override def partitionCounts: Option[IndexedSeq[Long]] = tr.partitionCounts
lazy val rowCountUpperBound: Option[Long] = partitionCounts.map(_.sum)
val children: IndexedSeq[BaseIR] = Array.empty[BaseIR]
def copy(newChildren: IndexedSeq[BaseIR]): TableRead = {
assert(newChildren.isEmpty)
TableRead(typ, dropRows, tr)
}
protected[ir] override def execute(ctx: ExecuteContext): TableValue = tr.apply(this, ctx)
}
case class TableParallelize(rowsAndGlobal: IR, nPartitions: Option[Int] = None) extends TableIR {
require(rowsAndGlobal.typ.isInstanceOf[TStruct])
require(rowsAndGlobal.typ.asInstanceOf[TStruct].fieldNames.sameElements(Array("rows", "global")))
lazy val rowCountUpperBound: Option[Long] = None
private val rowsType = rowsAndGlobal.typ.asInstanceOf[TStruct].fieldType("rows").asInstanceOf[TArray]
private val globalsType = rowsAndGlobal.typ.asInstanceOf[TStruct].fieldType("global").asInstanceOf[TStruct]
val children: IndexedSeq[BaseIR] = FastIndexedSeq(rowsAndGlobal)
def copy(newChildren: IndexedSeq[BaseIR]): TableParallelize = {
val IndexedSeq(newrowsAndGlobal: IR) = newChildren
TableParallelize(newrowsAndGlobal, nPartitions)
}
val typ: TableType = TableType(
rowsType.elementType.asInstanceOf[TStruct],
FastIndexedSeq(),
globalsType)
protected[ir] override def execute(ctx: ExecuteContext): TableValue = {
val hc = HailContext.get
val (Row(_rows: IndexedSeq[_], globals: Row), _) = CompileAndEvaluate[Row](ctx, rowsAndGlobal, optimize = false)
val rows = _rows.asInstanceOf[IndexedSeq[Row]]
rows.zipWithIndex.foreach { case (r, idx) =>
if (r == null)
fatal(s"cannot parallelize null values: found null value at index $idx")
}
log.info(s"parallelized ${ rows.length } rows")
val rowTyp = PType.canonical(typ.rowType).asInstanceOf[PStruct]
val rvd = ContextRDD.parallelize[RVDContext](hc.sc, rows, nPartitions)
.cmapPartitions((ctx, it) => it.toRegionValueIterator(ctx.region, rowTyp))
TableValue(typ, BroadcastRow(ctx, globals, typ.globalType), RVD.unkeyed(rowTyp, rvd))
}
}
/**
* Change the table to have key 'keys'.
*
* Let n be the longest common prefix of 'keys' and the old key, i.e. the
* number of key fields that are not being changed.
* - If 'isSorted', then 'child' must already be sorted by 'keys', and n must
* not be zero. Thus, if 'isSorted', TableKeyBy will not shuffle or scan.
* The new partitioner will be the old one with partition bounds truncated
* to length n.
* - If n = 'keys.length', i.e. we are simply shortening the key, do nothing
* but change the table type to the new key. 'isSorted' is ignored.
* - Otherwise, if 'isSorted' is false and n < 'keys.length', then shuffle.
*/
case class TableKeyBy(child: TableIR, keys: IndexedSeq[String], isSorted: Boolean = false) extends TableIR {
private val fields = child.typ.rowType.fieldNames.toSet
assert(keys.forall(fields.contains), s"${ keys.filter(k => !fields.contains(k)).mkString(", ") }")
lazy val rowCountUpperBound: Option[Long] = child.rowCountUpperBound
val children: IndexedSeq[BaseIR] = Array(child)
val typ: TableType = child.typ.copy(key = keys)
def copy(newChildren: IndexedSeq[BaseIR]): TableKeyBy = {
assert(newChildren.length == 1)
TableKeyBy(newChildren(0).asInstanceOf[TableIR], keys, isSorted)
}
protected[ir] override def execute(ctx: ExecuteContext): TableValue = {
val tv = child.execute(ctx)
tv.copy(typ = typ, rvd = tv.rvd.enforceKey(keys, isSorted))
}
}
case class TableRange(n: Int, nPartitions: Int) extends TableIR {
require(n >= 0)
require(nPartitions > 0)
private val nPartitionsAdj = math.max(math.min(n, nPartitions), 1)
val children: IndexedSeq[BaseIR] = Array.empty[BaseIR]
def copy(newChildren: IndexedSeq[BaseIR]): TableRange = {
assert(newChildren.isEmpty)
TableRange(n, nPartitions)
}
private val partCounts = partition(n, nPartitionsAdj)
override val partitionCounts = Some(partCounts.map(_.toLong).toFastIndexedSeq)
lazy val rowCountUpperBound: Option[Long] = Some(n.toLong)
val typ: TableType = TableType(
TStruct("idx" -> TInt32()),
Array("idx"),
TStruct.empty())
protected[ir] override def execute(ctx: ExecuteContext): TableValue = {
val localRowType = PType.canonical(typ.rowType).asInstanceOf[PStruct]
val localPartCounts = partCounts
val partStarts = partCounts.scanLeft(0)(_ + _)
val hc = HailContext.get
TableValue(typ,
BroadcastRow.empty(ctx),
new RVD(
RVDType(localRowType, Array("idx")),
new RVDPartitioner(Array("idx"), typ.rowType,
Array.tabulate(nPartitionsAdj) { i =>
val start = partStarts(i)
val end = partStarts(i + 1)
Interval(Row(start), Row(end), includesStart = true, includesEnd = false)
}),
ContextRDD.parallelize(hc.sc, Range(0, nPartitionsAdj), nPartitionsAdj)
.cmapPartitionsWithIndex { case (i, ctx, _) =>
val region = ctx.region
val rv = RegionValue(region)
val start = partStarts(i)
Iterator.range(start, start + localPartCounts(i))
.map { j =>
val off = localRowType.allocate(region)
localRowType.setFieldPresent(region, off, 0)
Region.storeInt(localRowType.fieldOffset(off, 0), j)
rv.setOffset(off)
rv
}
}))
}
}
case class TableFilter(child: TableIR, pred: IR) extends TableIR {
val children: IndexedSeq[BaseIR] = Array(child, pred)
val typ: TableType = child.typ
lazy val rowCountUpperBound: Option[Long] = child.rowCountUpperBound
def copy(newChildren: IndexedSeq[BaseIR]): TableFilter = {
assert(newChildren.length == 2)
TableFilter(newChildren(0).asInstanceOf[TableIR], newChildren(1).asInstanceOf[IR])
}
protected[ir] override def execute(ctx: ExecuteContext): TableValue = {
val tv = child.execute(ctx)
if (pred == True())
return tv
else if (pred == False())
return tv.copy(rvd = RVD.empty(HailContext.get.sc, typ.canonicalRVDType))
val (rTyp, f) = ir.Compile[Long, Long, Boolean](
"row", tv.rvd.rowPType,
"global", tv.globals.t,
pred)
assert(rTyp.virtualType == TBoolean())
tv.filterWithPartitionOp(f)((rowF, rv, globalRV) => rowF(rv.region, rv.offset, false, globalRV.offset, false))
}
}
case class TableHead(child: TableIR, n: Long) extends TableIR {
require(n >= 0, fatal(s"TableHead: n must be non-negative! Found '$n'."))
def typ: TableType = child.typ
lazy val children: IndexedSeq[BaseIR] = FastIndexedSeq(child)
def copy(newChildren: IndexedSeq[BaseIR]): TableHead = {
val IndexedSeq(newChild: TableIR) = newChildren
TableHead(newChild, n)
}
override def partitionCounts: Option[IndexedSeq[Long]] =
child.partitionCounts.map(getHeadPartitionCounts(_, n))
lazy val rowCountUpperBound: Option[Long] = child.rowCountUpperBound match {
case Some(c) => Some(c.min(n))
case None => Some(n)
}
protected[ir] override def execute(ctx: ExecuteContext): TableValue = {
val prev = child.execute(ctx)
prev.copy(rvd = prev.rvd.head(n, child.partitionCounts))
}
}
object RepartitionStrategy {
val SHUFFLE: Int = 0
val COALESCE: Int = 1
val NAIVE_COALESCE: Int = 2
}
case class TableRepartition(child: TableIR, n: Int, strategy: Int) extends TableIR {
def typ: TableType = child.typ
lazy val rowCountUpperBound: Option[Long] = child.rowCountUpperBound
lazy val children: IndexedSeq[BaseIR] = FastIndexedSeq(child)
def copy(newChildren: IndexedSeq[BaseIR]): TableRepartition = {
val IndexedSeq(newChild: TableIR) = newChildren
TableRepartition(newChild, n, strategy)
}
protected[ir] override def execute(ctx: ExecuteContext): TableValue = {
val prev = child.execute(ctx)
val rvd = strategy match {
case RepartitionStrategy.SHUFFLE => prev.rvd.coalesce(n, shuffle = true)
case RepartitionStrategy.COALESCE => prev.rvd.coalesce(n, shuffle = false)
case RepartitionStrategy.NAIVE_COALESCE => prev.rvd.naiveCoalesce(n)
}
prev.copy(rvd = rvd)
}
}
object TableJoin {
def apply(left: TableIR, right: TableIR, joinType: String): TableJoin =
TableJoin(left, right, joinType, left.typ.key.length)
}
/**
* Suppose 'left' has key [l_1, ..., l_n] and 'right' has key [r_1, ..., r_m].
* Then [l_1, ..., l_j] and [r_1, ..., r_j] must have the same type, where
* j = 'joinKey'. TableJoin computes the join of 'left' and 'right' along this
* common prefix of their keys, returning a table with key
* [l_1, ..., l_j, l_{j+1}, ..., l_n, r_{j+1}, ..., r_m].
*
* WARNING: If 'left' has any duplicate (full) key [k_1, ..., k_n], and j < m,
* and 'right' has multiple rows with the corresponding join key
* [k_1, ..., k_j] but distinct full keys, then the resulting table will have
* out-of-order keys. To avoid this, ensure one of the following:
* * j == m
* * 'left' has distinct keys
* * 'right' has distinct join keys (length j prefix), or at least no
* distinct keys with the same join key.
*/
case class TableJoin(left: TableIR, right: TableIR, joinType: String, joinKey: Int)
extends TableIR {
require(joinKey >= 0)
require(left.typ.key.length >= joinKey)
require(right.typ.key.length >= joinKey)
require(left.typ.keyType.truncate(joinKey) isIsomorphicTo right.typ.keyType.truncate(joinKey))
require(left.typ.globalType.fieldNames.toSet
.intersect(right.typ.globalType.fieldNames.toSet)
.isEmpty)
require(joinType == "inner" ||
joinType == "left" ||
joinType == "right" ||
joinType == "outer" ||
joinType == "zip")
val children: IndexedSeq[BaseIR] = Array(left, right)
lazy val rowCountUpperBound: Option[Long] = None
private val newRowType = {
val leftRowType = left.typ.rowType
val rightRowType = right.typ.rowType
val leftKey = left.typ.key.take(joinKey)
val rightKey = right.typ.key.take(joinKey)
val leftKeyType = TableType.keyType(leftRowType, leftKey)
val leftValueType = TableType.valueType(leftRowType, leftKey)
val rightValueType = TableType.valueType(rightRowType, rightKey)
if (leftValueType.fieldNames.toSet
.intersect(rightValueType.fieldNames.toSet)
.nonEmpty)
throw new RuntimeException(s"invalid join: \n left value: $leftValueType\n right value: $rightValueType")
leftKeyType ++ leftValueType ++ rightValueType
}
private val newGlobalType = left.typ.globalType ++ right.typ.globalType
private val newKey = left.typ.key ++ right.typ.key.drop(joinKey)
val typ: TableType = TableType(newRowType, newKey, newGlobalType)
def copy(newChildren: IndexedSeq[BaseIR]): TableJoin = {
assert(newChildren.length == 2)
TableJoin(
newChildren(0).asInstanceOf[TableIR],
newChildren(1).asInstanceOf[TableIR],
joinType,
joinKey)
}
protected[ir] override def execute(ctx: ExecuteContext): TableValue = {
val leftTV = left.execute(ctx)
val rightTV = right.execute(ctx)
val newGlobals = BroadcastRow(ctx,
Row.merge(leftTV.globals.javaValue, rightTV.globals.javaValue),
newGlobalType)
val leftRVDType = leftTV.rvd.typ.copy(key = left.typ.key.take(joinKey))
val rightRVDType = rightTV.rvd.typ.copy(key = right.typ.key.take(joinKey))
val leftRowType = leftRVDType.rowType
val rightRowType = rightRVDType.rowType
val leftKeyFieldIdx = leftRVDType.kFieldIdx
val rightKeyFieldIdx = rightRVDType.kFieldIdx
val leftValueFieldIdx = leftRVDType.valueFieldIdx
val rightValueFieldIdx = rightRVDType.valueFieldIdx
val newRowPType = PType.canonical(newRowType).asInstanceOf[PStruct]
val rvMerger = { (_: RVDContext, it: Iterator[JoinedRegionValue]) =>
val rvb = new RegionValueBuilder()
val rv = RegionValue()
it.map { joined =>
val lrv = joined._1
val rrv = joined._2
if (lrv != null)
rvb.set(lrv.region)
else {
assert(rrv != null)
rvb.set(rrv.region)
}
rvb.start(newRowPType)
rvb.startStruct()
if (lrv != null)
rvb.addFields(leftRowType, lrv, leftKeyFieldIdx)
else {
assert(rrv != null)
rvb.addFields(rightRowType, rrv, rightKeyFieldIdx)
}
if (lrv != null)
rvb.addFields(leftRowType, lrv, leftValueFieldIdx)
else
rvb.skipFields(leftValueFieldIdx.length)
if (rrv != null)
rvb.addFields(rightRowType, rrv, rightValueFieldIdx)
else
rvb.skipFields(rightValueFieldIdx.length)
rvb.endStruct()
rv.set(rvb.region, rvb.end())
rv
}
}
val joinedRVD = if (joinType == "zip") {
val leftRVD = leftTV.rvd
val rightRVD = rightTV.rvd
leftRVD.orderedZipJoin(
rightRVD,
joinKey,
rvMerger,
RVDType(newRowPType, newKey))
} else {
val leftRVD = leftTV.rvd
val rightRVD = rightTV.rvd
leftRVD.orderedJoin(
rightRVD,
joinKey,
joinType,
rvMerger,
RVDType(newRowPType, newKey))
}
TableValue(typ, newGlobals, joinedRVD)
}
}
case class TableIntervalJoin(
left: TableIR,
right: TableIR,
root: String,
product: Boolean
) extends TableIR {
lazy val children: IndexedSeq[BaseIR] = Array(left, right)
lazy val rowCountUpperBound: Option[Long] = left.rowCountUpperBound
val rightType: Type = if (product) TArray(right.typ.valueType) else right.typ.valueType
val typ: TableType = left.typ.copy(rowType = left.typ.rowType.appendKey(root, rightType))
override def copy(newChildren: IndexedSeq[BaseIR]): TableIR =
TableIntervalJoin(newChildren(0).asInstanceOf[TableIR], newChildren(1).asInstanceOf[TableIR], root, product)
override def partitionCounts: Option[IndexedSeq[Long]] = left.partitionCounts
protected[ir] override def execute(ctx: ExecuteContext): TableValue = {
val leftValue = left.execute(ctx)
val rightValue = right.execute(ctx)
val leftRVDType = leftValue.rvd.typ
val rightRVDType = rightValue.rvd.typ
val rightValueFields = rightRVDType.valueType.fieldNames
val localKey = typ.key
val localRoot = root
val newRVD =
if (product) {
val joiner = (rightPType: PStruct) => {
val (newRowPType, ins) = leftRVDType.rowType.unsafeStructInsert(PArray(rightPType.selectFields(rightValueFields)), List(localRoot))
(RVDType(newRowPType, localKey), (_: RVDContext, it: Iterator[Muple[RegionValue, Iterable[RegionValue]]]) => {
val rvb = new RegionValueBuilder()
val rv2 = RegionValue()
it.map { case Muple(rv, is) =>
rvb.set(rv.region)
rvb.start(newRowPType)
ins(
rv.region,
rv.offset,
rvb,
() => {
rvb.startArray(is.size)
is.foreach(i => rvb.selectRegionValue(rightPType, rightRVDType.valueFieldIdx, i))
rvb.endArray()
})
rv2.set(rv.region, rvb.end())
rv2
}
})
}
leftValue.rvd.orderedLeftIntervalJoin(rightValue.rvd, joiner)
} else {
val joiner = (rightPType: PStruct) => {
val (newRowPType, ins) = leftRVDType.rowType.unsafeStructInsert(rightPType.selectFields(rightValueFields), List(localRoot))
(RVDType(newRowPType, localKey), (_: RVDContext, it: Iterator[JoinedRegionValue]) => {
val rvb = new RegionValueBuilder()
val rv2 = RegionValue()
it.map { case Muple(rv, i) =>
rvb.set(rv.region)
rvb.start(newRowPType)
ins(
rv.region,
rv.offset,
rvb,
() =>
if (i == null)
rvb.setMissing()
else
rvb.selectRegionValue(rightPType, rightRVDType.valueFieldIdx, i))
rv2.set(rv.region, rvb.end())
rv2
}
})
}
leftValue.rvd.orderedLeftIntervalJoinDistinct(rightValue.rvd, joiner)
}
TableValue(typ, leftValue.globals, newRVD)
}
}
case class TableZipUnchecked(left: TableIR, right: TableIR) extends TableIR {
require((left.typ.rowType.fieldNames ++ right.typ.rowType.fieldNames).areDistinct())
require(right.typ.key.isEmpty)
lazy val rowCountUpperBound: Option[Long] = (left.rowCountUpperBound, right.rowCountUpperBound) match {
case (Some(l), Some(r)) => Some(l.min(r))
case (Some(l), None) => Some(l)
case (None, Some(r)) => Some(r)
case (None, None) => None
}
val typ: TableType = left.typ.copy(rowType = left.typ.rowType ++ right.typ.rowType)
override def partitionCounts: Option[IndexedSeq[Long]] = left.partitionCounts
lazy val children: IndexedSeq[BaseIR] = Array(left, right)
def copy(newChildren: IndexedSeq[BaseIR]): TableIR = {
val IndexedSeq(newLeft: TableIR, newRight: TableIR) = newChildren
TableZipUnchecked(newLeft, newRight)
}
override def execute(ctx: ExecuteContext): TableValue = {
val tv1 = left.execute(ctx)
val tv2 = right.execute(ctx)
val inserter = InsertFields(
Ref("left", left.typ.rowType),
right.typ.rowType.fieldNames.map(f => f -> GetField(Ref("right", right.typ.rowType), f)))
val rvdType: RVDType = RVDType(inserter.pType, tv1.rvd.typ.key)
val (t2, makeF) = ir.Compile[Long, Long, Long](
"left", tv1.rvd.typ.rowType,
"right", tv2.rvd.typ.rowType,
inserter)
assert(t2.virtualType == typ.rowType)
assert(t2 == rvdType.rowType)
val rvd = tv1.rvd.zipPartitionsWithIndex(rvdType, tv2.rvd) { (i, ctx, it1, it2) =>
val partRegion = ctx.freshRegion
val f = makeF(i, partRegion)
val region = ctx.region
val rv3 = RegionValue(region)
new Iterator[RegionValue] {
def hasNext: Boolean = {
val hn1 = it1.hasNext
val hn2 = it2.hasNext
assert(hn1 == hn2)
hn1
}
def next(): RegionValue = {
val rv1 = it1.next()
val rv2 = it2.next()
val off = f(region, rv1.offset, false, rv2.offset, false)
rv3.set(region, off)
rv3
}
}
}
TableValue(typ, tv1.globals, rvd)
}
}
case class TableMultiWayZipJoin(children: IndexedSeq[TableIR], fieldName: String, globalName: String) extends TableIR {
require(children.length > 0, "there must be at least one table as an argument")
private val first = children.head
private val rest = children.tail
lazy val rowCountUpperBound: Option[Long] = None
require(rest.forall(e => e.typ.rowType == first.typ.rowType), "all rows must have the same type")
require(rest.forall(e => e.typ.key == first.typ.key), "all keys must be the same")
require(rest.forall(e => e.typ.globalType == first.typ.globalType),
"all globals must have the same type")
private val newGlobalType = TStruct(globalName -> TArray(first.typ.globalType))
private val newValueType = TStruct(fieldName -> TArray(first.typ.valueType))
private val newRowType = first.typ.keyType ++ newValueType
lazy val typ: TableType = first.typ.copy(
rowType = newRowType,
globalType = newGlobalType
)
val rvdType: RVDType = typ.canonicalRVDType
def copy(newChildren: IndexedSeq[BaseIR]): TableMultiWayZipJoin =
TableMultiWayZipJoin(newChildren.asInstanceOf[IndexedSeq[TableIR]], fieldName, globalName)
protected[ir] override def execute(ctx: ExecuteContext): TableValue = {
val childValues = children.map(_.execute(ctx))
assert(childValues.map(_.rvd.typ).toSet.size == 1) // same physical types
val childRVDs = childValues.map(_.rvd)
val repartitionedRVDs =
if (childRVDs(0).partitioner.satisfiesAllowedOverlap(typ.key.length - 1) &&
childRVDs.forall(rvd => rvd.partitioner == childRVDs(0).partitioner))
childRVDs.map(_.truncateKey(typ.key.length))
else {
info("TableMultiWayZipJoin: repartitioning children")
val childRanges = childRVDs.flatMap(_.partitioner.rangeBounds)
val newPartitioner = RVDPartitioner.generate(childRVDs.head.typ.kType.virtualType, childRanges)
childRVDs.map(_.repartition(newPartitioner))
}
val newPartitioner = repartitionedRVDs(0).partitioner
val rvdType = repartitionedRVDs(0).typ
val rowType = rvdType.rowType
val keyIdx = rvdType.kFieldIdx
val valIdx = rvdType.valueFieldIdx
val localRVDType = rvdType
val localNewRowType = PType.canonical(newRowType).asInstanceOf[PStruct]
val localDataLength = children.length
val rvMerger = { (ctx: RVDContext, it: Iterator[ArrayBuilder[(RegionValue, Int)]]) =>
val rvb = new RegionValueBuilder()
val newRegionValue = RegionValue()
it.map { rvs =>
val rv = rvs(0)._1
rvb.set(ctx.region)
rvb.start(localNewRowType)
rvb.startStruct()
rvb.addFields(rowType, rv, keyIdx) // Add the key
rvb.startMissingArray(localDataLength) // add the values
var i = 0
while (i < rvs.length) {
val (rv, j) = rvs(i)
rvb.setArrayIndex(j)
rvb.setPresent()
rvb.startStruct()
rvb.addFields(rowType, rv, valIdx)
rvb.endStruct()
i += 1
}
rvb.endArrayUnchecked()
rvb.endStruct()
newRegionValue.set(rvb.region, rvb.end())
newRegionValue
}
}
val rvd = RVD(
typ = RVDType(localNewRowType, typ.key),
partitioner = newPartitioner,
crdd = ContextRDD.czipNPartitions(repartitionedRVDs.map(_.crdd.boundary)) { (ctx, its) =>
val orvIters = its.map(it => OrderedRVIterator(localRVDType, it, ctx))
rvMerger(ctx, OrderedRVIterator.multiZipJoin(orvIters))
})
val newGlobals = BroadcastRow(ctx,
Row(childValues.map(_.globals.javaValue)),
newGlobalType)
TableValue(typ, newGlobals, rvd)
}
}
case class TableLeftJoinRightDistinct(left: TableIR, right: TableIR, root: String) extends TableIR {
require(right.typ.keyType isPrefixOf left.typ.keyType,
s"\n L: ${ left.typ }\n R: ${ right.typ }")
lazy val rowCountUpperBound: Option[Long] = left.rowCountUpperBound
lazy val children: IndexedSeq[BaseIR] = Array(left, right)
private val newRowType = left.typ.rowType.structInsert(right.typ.valueType, List(root))._1
val typ: TableType = left.typ.copy(rowType = newRowType)
val rvdType: RVDType = typ.canonicalRVDType
override def partitionCounts: Option[IndexedSeq[Long]] = left.partitionCounts
def copy(newChildren: IndexedSeq[BaseIR]): TableLeftJoinRightDistinct = {
val IndexedSeq(newLeft: TableIR, newRight: TableIR) = newChildren
TableLeftJoinRightDistinct(newLeft, newRight, root)
}
protected[ir] override def execute(ctx: ExecuteContext): TableValue = {
val leftValue = left.execute(ctx)
val rightValue = right.execute(ctx)
val joinKey = math.min(left.typ.key.length, right.typ.key.length)
leftValue.copy(
typ = typ,
rvd = leftValue.rvd
.orderedLeftJoinDistinctAndInsert(rightValue.rvd.truncateKey(joinKey), root))
}
}
// Must leave key fields unchanged.
case class TableMapRows(child: TableIR, newRow: IR) extends TableIR {
val children: IndexedSeq[BaseIR] = Array(child, newRow)
lazy val rowCountUpperBound: Option[Long] = child.rowCountUpperBound
val typ: TableType = child.typ.copy(rowType = newRow.typ.asInstanceOf[TStruct])
def copy(newChildren: IndexedSeq[BaseIR]): TableMapRows = {
assert(newChildren.length == 2)
TableMapRows(newChildren(0).asInstanceOf[TableIR], newChildren(1).asInstanceOf[IR])
}
override def partitionCounts: Option[IndexedSeq[Long]] = child.partitionCounts
protected[ir] override def execute(ctx: ExecuteContext): TableValue = {
val tv = child.execute(ctx)
if (HailContext.getFlag("newaggs") != null) {
try {
return agg.TableMapIRNew(tv, newRow)
} catch {
case e: agg.UnsupportedExtraction =>
log.info(s"couldn't lower TableMapRows: $e")
}
}
val gType = tv.globals.t
var scanInitNeedsGlobals = false
var scanSeqNeedsGlobals = false
var rowIterationNeedsGlobals = false
val (scanAggs, scanInitOps, scanSeqOps, scanResultType, postScanIR) = ir.CompileWithAggregators[Long, Long, Long](
"global", gType,
"global", gType,
"row", tv.rvd.rowPType,
CompileWithAggregators.liftScan(newRow), "SCANR", { (nAggs: Int, initOp: IR) =>
scanInitNeedsGlobals |= Mentions(initOp, "global")
initOp
}, { (nAggs: Int, seqOp: IR) =>
scanSeqNeedsGlobals |= Mentions(seqOp, "global")
seqOp
})
val (rTyp, f) = ir.Compile[Long, Long, Long, Long](
"global", tv.globals.t,
"row", tv.rvd.rowPType,
"SCANR", scanResultType,
postScanIR)
assert(rTyp.virtualType == typ.rowType)
rowIterationNeedsGlobals |= Mentions(postScanIR, "global")