VcfFilter.scala 7.82 KB
Newer Older
Peter van 't Hof's avatar
Peter van 't Hof committed
1
package nl.lumc.sasc.biopet.tools
Peter van 't Hof's avatar
Peter van 't Hof committed
2
3
4

import htsjdk.variant.variantcontext.writer.AsyncVariantContextWriter
import htsjdk.variant.variantcontext.writer.VariantContextWriterBuilder
5
6
import htsjdk.variant.vcf.{ VCFHeader, VCFFileReader }
import htsjdk.variant.variantcontext.VariantContext
Peter van 't Hof's avatar
Peter van 't Hof committed
7
import java.io.File
Peter van 't Hof's avatar
Peter van 't Hof committed
8
import java.util.ArrayList
Peter van 't Hof's avatar
Peter van 't Hof committed
9
import nl.lumc.sasc.biopet.core.BiopetJavaCommandLineFunction
Peter van 't Hof's avatar
Peter van 't Hof committed
10
import nl.lumc.sasc.biopet.core.ToolCommand
Peter van 't Hof's avatar
Peter van 't Hof committed
11
12
13
14
15
16
17
18
19
import nl.lumc.sasc.biopet.core.config.Configurable
import org.broadinstitute.gatk.utils.commandline.{ Output, Input }
import scala.collection.JavaConversions._

class VcfFilter(val root: Configurable) extends BiopetJavaCommandLineFunction {
  javaMainClass = getClass.getName

  @Input(doc = "Input vcf", shortName = "I", required = true)
  var inputVcf: File = _
Peter van 't Hof's avatar
Peter van 't Hof committed
20

Peter van 't Hof's avatar
Peter van 't Hof committed
21
22
  @Output(doc = "Output vcf", shortName = "o", required = false)
  var outputVcf: File = _
Peter van 't Hof's avatar
Peter van 't Hof committed
23

Peter van 't Hof's avatar
Peter van 't Hof committed
24
25
26
27
  var minSampleDepth: Option[Int] = _
  var minTotalDepth: Option[Int] = _
  var minAlternateDepth: Option[Int] = _
  var minSamplesPass: Option[Int] = _
Peter van 't Hof's avatar
Peter van 't Hof committed
28
  var filterRefCalls: Boolean = _
Peter van 't Hof's avatar
Peter van 't Hof committed
29

Peter van 't Hof's avatar
Peter van 't Hof committed
30
31
  override val defaultVmem = "8G"
  memoryLimit = Option(4.0)
Peter van 't Hof's avatar
Peter van 't Hof committed
32

Peter van 't Hof's avatar
Peter van 't Hof committed
33
34
35
36
37
  override def afterGraph {
    minSampleDepth = config("min_sample_depth")
    minTotalDepth = config("min_total_depth")
    minAlternateDepth = config("min_alternate_depth")
    minSamplesPass = config("min_samples_pass")
Peter van 't Hof's avatar
Peter van 't Hof committed
38
    filterRefCalls = config("filter_ref_calls")
Peter van 't Hof's avatar
Peter van 't Hof committed
39
  }
Peter van 't Hof's avatar
Peter van 't Hof committed
40
41
42

  override def commandLine = super.commandLine +
    required("-I", inputVcf) +
Peter van 't Hof's avatar
Peter van 't Hof committed
43
    required("-o", outputVcf) +
Peter van 't Hof's avatar
Peter van 't Hof committed
44
45
    optional("--minSampleDepth", minSampleDepth) +
    optional("--minTotalDepth", minTotalDepth) +
Peter van 't Hof's avatar
Peter van 't Hof committed
46
    optional("--minAlternateDepth", minAlternateDepth) +
Peter van 't Hof's avatar
Peter van 't Hof committed
47
48
    optional("--minSamplesPass", minSamplesPass) +
    conditional(filterRefCalls, "--filterRefCalls")
Peter van 't Hof's avatar
Peter van 't Hof committed
49
50
}

