Repository navigation
Expand file tree
/
Copy pathVariant.scala
More file actions
423 lines (332 loc) · 11.7 KB
/
Copy pathVariant.scala
File metadata and controls
423 lines (332 loc) · 11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
package is.hail.variant
import is.hail.check.{Arbitrary, Gen}
import is.hail.expr._
import is.hail.sparkextras.OrderedKey
import is.hail.utils._
import org.apache.spark.SparkContext
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.Row
import org.apache.spark.sql.types._
import org.json4s._
import scala.collection.JavaConverters._
import scala.math.Numeric.Implicits._
import scala.reflect.ClassTag
object Contig {
val standardContigs = (1 to 23).map(_.toString) ++ IndexedSeq("X", "Y", "MT")
val standardContigIdx = standardContigs.zipWithIndex.toMap
def compare(lhs: String, rhs: String): Int = {
(standardContigIdx.get(lhs), standardContigIdx.get(rhs)) match {
case (Some(i), Some(j)) => i.compare(j)
case (Some(_), None) => -1
case (None, Some(_)) => 1
case (None, None) => lhs.compare(rhs)
}
}
}
case class Contig(name: String, length: Int)
object AltAlleleType extends Enumeration {
type AltAlleleType = Value
val SNP, MNP, Insertion, Deletion, Complex, Star = Value
}
object CopyState extends Enumeration {
type CopyState = Value
val Auto, HemiX, HemiY = Value
}
object AltAllele {
def sparkSchema: StructType = StructType(Array(
StructField("ref", StringType, nullable = false),
StructField("alt", StringType, nullable = false)))
val expandedType: TStruct = TStruct("ref" -> TString,
"alt" -> TString)
def fromRow(r: Row): AltAllele =
AltAllele(r.getString(0), r.getString(1))
def gen(ref: String): Gen[AltAllele] =
for (alt <- Gen.frequency((10, genDNAString),
(1, Gen.const("*"))) if alt != ref)
yield AltAllele(ref, alt)
def gen: Gen[AltAllele] =
for (ref <- genDNAString;
alt <- genDNAString if alt != ref)
yield AltAllele(ref, alt)
implicit def altAlleleOrder: Ordering[AltAllele] = new Ordering[AltAllele] {
def compare(x: AltAllele, y: AltAllele): Int = x.compare(y)
}
}
case class AltAllele(ref: String,
alt: String) {
require(ref != alt, "ref was equal to alt")
require(!ref.isEmpty, "ref was an empty string")
require(!alt.isEmpty, "alt was an empty string")
import AltAlleleType._
def altAlleleType: AltAlleleType = {
if (isSNP)
SNP
else if (isInsertion)
Insertion
else if (isDeletion)
Deletion
else if (isStar)
Star
else if (ref.length == alt.length)
MNP
else
Complex
}
def isStar: Boolean = alt == "*"
def isSNP: Boolean = !isStar && ( (ref.length == 1 && alt.length == 1) ||
(ref.length == alt.length && nMismatch == 1) )
def isMNP: Boolean = ref.length > 1 &&
ref.length == alt.length &&
nMismatch > 1
def isInsertion: Boolean = ref.length < alt.length && ref(0) == alt(0) && alt.endsWith(ref.substring(1))
def isDeletion: Boolean = alt.length < ref.length && ref(0) == alt(0) && ref.endsWith(alt.substring(1))
def isIndel: Boolean = isInsertion || isDeletion
def isComplex: Boolean = ref.length != alt.length && !isInsertion && !isDeletion
def isTransition: Boolean = isSNP && {
val (refChar, altChar) = strippedSNP
(refChar == 'A' && altChar == 'G') || (refChar == 'G' && altChar == 'A') ||
(refChar == 'C' && altChar == 'T') || (refChar == 'T' && altChar == 'C')
}
def isTransversion: Boolean = isSNP && !isTransition
def nMismatch: Int = {
require(ref.length == alt.length, s"invalid nMismatch call on ref `${ ref }' and alt `${ alt }'")
(ref, alt).zipped.map((a, b) => if (a == b) 0 else 1).sum
}
def strippedSNP: (Char, Char) = {
require(isSNP, "called strippedSNP on non-SNP")
(ref, alt).zipped.dropWhile { case (a, b) => a == b }.head
}
def toRow: Row = Row(ref, alt)
def toJSON: JValue = JObject(
("ref", JString(ref)),
("alt", JString(alt)))
override def toString: String = s"$ref/$alt"
def compare(that: AltAllele): Int = {
val c = ref.compare(that.ref)
if (c != 0)
return c
alt.compare(that.alt)
}
}
object Variant {
def apply(contig: String,
start: Int,
ref: String,
alt: String): Variant = Variant(contig, start, ref, Array(AltAllele(ref, alt)))
def apply(contig: String,
start: Int,
ref: String,
alts: Array[String]): Variant =
Variant(contig, start, ref, alts.map(alt => AltAllele(ref, alt)))
def apply(contig: String,
start: Int,
ref: String,
alts: java.util.ArrayList[String]): Variant = Variant(contig, start, ref, alts.asScala.toArray)
def parse(str: String): Variant = {
val colonSplit = str.split(":")
if (colonSplit.length != 4)
fatal(s"invalid variant, expected 4 colon-delimited fields, found ${ colonSplit.length }: $str")
val Array(contig, start, ref, alts) = colonSplit
Variant(contig, start.toInt, ref, alts.split(","))
}
def nGenotypes(nAlleles: Int): Int = {
require(nAlleles > 0, s"called nGenotypes with invalid number of alternates: $nAlleles")
nAlleles * (nAlleles + 1) / 2
}
def gen: Gen[Variant] = VariantSubgen.random.gen
implicit def arbVariant: Arbitrary[Variant] = Arbitrary(gen)
def sparkSchema: StructType =
StructType(Array(
StructField("contig", StringType, nullable = false),
StructField("start", IntegerType, nullable = false),
StructField("ref", StringType, nullable = false),
StructField("altAlleles", ArrayType(AltAllele.sparkSchema, containsNull = false),
nullable = false)))
def expandedType: TStruct =
TStruct("contig" -> TString,
"start" -> TInt,
"ref" -> TString,
"altAlleles" -> TArray(AltAllele.expandedType))
def fromRow(r: Row) =
Variant(r.getAs[String](0),
r.getAs[Int](1),
r.getAs[String](2),
r.getSeq[Row](3)
.map(s => AltAllele.fromRow(s))
.toArray)
implicit val orderedKey: OrderedKey[Locus, Variant] =
new OrderedKey[Locus, Variant] {
def project(key: Variant): Locus = key.locus
def kOrd: Ordering[Variant] = implicitly[Ordering[Variant]]
def pkOrd: Ordering[Locus] = implicitly[Ordering[Locus]]
def kct: ClassTag[Variant] = implicitly[ClassTag[Variant]]
def pkct: ClassTag[Locus] = implicitly[ClassTag[Locus]]
}
def variantUnitRdd(sc: SparkContext, input: String): RDD[(Variant, Unit)] =
sc.textFileLines(input)
.map {
_.map { line =>
val fields = line.split(":")
if (fields.length != 4)
fatal("invalid variant: expect `CHR:POS:REF:ALT1,ALT2,...,ALTN'")
val ref = fields(2)
(Variant(fields(0),
fields(1).toInt,
ref,
fields(3).split(",").map(alt => AltAllele(ref, alt))), ())
}.value
}
implicit def variantOrder: Ordering[Variant] = new Ordering[Variant] {
def compare(x: Variant, y: Variant): Int = x.compare(y)
}
}
object VariantSubgen {
val random = VariantSubgen(
contigGen = Gen.identifier,
startGen = Gen.posInt,
nAllelesGen = Gen.frequency((5, Gen.const(2)), (1, Gen.choose(2, 10))),
refGen = genDNAString,
altGen = Gen.frequency((10, genDNAString),
(1, Gen.const("*"))))
val plinkCompatible = random.copy(
contigGen = Gen.choose(1, 22).map(_.toString)
)
val biallelic = random.copy(nAllelesGen = Gen.const(2))
}
case class VariantSubgen(
contigGen: Gen[String],
startGen: Gen[Int],
nAllelesGen: Gen[Int],
refGen: Gen[String],
altGen: Gen[String]) {
def gen: Gen[Variant] =
for (contig <- contigGen;
start <- startGen;
nAlleles <- nAllelesGen;
ref <- refGen;
altAlleles <- Gen.distinctBuildableOfN[Array, String](
nAlleles,
altGen)
.filter(!_.contains(ref))) yield
Variant(contig, start, ref, altAlleles.tail.map(alt => AltAllele(ref, alt)))
}
case class Variant(contig: String,
start: Int,
ref: String,
altAlleles: IndexedSeq[AltAllele]) {
/* The position is 1-based. Telomeres are indicated by using positions 0 or N+1, where N is the length of the
corresponding chromosome or contig. See the VCF spec, v4.2, section 1.4.1. */
require(start >= 0, s"invalid variant: negative position: `${ this.toString }'")
require(!ref.isEmpty, s"invalid variant: empty contig: `${ this.toString }'")
def nAltAlleles: Int = altAlleles.length
def isBiallelic: Boolean = nAltAlleles == 1
// FIXME altAllele, alt to be deprecated
def altAllele: AltAllele = {
require(isBiallelic, "called altAllele on a non-biallelic variant")
altAlleles(0)
}
def alt: String = altAllele.alt
def nAlleles: Int = 1 + nAltAlleles
def allele(i: Int): String = if (i == 0)
ref
else
altAlleles(i - 1).alt
def nGenotypes = Variant.nGenotypes(nAlleles)
def locus: Locus = Locus(contig, start)
def isAutosomalOrPseudoAutosomal: Boolean =
isAutosomal || inXPar || inYPar
def isAutosomal = !(inX || inY || isMitochondrial)
def isMitochondrial = {
val c = contig.toUpperCase
c == "MT" || c == "M" || c == "26"
}
// PAR regions of sex chromosomes: https://en.wikipedia.org/wiki/Pseudoautosomal_region
// Boundaries for build GRCh37: http://www.ncbi.nlm.nih.gov/projects/genome/assembly/grc/human/
def inXParPos: Boolean = (60001 <= start && start <= 2699520) || (154931044 <= start && start <= 155260560)
def inYParPos: Boolean = (10001 <= start && start <= 2649520) || (59034050 <= start && start <= 59363566)
// FIXME: will replace with contig == "X" etc once bgen/plink support is merged and conversion is handled by import
def inXPar: Boolean = inX && inXParPos
def inYPar: Boolean = inY && inYParPos
def inXNonPar: Boolean = inX && !inXParPos
def inYNonPar: Boolean = inY && !inYParPos
private def inX: Boolean = contig.toUpperCase == "X" || contig == "23" || contig == "25"
private def inY: Boolean = contig.toUpperCase == "Y" || contig == "24"
import CopyState._
def copyState(sex: Sex.Sex): CopyState =
if (sex == Sex.Male)
if (inXNonPar)
HemiX
else if (inYNonPar)
HemiY
else
Auto
else
Auto
def compare(that: Variant): Int = {
var c = Contig.compare(contig, that.contig)
if (c != 0)
return c
c = start.compare(that.start)
if (c != 0)
return c
c = ref.compare(that.ref)
if (c != 0)
return c
c = nAltAlleles.compare(that.nAltAlleles)
if (c != 0)
return c
var i = 0
while (i < altAlleles.length) {
c = altAlleles(i).alt.compare(that.altAlleles(i).alt)
if (c != 0)
return c
i += 1
}
0
}
def minRep: Variant = {
if (ref.length == 1)
this
else if (altAlleles.forall(a => a.isStar))
Variant(contig, start, ref.substring(0, 1), altAlleles.map(_.alt).toArray)
else {
val alts = altAlleles.filter(!_.isStar).map(a => a.alt)
require(alts.forall(ref != _))
val min_length = math.min(ref.length, alts.map(x => x.length).min)
var ne = 0
while (ne < min_length - 1
&& alts.forall(x => ref(ref.length - ne - 1) == x(x.length - ne - 1))
) {
ne += 1
}
var ns = 0
while (ns < min_length - ne - 1
&& alts.forall(x => ref(ns) == x(ns))
) {
ns += 1
}
if (ne + ns == 0)
this
else {
assert(ns < ref.length - ne && alts.forall(x => ns < x.length - ne))
Variant(contig, start + ns, ref.substring(ns, ref.length - ne),
altAlleles.map(a => if (a.isStar) a.alt else a.alt.substring(ns, a.alt.length - ne)).toArray)
}
}
}
override def toString: String =
s"$contig:$start:$ref:${ altAlleles.map(_.alt).mkString(",") }"
def toRow = {
Row.fromSeq(Array(
contig,
start,
ref,
altAlleles.map { a => Row.fromSeq(Array(a.ref, a.alt)) }))
}
def toJSON: JValue = JObject(
("contig", JString(contig)),
("start", JInt(start)),
("ref", JString(ref)),
("altAlleles", JArray(altAlleles.map(_.toJSON).toList))
)
}