/
AlignmentRecordRDD.scala
1525 lines (1363 loc) · 54.8 KB
/
AlignmentRecordRDD.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
/**
* Licensed to Big Data Genomics (BDG) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The BDG licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.bdgenomics.adam.rdd.read
import htsjdk.samtools._
import htsjdk.samtools.cram.ref.ReferenceSource
import htsjdk.samtools.util.{ BinaryCodec, BlockCompressedOutputStream }
import java.io.{ OutputStream, StringWriter, Writer }
import java.net.URI
import java.nio.file.Paths
import org.apache.hadoop.fs.Path
import org.apache.hadoop.io.LongWritable
import org.apache.parquet.hadoop.metadata.CompressionCodecName
import org.apache.spark.SparkContext
import org.apache.spark.api.java.JavaRDD
import org.apache.spark.broadcast.Broadcast
import org.apache.spark.rdd.MetricsContext._
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.{ Dataset, Row, SQLContext }
import org.apache.spark.storage.StorageLevel
import org.bdgenomics.adam.algorithms.consensus.{
ConsensusGenerator,
ConsensusGeneratorFromReads,
NormalizationUtils
}
import org.bdgenomics.adam.converters.AlignmentRecordConverter
import org.bdgenomics.adam.instrumentation.Timers._
import org.bdgenomics.adam.models._
import org.bdgenomics.adam.rdd.ADAMContext._
import org.bdgenomics.adam.rdd.{
AvroRecordGroupGenomicDataset,
ADAMSaveAnyArgs,
JavaSaveArgs,
SAMHeaderWriter
}
import org.bdgenomics.adam.rdd.feature.{
CoverageRDD,
DatasetBoundCoverageRDD,
RDDBoundCoverageRDD
}
import org.bdgenomics.adam.rdd.read.realignment.RealignIndels
import org.bdgenomics.adam.rdd.read.recalibration.BaseQualityRecalibration
import org.bdgenomics.adam.rdd.fragment.FragmentRDD
import org.bdgenomics.adam.rdd.variant.VariantRDD
import org.bdgenomics.adam.sql.{ AlignmentRecord => AlignmentRecordProduct }
import org.bdgenomics.adam.serialization.AvroSerializer
import org.bdgenomics.adam.util.{ FileMerger, ReferenceFile }
import org.bdgenomics.formats.avro._
import org.bdgenomics.utils.interval.array.{
IntervalArray,
IntervalArraySerializer
}
import org.seqdoop.hadoop_bam._
import scala.collection.JavaConversions._
import scala.language.implicitConversions
import scala.math.{ abs, min }
import scala.reflect.ClassTag
import scala.reflect.runtime.universe._
private[adam] case class AlignmentRecordArray(
array: Array[(ReferenceRegion, AlignmentRecord)],
maxIntervalWidth: Long) extends IntervalArray[ReferenceRegion, AlignmentRecord] {
def duplicate(): IntervalArray[ReferenceRegion, AlignmentRecord] = {
copy()
}
protected def replace(arr: Array[(ReferenceRegion, AlignmentRecord)],
maxWidth: Long): IntervalArray[ReferenceRegion, AlignmentRecord] = {
AlignmentRecordArray(arr, maxWidth)
}
}
private[adam] class AlignmentRecordArraySerializer extends IntervalArraySerializer[ReferenceRegion, AlignmentRecord, AlignmentRecordArray] {
protected val kSerializer = new ReferenceRegionSerializer
protected val tSerializer = new AvroSerializer[AlignmentRecord]
protected def builder(arr: Array[(ReferenceRegion, AlignmentRecord)],
maxIntervalWidth: Long): AlignmentRecordArray = {
AlignmentRecordArray(arr, maxIntervalWidth)
}
}
object AlignmentRecordRDD extends Serializable {
/**
* Hadoop configuration path to check for a boolean value indicating whether
* the current or original read qualities should be written. True indicates
* to write the original qualities. The default is false.
*/
val WRITE_ORIGINAL_QUALITIES = "org.bdgenomics.adam.rdd.read.AlignmentRecordRDD.writeOriginalQualities"
/**
* Hadoop configuration path to check for a boolean value indicating whether
* to write the "/1" "/2" suffixes to the read name that indicate whether a
* read is first or second in a pair. Default is false (no suffixes).
*/
val WRITE_SUFFIXES = "org.bdgenomics.adam.rdd.read.AlignmentRecordRDD.writeSuffixes"
/**
* Converts a processing step back to the SAM representation.
*
* @param ps The processing step to convert.
* @return Returns an HTSJDK program group.
*/
private[adam] def processingStepToSam(
ps: ProcessingStep): SAMProgramRecord = {
require(ps.getId != null,
"Processing stage ID cannot be null (%s).".format(ps))
val pg = new SAMProgramRecord(ps.getId)
Option(ps.getPreviousId).foreach(pg.setPreviousProgramGroupId(_))
Option(ps.getProgramName).foreach(pg.setProgramName)
Option(ps.getVersion).foreach(pg.setProgramVersion)
Option(ps.getCommandLine).foreach(pg.setCommandLine)
pg
}
/**
* Builds an AlignmentRecordRDD for unaligned reads.
*
* @param rdd The underlying AlignmentRecord RDD.
* @return A new AlignmentRecordRDD.
*/
def unaligned(rdd: RDD[AlignmentRecord]): AlignmentRecordRDD = {
RDDBoundAlignmentRecordRDD(rdd,
SequenceDictionary.empty,
RecordGroupDictionary.empty,
Seq.empty,
None)
}
/**
* Validates that there are no gaps in a set of quality score bins.
*
* @param bins Bins to validate.
*
* @throws IllegalArgumentException Throws exception if the bins are empty,
* there is a gap between bins, or two bins overlap.
*/
private[rdd] def validateBins(bins: Seq[QualityScoreBin]) {
require(bins.nonEmpty, "Bins cannot be empty.")
// if we have multiple bins, validate them
// - check that we don't have gaps between bins
// - check that we don't have overlapping bins
if (bins.size > 1) {
val sortedBins = bins.sortBy(_.low)
(0 until (sortedBins.size - 1)).foreach(idx => {
if (sortedBins(idx).high < sortedBins(idx + 1).low) {
throw new IllegalArgumentException("Gap between bins %s and %s (all bins: %s).".format(
sortedBins(idx), sortedBins(idx + 1), bins.mkString(",")))
} else if (sortedBins(idx).high > sortedBins(idx + 1).low) {
throw new IllegalArgumentException("Bins %s and %s overlap (all bins: %s).".format(
sortedBins(idx), sortedBins(idx + 1), bins.mkString(",")))
}
})
}
}
/**
* Builds an AlignmentRecordRDD without a partition map.
*
* @param rdd The underlying AlignmentRecord RDD.
* @param sequences The sequence dictionary for the RDD.
* @param recordGroups The record group dictionary for the RDD.
* @return A new AlignmentRecordRDD.
*/
def apply(rdd: RDD[AlignmentRecord],
sequences: SequenceDictionary,
recordGroups: RecordGroupDictionary,
processingSteps: Seq[ProcessingStep]): AlignmentRecordRDD = {
RDDBoundAlignmentRecordRDD(rdd,
sequences,
recordGroups,
processingSteps,
None)
}
def apply(ds: Dataset[AlignmentRecordProduct],
sequences: SequenceDictionary,
recordGroups: RecordGroupDictionary,
processingSteps: Seq[ProcessingStep]): AlignmentRecordRDD = {
DatasetBoundAlignmentRecordRDD(ds,
sequences,
recordGroups,
processingSteps)
}
}
case class ParquetUnboundAlignmentRecordRDD private[rdd] (
@transient private val sc: SparkContext,
private val parquetFilename: String,
sequences: SequenceDictionary,
recordGroups: RecordGroupDictionary,
@transient val processingSteps: Seq[ProcessingStep]) extends AlignmentRecordRDD {
lazy val optPartitionMap = sc.extractPartitionMap(parquetFilename)
lazy val rdd: RDD[AlignmentRecord] = {
sc.loadParquet(parquetFilename)
}
lazy val dataset = {
val sqlContext = SQLContext.getOrCreate(sc)
import sqlContext.implicits._
sqlContext.read.parquet(parquetFilename).as[AlignmentRecordProduct]
}
def replaceSequences(
newSequences: SequenceDictionary): AlignmentRecordRDD = {
copy(sequences = newSequences)
}
def replaceRecordGroups(
newRecordGroups: RecordGroupDictionary): AlignmentRecordRDD = {
copy(recordGroups = newRecordGroups)
}
def replaceProcessingSteps(
newProcessingSteps: Seq[ProcessingStep]): AlignmentRecordRDD = {
copy(processingSteps = newProcessingSteps)
}
}
case class DatasetBoundAlignmentRecordRDD private[rdd] (
dataset: Dataset[AlignmentRecordProduct],
sequences: SequenceDictionary,
recordGroups: RecordGroupDictionary,
@transient val processingSteps: Seq[ProcessingStep]) extends AlignmentRecordRDD {
lazy val rdd = dataset.rdd.map(_.toAvro)
protected lazy val optPartitionMap = None
override def saveAsParquet(filePath: String,
blockSize: Int = 128 * 1024 * 1024,
pageSize: Int = 1 * 1024 * 1024,
compressCodec: CompressionCodecName = CompressionCodecName.GZIP,
disableDictionaryEncoding: Boolean = false) {
log.warn("Saving directly as Parquet from SQL. Options other than compression codec are ignored.")
dataset.toDF()
.write
.format("parquet")
.option("spark.sql.parquet.compression.codec", compressCodec.toString.toLowerCase())
.save(filePath)
saveMetadata(filePath)
}
override def transformDataset(
tFn: Dataset[AlignmentRecordProduct] => Dataset[AlignmentRecordProduct]): AlignmentRecordRDD = {
copy(dataset = tFn(dataset))
}
def replaceSequences(
newSequences: SequenceDictionary): AlignmentRecordRDD = {
copy(sequences = newSequences)
}
def replaceRecordGroups(
newRecordGroups: RecordGroupDictionary): AlignmentRecordRDD = {
copy(recordGroups = newRecordGroups)
}
def replaceProcessingSteps(
newProcessingSteps: Seq[ProcessingStep]): AlignmentRecordRDD = {
copy(processingSteps = newProcessingSteps)
}
}
case class RDDBoundAlignmentRecordRDD private[rdd] (
rdd: RDD[AlignmentRecord],
sequences: SequenceDictionary,
recordGroups: RecordGroupDictionary,
@transient val processingSteps: Seq[ProcessingStep],
optPartitionMap: Option[Array[Option[(ReferenceRegion, ReferenceRegion)]]]) extends AlignmentRecordRDD {
/**
* A SQL Dataset of reads.
*/
lazy val dataset: Dataset[AlignmentRecordProduct] = {
val sqlContext = SQLContext.getOrCreate(rdd.context)
import sqlContext.implicits._
sqlContext.createDataset(rdd.map(AlignmentRecordProduct.fromAvro))
}
override def toCoverage(): CoverageRDD = {
val covCounts =
rdd.filter(r => {
val readMapped = r.getReadMapped
// validate alignment fields
if (readMapped) {
require(r.getStart != null && r.getEnd != null && r.getContigName != null,
"Read was mapped but was missing alignment start/end/contig (%s).".format(r))
}
readMapped
}).flatMap(r => {
val positions: List[Long] = List.range(r.getStart, r.getEnd)
positions.map(n => (ReferencePosition(r.getContigName, n), 1))
}).reduceByKey(_ + _)
.map(r => Coverage(r._1, r._2.toDouble))
RDDBoundCoverageRDD(covCounts, sequences, None)
}
def replaceSequences(
newSequences: SequenceDictionary): AlignmentRecordRDD = {
copy(sequences = newSequences)
}
def replaceRecordGroups(
newRecordGroups: RecordGroupDictionary): AlignmentRecordRDD = {
copy(recordGroups = newRecordGroups)
}
def replaceProcessingSteps(
newProcessingSteps: Seq[ProcessingStep]): AlignmentRecordRDD = {
copy(processingSteps = newProcessingSteps)
}
}
private case class AlignmentWindow(contigName: String, start: Long, end: Long) {
}
sealed abstract class AlignmentRecordRDD extends AvroRecordGroupGenomicDataset[AlignmentRecord, AlignmentRecordProduct, AlignmentRecordRDD] {
protected val productFn = AlignmentRecordProduct.fromAvro(_)
protected val unproductFn = (a: AlignmentRecordProduct) => a.toAvro
@transient val uTag: TypeTag[AlignmentRecordProduct] = typeTag[AlignmentRecordProduct]
/**
* Applies a function that transforms the underlying RDD into a new RDD using
* the Spark SQL API.
*
* @param tFn A function that transforms the underlying RDD as a Dataset.
* @return A new RDD where the RDD of genomic data has been replaced, but the
* metadata (sequence dictionary, and etc) is copied without modification.
*/
def transformDataset(
tFn: Dataset[AlignmentRecordProduct] => Dataset[AlignmentRecordProduct]): AlignmentRecordRDD = {
DatasetBoundAlignmentRecordRDD(dataset,
sequences,
recordGroups,
processingSteps)
.transformDataset(tFn)
}
/**
* Replaces the underlying RDD and SequenceDictionary and emits a new object.
*
* @param newRdd New RDD to replace current RDD.
* @param newSequences New sequence dictionary to replace current dictionary.
* @return Returns a new AlignmentRecordRDD.
*/
protected def replaceRddAndSequences(newRdd: RDD[AlignmentRecord],
newSequences: SequenceDictionary,
partitionMap: Option[Array[Option[(ReferenceRegion, ReferenceRegion)]]] = None): AlignmentRecordRDD = {
RDDBoundAlignmentRecordRDD(newRdd,
newSequences,
recordGroups,
processingSteps,
partitionMap)
}
protected def replaceRdd(newRdd: RDD[AlignmentRecord],
newPartitionMap: Option[Array[Option[(ReferenceRegion, ReferenceRegion)]]] = None): AlignmentRecordRDD = {
RDDBoundAlignmentRecordRDD(newRdd,
sequences,
recordGroups,
processingSteps,
newPartitionMap)
}
protected def buildTree(rdd: RDD[(ReferenceRegion, AlignmentRecord)])(
implicit tTag: ClassTag[AlignmentRecord]): IntervalArray[ReferenceRegion, AlignmentRecord] = {
IntervalArray(rdd, AlignmentRecordArray.apply(_, _))
}
def union(rdds: AlignmentRecordRDD*): AlignmentRecordRDD = {
val iterableRdds = rdds.toSeq
AlignmentRecordRDD(rdd.context.union(rdd, iterableRdds.map(_.rdd): _*),
iterableRdds.map(_.sequences).fold(sequences)(_ ++ _),
iterableRdds.map(_.recordGroups).fold(recordGroups)(_ ++ _),
iterableRdds.map(_.processingSteps).fold(processingSteps)(_ ++ _))
}
/**
* Convert this set of reads into fragments.
*
* @return Returns a FragmentRDD where all reads have been grouped together by
* the original sequence fragment they come from.
*/
def toFragments(): FragmentRDD = {
FragmentRDD(groupReadsByFragment().map(_.toFragment),
sequences,
recordGroups,
processingSteps)
}
/**
* Groups all reads by record group and read name.
*
* @return SingleReadBuckets with primary, secondary and unmapped reads
*/
private def locallyGroupReadsByFragment(): RDD[SingleReadBucket] = {
SingleReadBucket.fromQuerynameSorted(rdd)
}
/**
* Convert this set of reads into fragments.
*
* Assumes that reads are sorted by readname.
* *
*
* @return Returns a FragmentRDD where all reads have been grouped together by
* the original sequence fragment they come from.
*/
private[rdd] def querynameSortedToFragments: FragmentRDD = {
FragmentRDD(locallyGroupReadsByFragment().map(_.toFragment),
sequences,
recordGroups,
processingSteps)
}
/**
* Converts this set of reads into a corresponding CoverageRDD.
*
* @return CoverageRDD containing mapped RDD of Coverage.
*/
def toCoverage(): CoverageRDD = {
import dataset.sqlContext.implicits._
val covCounts = dataset.toDF
.where($"readMapped")
.select($"contigName", $"start", $"end")
.as[AlignmentWindow]
.flatMap(w => {
val width = (w.end - w.start).toInt
val buffer = new Array[Coverage](width)
var idx = 0
var pos = w.start
while (idx < width) {
val lastPos = pos
pos += 1L
buffer(idx) = Coverage(w.contigName, lastPos, pos, 1.0)
idx += 1
}
buffer
}).toDF
.groupBy("contigName", "start", "end")
.sum("count")
.withColumnRenamed("sum(count)", "count")
.as[Coverage]
DatasetBoundCoverageRDD(covCounts, sequences)
}
/**
* Returns all reference regions that overlap this read.
*
* If a read is unaligned, it covers no reference region. If a read is aligned
* we expect it to cover a single region. A chimeric read would cover multiple
* regions, but we store chimeric reads in a way similar to BAM, where the
* split alignments are stored in multiple separate reads.
*
* @param elem Read to produce regions for.
* @return The seq of reference regions this read covers.
*/
protected def getReferenceRegions(elem: AlignmentRecord): Seq[ReferenceRegion] = {
ReferenceRegion.opt(elem).toSeq
}
/**
* Saves this RDD as BAM, CRAM, or SAM if the extension provided is .sam, .cram,
* or .bam.
*
* @param args Arguments defining where to save the file.
* @param isSorted True if input data is sorted. Sets the ordering in the SAM
* file header.
* @return Returns true if the extension in args ended in .sam/.bam and the
* file was saved.
*/
private[rdd] def maybeSaveBam(args: ADAMSaveAnyArgs,
isSorted: Boolean = false): Boolean = {
if (args.outputPath.endsWith(".sam") ||
args.outputPath.endsWith(".bam") ||
args.outputPath.endsWith(".cram")) {
log.info("Saving data in SAM/BAM/CRAM format")
saveAsSam(
args.outputPath,
isSorted = isSorted,
asSingleFile = args.asSingleFile,
deferMerging = args.deferMerging,
disableFastConcat = args.disableFastConcat
)
true
} else {
false
}
}
/**
* Saves the RDD as FASTQ if the file has the proper extension.
*
* @param args Save arguments defining the file path to save at.
* @return True if the file extension ended in ".fq" or ".fastq" and the file
* was saved as FASTQ, or if the file extension ended in ".ifq" and the file
* was saved as interleaved FASTQ.
*/
private[rdd] def maybeSaveFastq(args: ADAMSaveAnyArgs): Boolean = {
if (args.outputPath.endsWith(".fq") || args.outputPath.endsWith(".fastq") ||
args.outputPath.endsWith(".ifq")) {
saveAsFastq(args.outputPath,
sort = args.sortFastqOutput,
asSingleFile = args.asSingleFile,
disableFastConcat = args.disableFastConcat
)
true
} else
false
}
/**
* Saves AlignmentRecords as a directory of Parquet files or as SAM/BAM.
*
* This method infers the output format from the file extension. Filenames
* ending in .sam/.bam are saved as SAM/BAM, and all other files are saved
* as Parquet.
*
* @param args Save configuration arguments.
* @param isSorted If the output is sorted, this will modify the SAM/BAM header.
* @return Returns true if saving succeeded.
*/
def save(args: ADAMSaveAnyArgs,
isSorted: Boolean = false): Boolean = {
(maybeSaveBam(args, isSorted) ||
maybeSaveFastq(args) ||
{ saveAsParquet(args); true })
}
/**
* Saves this RDD to disk, with the type identified by the extension.
*
* @param filePath Path to save the file at.
* @param isSorted Whether the file is sorted or not.
* @return Returns true if saving succeeded.
*/
def save(filePath: java.lang.String,
isSorted: java.lang.Boolean): java.lang.Boolean = {
save(new JavaSaveArgs(filePath), isSorted)
}
/**
* Converts an RDD into the SAM spec string it represents.
*
* This method converts an RDD of AlignmentRecords back to an RDD of
* SAMRecordWritables and a SAMFileHeader, and then maps this RDD into a
* string on the driver that represents this file in SAM.
*
* @return A string on the driver representing this RDD of reads in SAM format.
*/
def saveAsSamString(): String = {
// convert the records
val (convertRecords: RDD[SAMRecordWritable], header: SAMFileHeader) = convertToSam()
// collect the records to the driver
val records = convertRecords.collect()
// get a header writing codec
val samHeaderCodec = new SAMTextHeaderCodec
samHeaderCodec.setValidationStringency(ValidationStringency.SILENT)
// create a stringwriter and write the header to it
val samStringWriter = new StringWriter()
samHeaderCodec.encode(samStringWriter, header)
// create a sam text writer
val samWriter: SAMTextWriter = new SAMTextWriter(samStringWriter)
// write all records to the writer
records.foreach(record => samWriter.writeAlignment(record.get))
// return the writer as a string
samStringWriter.toString
}
/**
* Converts an RDD of ADAM read records into SAM records.
*
* @return Returns a SAM/BAM formatted RDD of reads, as well as the file header.
*/
def convertToSam(isSorted: Boolean = false): (RDD[SAMRecordWritable], SAMFileHeader) = ConvertToSAM.time {
// create conversion object
val adamRecordConverter = new AlignmentRecordConverter
// create header and set sort order if needed
val header = adamRecordConverter.createSAMHeader(sequences, recordGroups)
if (isSorted) {
header.setSortOrder(SAMFileHeader.SortOrder.coordinate)
} else {
header.setSortOrder(SAMFileHeader.SortOrder.unsorted)
}
// get program records and attach to header
val pgRecords = processingSteps.map(r => {
AlignmentRecordRDD.processingStepToSam(r)
})
header.setProgramRecords(pgRecords)
// broadcast for efficiency
val hdrBcast = rdd.context.broadcast(SAMFileHeaderWritable(header))
// map across RDD to perform conversion
val convertedRDD: RDD[SAMRecordWritable] = rdd.map(r => {
// must wrap record for serializability
val srw = new SAMRecordWritable()
srw.set(adamRecordConverter.convert(r, hdrBcast.value, recordGroups))
srw
})
(convertedRDD, header)
}
/**
* Cuts reads into _k_-mers, and then counts the number of occurrences of each _k_-mer.
*
* Java friendly variant.
*
* @param kmerLength The value of _k_ to use for cutting _k_-mers.
* @return Returns an RDD containing k-mer/count pairs.
*/
def countKmers(kmerLength: java.lang.Integer): JavaRDD[(String, java.lang.Long)] = {
val k: Int = kmerLength
countKmers(k).map(kv => {
val (k, v) = kv
(k, v: java.lang.Long)
}).toJavaRDD()
}
/**
* Cuts reads into _k_-mers, and then counts the number of occurrences of each _k_-mer.
*
* @param kmerLength The value of _k_ to use for cutting _k_-mers.
* @return Returns an RDD containing k-mer/count pairs.
*/
def countKmers(kmerLength: Int): RDD[(String, Long)] = {
rdd.flatMap(r => {
// cut each read into k-mers, and attach a count of 1L
r.getSequence
.sliding(kmerLength)
.map(k => (k, 1L))
}).reduceByKey((k1: Long, k2: Long) => k1 + k2)
}
/**
* Cuts reads into _k_-mers, and then counts the number of occurrences of each _k_-mer.
*
* @param kmerLength The value of _k_ to use for cutting _k_-mers.
* @return Returns a Dataset containing k-mer/count pairs.
*/
def countKmersAsDataset(kmerLength: java.lang.Integer): Dataset[(String, Long)] = {
import dataset.sqlContext.implicits._
val kmers = dataset.select($"sequence".as[String])
.flatMap(_.sliding(kmerLength))
.as[String]
kmers.toDF()
.groupBy($"value")
.count()
.select($"value".as("kmer"), $"count".as("count"))
.as[(String, Long)]
}
/**
* Saves an RDD of ADAM read data into the SAM/BAM format.
*
* @param filePath Path to save files to.
* @param asType Selects whether to save as SAM, BAM, or CRAM. The default
* value is None, which means the file type is inferred from the extension.
* @param asSingleFile If true, saves output as a single file.
* @param isSorted If the output is sorted, this will modify the header.
* @param deferMerging If true and asSingleFile is true, we will save the
* output shards as a headerless file, but we will not merge the shards.
* @param disableFastConcat If asSingleFile is true and deferMerging is false,
* disables the use of the parallel file merging engine.
*/
def saveAsSam(
filePath: String,
asType: Option[SAMFormat] = None,
asSingleFile: Boolean = false,
isSorted: Boolean = false,
deferMerging: Boolean = false,
disableFastConcat: Boolean = false): Unit = SAMSave.time {
val fileType = asType.getOrElse(SAMFormat.inferFromFilePath(filePath))
// convert the records
val (convertRecords: RDD[SAMRecordWritable], header: SAMFileHeader) =
convertToSam(isSorted)
// add keys to our records
val withKey = convertRecords.keyBy(v => new LongWritable(v.get.getAlignmentStart))
// write file to disk
val conf = rdd.context.hadoopConfiguration
// get file system
val headPath = new Path(filePath + "_head")
val tailPath = new Path(filePath + "_tail")
val outputPath = new Path(filePath)
val fs = headPath.getFileSystem(rdd.context.hadoopConfiguration)
// TIL: sam and bam are written in completely different ways!
if (fileType == SAMFormat.SAM) {
SAMHeaderWriter.writeHeader(fs, headPath, header)
} else if (fileType == SAMFormat.BAM) {
// get an output stream
val os = fs.create(headPath)
.asInstanceOf[OutputStream]
// create htsjdk specific streams for writing the bam header
val compressedOut: OutputStream = new BlockCompressedOutputStream(os, null)
val binaryCodec = new BinaryCodec(compressedOut)
// write a bam header - cribbed from Hadoop-BAM
binaryCodec.writeBytes("BAM\001".getBytes())
val sw: Writer = new StringWriter()
new SAMTextHeaderCodec().encode(sw, header)
binaryCodec.writeString(sw.toString, true, false)
// write sequence dictionary
val ssd = header.getSequenceDictionary
binaryCodec.writeInt(ssd.size())
ssd.getSequences
.toList
.foreach(r => {
binaryCodec.writeString(r.getSequenceName(), true, true)
binaryCodec.writeInt(r.getSequenceLength())
})
// flush and close all the streams
compressedOut.flush()
os.flush()
os.close()
} else {
// from https://samtools.github.io/hts-specs/CRAMv3.pdf
// cram has a variety of addtional constraints:
//
// * file definition has 20 byte identifier field
// * header must have SO:pos
// * sequence records must have attached MD5s (we don't support
// embedding reference sequences)
//
// we'll defer the writing to the cram container stream writer, and will
// do validation here
require(isSorted, "To save as CRAM, input must be sorted.")
require(sequences.records.forall(_.md5.isDefined),
"To save as CRAM, all sequences must have an attached MD5. See %s".format(
sequences))
val refSource = conf.get(CRAMInputFormat.REFERENCE_SOURCE_PATH_PROPERTY)
require(refSource != null,
"To save as CRAM, the reference source must be set in your config as %s.".format(
CRAMInputFormat.REFERENCE_SOURCE_PATH_PROPERTY))
// get an output stream
val os = fs.create(headPath)
.asInstanceOf[OutputStream]
// create a cram container writer
val csw = new CRAMContainerStreamWriter(os, null, // null -> do not write index
new ReferenceSource(Paths.get(URI.create(refSource))),
header,
filePath) // write filepath as id
// write the header
csw.writeHeader(header)
// finish the cram container, but don't write EOF
csw.finish(false)
// flush and close the output stream
os.flush()
os.close()
}
// set path to header file
conf.set("org.bdgenomics.adam.rdd.read.bam_header_path", headPath.toString)
if (!asSingleFile) {
val headeredOutputFormat = fileType match {
case SAMFormat.SAM => classOf[InstrumentedADAMSAMOutputFormat[LongWritable]]
case SAMFormat.BAM => classOf[InstrumentedADAMBAMOutputFormat[LongWritable]]
case SAMFormat.CRAM => classOf[InstrumentedADAMCRAMOutputFormat[LongWritable]]
}
withKey.saveAsNewAPIHadoopFile(
filePath,
classOf[LongWritable],
classOf[SAMRecordWritable],
headeredOutputFormat,
conf
)
// clean up the header after writing
fs.delete(headPath, true)
} else {
log.info(s"Writing single ${fileType} file (not Hadoop-style directory)")
val tailPath = new Path(filePath + "_tail")
val outputPath = new Path(filePath)
// set up output format
val headerLessOutputFormat = fileType match {
case SAMFormat.SAM => classOf[InstrumentedADAMSAMOutputFormatHeaderLess[LongWritable]]
case SAMFormat.BAM => classOf[InstrumentedADAMBAMOutputFormatHeaderLess[LongWritable]]
case SAMFormat.CRAM => classOf[InstrumentedADAMCRAMOutputFormatHeaderLess[LongWritable]]
}
// save rdd
withKey.saveAsNewAPIHadoopFile(
tailPath.toString,
classOf[LongWritable],
classOf[SAMRecordWritable],
headerLessOutputFormat,
conf
)
if (!deferMerging) {
FileMerger.mergeFiles(rdd.context,
fs,
outputPath,
tailPath,
optHeaderPath = Some(headPath),
writeEmptyGzipBlock = (fileType == SAMFormat.BAM),
writeCramEOF = (fileType == SAMFormat.CRAM),
disableFastConcat = disableFastConcat)
}
}
}
/**
* Saves this RDD to disk as a SAM/BAM/CRAM file.
*
* @param filePath Path to save the file at.
* @param asType The SAMFormat to save as. If left null, we will infer the
* format from the file extension.
* @param asSingleFile If true, saves output as a single file.
* @param isSorted If the output is sorted, this will modify the header.
*/
def saveAsSam(
filePath: java.lang.String,
asType: SAMFormat,
asSingleFile: java.lang.Boolean,
isSorted: java.lang.Boolean) {
saveAsSam(filePath,
asType = Option(asType),
asSingleFile = asSingleFile,
isSorted = isSorted)
}
/**
* Sorts our read data by reference positions, with contigs ordered by name.
*
* Sorts reads by the location where they are aligned. Unaligned reads are
* put at the end and sorted by read name. Contigs are ordered
* lexicographically.
*
* @return Returns a new RDD containing sorted reads.
*
* @see sortReadsByReferencePositionAndIndex
*/
def sortReadsByReferencePosition(): AlignmentRecordRDD = SortReads.time {
log.info("Sorting reads by reference position")
// NOTE: In order to keep unmapped reads from swamping a single partition
// we sort the unmapped reads by read name. We prefix with tildes ("~";
// ASCII 126) to ensure that the read name is lexicographically "after" the
// contig names.
replaceRddAndSequences(rdd.sortBy(r => {
if (r.getReadMapped) {
ReferencePosition(r)
} else {
ReferencePosition(s"~~~${r.getReadName}", 0)
}
}), sequences.stripIndices.sorted)
}
/**
* Sorts our read data by reference positions, with contigs ordered by index.
*
* Sorts reads by the location where they are aligned. Unaligned reads are
* put at the end and sorted by read name. Contigs are ordered by index
* that they are ordered in the SequenceDictionary.
*
* @return Returns a new RDD containing sorted reads.
*
* @see sortReadsByReferencePosition
*/
def sortReadsByReferencePositionAndIndex(): AlignmentRecordRDD = SortByIndex.time {
log.info("Sorting reads by reference index, using %s.".format(sequences))
import scala.math.Ordering.{ Int => ImplicitIntOrdering, _ }
// NOTE: In order to keep unmapped reads from swamping a single partition
// we sort the unmapped reads by read name. To do this, we hash the sequence name
// and add the max contig index
val maxContigIndex = sequences.records.flatMap(_.referenceIndex).max
replaceRdd(rdd.sortBy(r => {
if (r.getReadMapped) {
val sr = sequences(r.getContigName)
require(sr.isDefined, "Read %s has contig name %s not in dictionary %s.".format(
r, r.getContigName, sequences))
require(sr.get.referenceIndex.isDefined,
"Contig %s from sequence dictionary lacks an index.".format(sr))
(sr.get.referenceIndex.get, r.getStart: Long)
} else {
val readHash = abs(r.getReadName.hashCode + maxContigIndex)
val idx = if (readHash > maxContigIndex) readHash else Int.MaxValue
(idx, 0L)
}
}))
}
/**
* Marks reads as possible fragment duplicates.
*
* @return A new RDD where reads have the duplicate read flag set. Duplicate
* reads are NOT filtered out.
*/
def markDuplicates(): AlignmentRecordRDD = MarkDuplicatesInDriver.time {
replaceRdd(MarkDuplicates(this))
}
/**
* Runs base quality score recalibration on a set of reads. Uses a table of
* known SNPs to mask true variation during the recalibration process.
*
* Java friendly variant.
*
* @param knownSnps A table of known SNPs to mask valid variants.
* @param minAcceptableQuality The minimum quality score to recalibrate.
* @param storageLevel An optional storage level to set for the output
* of the first stage of BQSR. Set to null to omit.
* @return Returns an RDD of recalibrated reads.
*/
def recalibrateBaseQualities(
knownSnps: VariantRDD,
minAcceptableQuality: java.lang.Integer,
storageLevel: StorageLevel): AlignmentRecordRDD = {
val snpTable = SnpTable(knownSnps)
val bcastSnps = rdd.context.broadcast(snpTable)
val sMinQual: Int = minAcceptableQuality
recalibrateBaseQualities(bcastSnps,
minAcceptableQuality = sMinQual,
optStorageLevel = Option(storageLevel))
}
/**
* Runs base quality score recalibration on a set of reads. Uses a table of
* known SNPs to mask true variation during the recalibration process.
*
* @param knownSnps A table of known SNPs to mask valid variants.
* @param minAcceptableQuality The minimum quality score to recalibrate.
* @param optStorageLevel An optional storage level to set for the output
* of the first stage of BQSR. Defaults to StorageLevel.MEMORY_ONLY.
* @return Returns an RDD of recalibrated reads.
*/
def recalibrateBaseQualities(
knownSnps: Broadcast[SnpTable],
minAcceptableQuality: Int = 5,
optStorageLevel: Option[StorageLevel] = Some(StorageLevel.MEMORY_ONLY)): AlignmentRecordRDD = BQSRInDriver.time {
replaceRdd(BaseQualityRecalibration(rdd,
knownSnps,
recordGroups,
minAcceptableQuality,
optStorageLevel))
}