Peter van 't Hof's avatar
Peter van 't Hof committed
51
object VcfFilter extends ToolCommand {
52
53
54
55
56
57
58
59
60
61
62
63
  case class Args(inputVcf: File = null,
                  outputVcf: File = null,
                  minSampleDepth: Int = -1,
                  minTotalDepth: Int = -1,
                  minAlternateDepth: Int = -1,
                  minSamplesPass: Int = 0,
                  minBamAlternateDepth: Int = 0,
                  mustHaveVariant: List[String] = Nil,
                  denovoInSample: String = null,
                  notSameGenotype: List[(String, String)] = Nil,
                  filterHetVarToHomVar: List[(String, String)] = Nil,
                  filterRefCalls: Boolean = false) extends AbstractArgs
Peter van 't Hof's avatar
Peter van 't Hof committed
64
65

  class OptParser extends AbstractOptParser {
Peter van 't Hof's avatar
Peter van 't Hof committed
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
    opt[File]('I', "inputVcf") required () maxOccurs (1) valueName ("<file>") action { (x, c) =>
      c.copy(inputVcf = x)
    }
    opt[File]('o', "outputVcf") required () maxOccurs (1) valueName ("<file>") action { (x, c) =>
      c.copy(outputVcf = x)
    } text ("output file, default to stdout")
    opt[Int]("minSampleDepth") unbounded () action { (x, c) =>
      c.copy(minSampleDepth = x)
    }
    opt[Int]("minTotalDepth") unbounded () action { (x, c) =>
      c.copy(minTotalDepth = x)
    }
    opt[Int]("minAlternateDepth") unbounded () action { (x, c) =>
      c.copy(minAlternateDepth = x)
    }
    opt[Int]("minSamplesPass") unbounded () action { (x, c) =>
      c.copy(minSamplesPass = x)
    }
    opt[Int]("minBamAlternateDepth") unbounded () action { (x, c) =>
      c.copy(minBamAlternateDepth = x)
    }
87
88
89
90
91
92
93
94
95
96
97
98
    opt[String]("denovoInSample") maxOccurs (1) unbounded () action { (x, c) =>
      c.copy(denovoInSample = x)
    }
    opt[String]("mustHaveVariant") unbounded () action { (x, c) =>
      c.copy(mustHaveVariant = x :: c.mustHaveVariant)
    }
    opt[String]("notSameGenotype") unbounded () action { (x, c) =>
      c.copy(notSameGenotype = (x.split(":")(0), x.split(":")(1)) :: c.notSameGenotype)
    } validate { x => if (x.split(":").length == 2) success else failure("--notSameGenotype should be in this format: sample:sample") }
    opt[String]("filterHetVarToHomVar") unbounded () action { (x, c) =>
      c.copy(filterHetVarToHomVar = (x.split(":")(0), x.split(":")(1)) :: c.filterHetVarToHomVar)
    } validate { x => if (x.split(":").length == 2) success else failure("--filterHetVarToHomVar should be in this format: sample:sample") }
Peter van 't Hof's avatar
Peter van 't Hof committed
99
100
101
    opt[Unit]("filterRefCalls") unbounded () action { (x, c) =>
      c.copy(filterRefCalls = true)
    }
Peter van 't Hof's avatar
Peter van 't Hof committed
102
  }
Peter van 't Hof's avatar
Peter van 't Hof committed
103

104
105
  var commandArgs: Args = _

Peter van 't Hof's avatar
Peter van 't Hof committed
106
107
108
109
  /**
   * @param args the command line arguments
   */
  def main(args: Array[String]): Unit = {
Peter van 't Hof's avatar
Peter van 't Hof committed
110
    val argsParser = new OptParser
111
    commandArgs = argsParser.parse(args, Args()) getOrElse sys.exit(1)
Peter van 't Hof's avatar
Peter van 't Hof committed
112

Peter van 't Hof's avatar
Peter van 't Hof committed
113
    val reader = new VCFFileReader(commandArgs.inputVcf, false)
Peter van 't Hof's avatar
Peter van 't Hof committed
114
    val header = reader.getFileHeader
Peter van 't Hof's avatar
Peter van 't Hof committed
115
    val writer = new AsyncVariantContextWriter(new VariantContextWriterBuilder().setOutputFile(commandArgs.outputVcf).build)
Peter van 't Hof's avatar
Peter van 't Hof committed
116
    writer.writeHeader(header)
Peter van 't Hof's avatar
Peter van 't Hof committed
117

Peter van 't Hof's avatar
Peter van 't Hof committed
118
    val bamDPFields = (for (line <- header.getInfoHeaderLines if line.getID.startsWith("BAM-DP-")) yield line.getID).toList
Peter van 't Hof's avatar
Peter van 't Hof committed
119

Peter van 't Hof's avatar
Peter van 't Hof committed
120
121
    for (record <- reader) {
      val genotypes = for (genotype <- record.getGenotypes) yield {
Peter van 't Hof's avatar
Peter van 't Hof committed
122
        val DP = if (genotype.hasDP) genotype.getDP else -1
Peter van 't Hof's avatar
Peter van 't Hof committed
123
124
125
126
        val AD = if (genotype.hasAD) List(genotype.getAD: _*) else Nil
        DP >= commandArgs.minSampleDepth &&
          (if (!AD.isEmpty) AD.tail.count(_ >= commandArgs.minAlternateDepth) > 0 else true) &&
          !(commandArgs.filterRefCalls && genotype.isHomRef)
Peter van 't Hof's avatar
Peter van 't Hof committed
127
      }
Peter van 't Hof's avatar
Peter van 't Hof committed
128
129
130

      if (record.getAttributeAsInt("DP", -1) >= commandArgs.minTotalDepth &&
        genotypes.count(_ == true) >= commandArgs.minSamplesPass &&
131
132
133
134
135
        minBamAlternateDepth(record, header) &&
        mustHaveVariant(record) &&
        notSameGenotype(record) &&
        filterHetVarToHomVar(record) &&
        denovoInSample(record))
Peter van 't Hof's avatar
Peter van 't Hof committed
136
137
138
139
140
        writer.add(record)
    }
    reader.close
    writer.close
  }
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

  def minBamAlternateDepth(record: VariantContext, header: VCFHeader): Boolean = {
    val bamADFields = (for (line <- header.getInfoHeaderLines if line.getID.startsWith("BAM-AD-")) yield line.getID).toList

    val bamADvalues = (for (field <- bamADFields) yield {
      record.getAttribute(field, new ArrayList) match {
        case t: ArrayList[_] if t.length > 1 => {
          for (i <- 1 until t.size) yield {
            t(i) match {
              case a: Int    => a > commandArgs.minBamAlternateDepth
              case a: String => a.toInt > commandArgs.minBamAlternateDepth
              case _         => false
            }
          }
        }
        case _ => List(false)
      }
    }).flatten

    return commandArgs.minBamAlternateDepth <= 0 || bamADvalues.count(_ == true) >= commandArgs.minSamplesPass
  }

  def mustHaveVariant(record: VariantContext): Boolean = {
    return !commandArgs.mustHaveVariant.map(record.getGenotype(_)).exists(a => a.isHomRef || a.isNoCall)
  }

  def notSameGenotype(record: VariantContext): Boolean = {
    for ((sample1, sample2) <- commandArgs.notSameGenotype) {
      val genotype1 = record.getGenotype(sample1)
      val genotype2 = record.getGenotype(sample2)
      if (genotype1.sameGenotype(genotype2)) return false
    }
    return true
  }

  def filterHetVarToHomVar(record: VariantContext): Boolean = {
    for ((sample1, sample2) <- commandArgs.filterHetVarToHomVar) {
      val genotype1 = record.getGenotype(sample1)
      val genotype2 = record.getGenotype(sample2)
      if (genotype1.isHet && !genotype1.getAlleles.forall(_.isNonReference)) {
        for (allele <- genotype1.getAlleles if allele.isNonReference) {
          if (genotype2.getAlleles.forall(_.basesMatch(allele))) return false
        }
      }
    }
    return true
  }

  def denovoInSample(record: VariantContext): Boolean = {
    if (commandArgs.denovoInSample == null) return true
    val genotype = record.getGenotype(commandArgs.denovoInSample)
    for (allele <- genotype.getAlleles if allele.isNonReference) {
      for (g <- record.getGenotypes if g.getSampleName != commandArgs.denovoInSample) {
        if (g.getAlleles.exists(_.basesMatch(allele))) return false
      }
    }
    return true
  }
Peter van 't Hof's avatar
Peter van 't Hof committed
199
}