Skip to content

Variant Direction

gentropy.dataset.variant_direction.Direction

Bases: int, Enum

Allele direction.

Attributes:

Name Type Description
DIRECT int

Direct allele direction (e.g., A/G). Defaults to 1.

FLIPPED int

Flipped allele direction (e.g., G/A). Defaults to -1.

Source code in src/gentropy/dataset/variant_direction.py
17
18
19
20
21
22
23
24
25
26
class Direction(int, Enum):
    """Allele direction.

    Attributes:
        DIRECT (int): Direct allele direction (e.g., A/G). Defaults to 1.
        FLIPPED (int): Flipped allele direction (e.g., G/A). Defaults to -1.
    """

    DIRECT = 1
    FLIPPED = -1

gentropy.dataset.variant_direction.Strand

Bases: int, Enum

Strand orientation.

Attributes:

Name Type Description
FORWARD int

Forward strand. Defaults to 1.

REVERSE int

Reverse strand. Defaults to -1.

Source code in src/gentropy/dataset/variant_direction.py
29
30
31
32
33
34
35
36
37
38
class Strand(int, Enum):
    """Strand orientation.

    Attributes:
        FORWARD (int): Forward strand. Defaults to 1.
        REVERSE (int): Reverse strand. Defaults to -1.
    """

    FORWARD = 1
    REVERSE = -1

gentropy.dataset.variant_direction.VariantType

Bases: int, Enum

Variant types based on length of reference and alternate alleles.

Attributes:

Name Type Description
SNP int

Single Nucleotide Polymorphism. Defaults to 1.

INS int

Insertion. Defaults to 2.

DEL int

Deletion. Defaults to 3.

MNP int

Multi-Nucleotide Polymorphism. Defaults to 4.

Source code in src/gentropy/dataset/variant_direction.py
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class VariantType(int, Enum):
    """Variant types based on length of reference and alternate alleles.

    Attributes:
        SNP (int): Single Nucleotide Polymorphism. Defaults to 1.
        INS (int): Insertion. Defaults to 2.
        DEL (int): Deletion. Defaults to 3.
        MNP (int): Multi-Nucleotide Polymorphism. Defaults to 4.
    """

    SNP = 1
    INS = 2
    DEL = 3
    MNP = 4

gentropy.dataset.variant_direction.VariantDirection dataclass

Bases: Dataset

Dataset used for aligning allele directionality between different datasets.

This dataset is useful for flipping alleles to match reference datasets.

This dataset expends each variant into 4 entries to account for

  • Different directions (FORWARD and FLIPPED) - e.g. A/G and G/A
  • Different strands (FORWARD and REVERSE) - e.g. A/G and T/C

Each entry contains the combination of both, meaning that for each input variant there will be 4 entries in this dataset. For strand ambiguous variants the FORWARD and FLIPPED entries will be identical to the REVERSE and FLIPPED entries, so we keep only one copy of them.

Additionally this dataset annotates:

  • ambiguous strand variants
  • type of variant (SNP, INS, DEL, MNP)
  • original allele frequencies from the source dataset
  • original variant id from the source dataset
Joining with other datasets

To compare two datasets, you need to ensure that both datasets are joined on the variantId that is a combination of chromosome, position, reference allele and alternate allele.

Building the dataset

The easiest way to create this dataset (have a complete variant space) is to build it from a VariantIndex.

Examples:

>>> data = [("1", 100, "A", "G", [("nfe_adj", 0.1), ("fin_adj", 0.2)]), ("1", 100, "T", "A", [("nfe_adj", 0.1), ("fin_adj", 0.2)])]
>>> schema = "chromosome STRING, position INT, referenceAllele STRING, alternateAllele STRING, alleleFrequencies ARRAY<STRUCT<populationName: STRING, alleleFrequency: DOUBLE>>"
>>> df = spark.createDataFrame(data, schema).withColumn("variantId",
... f.concat_ws("_", "chromosome", "position", "referenceAllele", "alternateAllele"))
>>> variant_index = VariantIndex(_df=df)
>>> variant_direction = VariantDirection.from_variant_index(variant_index)
>>> variant_direction.df.show(truncate=False)
+----------+-----------------+----+---------+---------+------+-----------------+--------------------------------+
|chromosome|originalVariantId|type|variantId|direction|strand|isStrandAmbiguous|originalAlleleFrequencies       |
+----------+-----------------+----+---------+---------+------+-----------------+--------------------------------+
|1         |1_100_A_G        |1   |1_100_A_G|1        |1     |false            |[{nfe_adj, 0.1}, {fin_adj, 0.2}]|
|1         |1_100_A_G        |1   |1_100_G_A|-1       |1     |false            |[{nfe_adj, 0.1}, {fin_adj, 0.2}]|
|1         |1_100_A_G        |1   |1_100_T_C|1        |-1    |false            |[{nfe_adj, 0.1}, {fin_adj, 0.2}]|
|1         |1_100_A_G        |1   |1_100_C_T|-1       |-1    |false            |[{nfe_adj, 0.1}, {fin_adj, 0.2}]|
|1         |1_100_T_A        |1   |1_100_T_A|1        |1     |true             |[{nfe_adj, 0.1}, {fin_adj, 0.2}]|
|1         |1_100_T_A        |1   |1_100_A_T|-1       |1     |true             |[{nfe_adj, 0.1}, {fin_adj, 0.2}]|
+----------+-----------------+----+---------+---------+------+-----------------+--------------------------------+
Source code in src/gentropy/dataset/variant_direction.py
 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
@dataclass
class VariantDirection(Dataset):
    """Dataset used for aligning allele directionality between different datasets.

    This dataset is useful for flipping alleles to match reference datasets.

    This dataset expends each variant into 4 entries to account for

    * Different directions (`FORWARD` and `FLIPPED`) - e.g. A/G and G/A
    * Different strands (`FORWARD` and `REVERSE`) - e.g. A/G and T/C

    Each entry contains the combination of both, meaning that for each input variant
    there will be 4 entries in this dataset. For strand ambiguous variants the
    `FORWARD` and `FLIPPED` entries will be identical to the `REVERSE` and `FLIPPED` entries,
    so we keep only one copy of them.

    Additionally this dataset annotates:

    * ambiguous strand variants
    * type of variant (SNP, INS, DEL, MNP)
    * original allele frequencies from the source dataset
    * original variant id from the source dataset

    ??? tip "Joining with other datasets"
        To compare two datasets, you need to ensure that both datasets are joined on the `variantId` that
        is a combination of `chromosome`, `position`, `reference allele` and `alternate allele`.

    ??? note "Building the dataset"
        The easiest way to create this dataset (have a complete variant space) is to build it
        from a **VariantIndex**.

    Examples:
        >>> data = [("1", 100, "A", "G", [("nfe_adj", 0.1), ("fin_adj", 0.2)]), ("1", 100, "T", "A", [("nfe_adj", 0.1), ("fin_adj", 0.2)])]
        >>> schema = "chromosome STRING, position INT, referenceAllele STRING, alternateAllele STRING, alleleFrequencies ARRAY<STRUCT<populationName: STRING, alleleFrequency: DOUBLE>>"
        >>> df = spark.createDataFrame(data, schema).withColumn("variantId",
        ... f.concat_ws("_", "chromosome", "position", "referenceAllele", "alternateAllele"))
        >>> variant_index = VariantIndex(_df=df)
        >>> variant_direction = VariantDirection.from_variant_index(variant_index)
        >>> variant_direction.df.show(truncate=False)
        +----------+-----------------+----+---------+---------+------+-----------------+--------------------------------+
        |chromosome|originalVariantId|type|variantId|direction|strand|isStrandAmbiguous|originalAlleleFrequencies       |
        +----------+-----------------+----+---------+---------+------+-----------------+--------------------------------+
        |1         |1_100_A_G        |1   |1_100_A_G|1        |1     |false            |[{nfe_adj, 0.1}, {fin_adj, 0.2}]|
        |1         |1_100_A_G        |1   |1_100_G_A|-1       |1     |false            |[{nfe_adj, 0.1}, {fin_adj, 0.2}]|
        |1         |1_100_A_G        |1   |1_100_T_C|1        |-1    |false            |[{nfe_adj, 0.1}, {fin_adj, 0.2}]|
        |1         |1_100_A_G        |1   |1_100_C_T|-1       |-1    |false            |[{nfe_adj, 0.1}, {fin_adj, 0.2}]|
        |1         |1_100_T_A        |1   |1_100_T_A|1        |1     |true             |[{nfe_adj, 0.1}, {fin_adj, 0.2}]|
        |1         |1_100_T_A        |1   |1_100_A_T|-1       |1     |true             |[{nfe_adj, 0.1}, {fin_adj, 0.2}]|
        +----------+-----------------+----+---------+---------+------+-----------------+--------------------------------+
        <BLANKLINE>

    """

    @classmethod
    def get_schema(cls: type[VariantDirection]) -> t.StructType:
        """Provides the schema for the variant index dataset.

        Returns:
            t.StructType: Schema for the VariantIndex dataset
        """
        return parse_spark_schema("variant_direction.json")

    @classmethod
    def is_strand_ambiguous(cls, ref: Column, alt: Column) -> Column:
        """Check if the variant is strand ambiguous.

        Args:
            ref (Column): Reference allele column.
            alt (Column): Alternate allele column.

        Returns:
            Column: Boolean column indicating if the variant is palindromic.

        Examples:
            >>> data = [("A", "T"), ("C", "G"), ("A", "G"), ("AC", "GT"), ("AT", "TA"), ("A", "AT")]
            >>> schema = "ref STRING, alt STRING"
            >>> df = spark.createDataFrame(data, schema)
            >>> df.withColumn("isStrandAmbiguous", VariantDirection.is_strand_ambiguous(f.col("ref"), f.col("alt"))).show()
            +---+---+-----------------+
            |ref|alt|isStrandAmbiguous|
            +---+---+-----------------+
            |  A|  T|             true|
            |  C|  G|             true|
            |  A|  G|            false|
            | AC| GT|             true|
            | AT| TA|            false|
            |  A| AT|            false|
            +---+---+-----------------+
            <BLANKLINE>

        """
        ref_len = f.length(ref)
        alt_len = f.length(alt)
        ref = f.upper(ref)
        alt = f.upper(alt)
        return f.when(
            (ref_len == alt_len) & (cls.reverse(cls.complement(alt)) == ref), True
        ).otherwise(False)

    @staticmethod
    def reverse(allele: Column) -> Column:
        """Reverse the allele string.

        Args:
            allele (Column): Allele column.

        Returns:
            Column: Reversed allele column.

        Examples:
            >>> data = [("A",), ("AT",), ("GTC",)]
            >>> schema = "allele STRING"
            >>> df = spark.createDataFrame(data, schema)
            >>> df.withColumn("reversed", VariantDirection.reverse(f.col("allele"))).show()
            +------+--------+
            |allele|reversed|
            +------+--------+
            |     A|       A|
            |    AT|      TA|
            |   GTC|     CTG|
            +------+--------+
            <BLANKLINE>

        """
        return f.reverse(allele)

    @staticmethod
    def complement(allele: Column) -> Column:
        """Complement the allele string.

        Args:
            allele (Column): Allele column.

        Returns:
            Column: Complemented allele column.

        Examples:
            >>> data = [("A",), ("C",), ("G",), ("T",), ("AT",), ("GTC",)]
            >>> schema = "allele STRING"
            >>> df = spark.createDataFrame(data, schema)
            >>> df.withColumn("complemented", VariantDirection.complement(f.col("allele"))).show()
            +------+------------+
            |allele|complemented|
            +------+------------+
            |     A|           T|
            |     C|           G|
            |     G|           C|
            |     T|           A|
            |    AT|          TA|
            |   GTC|         CAG|
            +------+------------+
            <BLANKLINE>

        """
        return f.translate(f.upper(allele), "ACGT", "TGCA")

    @classmethod
    def variant_type(cls, ref: Column, alt: Column) -> Column:
        """Get the variant type.

        Args:
            ref (Column): Reference allele column.
            alt (Column): Alternate allele column.

        Returns:
            Column: Variant type column.

        Note:
            Variant type coding follows VariantType enum:
            - 1: SNP (Single Nucleotide Polymorphism)
            - 2: INS (Insertion)
            - 3: DEL (Deletion)
            - 4: MNP (Multi-Nucleotide Polymorphism)

        Examples:
            >>> data = [("A", "G"), ("A", "AT"), ("AT", "A"), ("AT", "GC")]
            >>> schema = "ref STRING, alt STRING"
            >>> df = spark.createDataFrame(data, schema)
            >>> df.withColumn("type", VariantDirection.variant_type(f.col("ref"), f.col("alt"))).show()
            +---+---+----+
            |ref|alt|type|
            +---+---+----+
            |  A|  G|   1|
            |  A| AT|   2|
            | AT|  A|   3|
            | AT| GC|   4|
            +---+---+----+
            <BLANKLINE>
        """
        ref = f.upper(ref)
        alt = f.upper(alt)
        expr = (
            f.when((f.length(alt) > f.length(ref)), f.lit(VariantType.INS.value))
            .when((f.length(alt) < f.length(ref)), f.lit(VariantType.DEL.value))
            .when(
                ((f.length(alt) == 1) & (f.length(ref) == 1)),
                f.lit(VariantType.SNP.value),
            )
            .otherwise(f.lit(VariantType.MNP.value))
        )
        return expr.cast(t.ByteType())

    @classmethod
    def alleles(
        cls, chrom: Column, pos: Column, ref: Column, alt: Column, af: Column
    ) -> Column:
        """Get the alleles of the variant.

        Args:
            chrom (Column): Chromosome column.
            pos (Column): Position column.
            ref (Column): Reference allele column.
            alt (Column): Alternate allele column.
            af (Column): Allele frequencies column.

        Returns:
            Column: Array of structs with variantId, direction, strand, isStrandAmbiguous, alleleFrequencies.

        Examples:
            >>> data = [("1", 100, "A", "G", [("nfe_adj", 0.1),]), ("1", 100, "T", "A", [("nfe_adj", 0.1),])]
            >>> schema = "chrom STRING, pos INT, ref STRING, alt STRING, af ARRAY<STRUCT<populationName: STRING, alleleFrequency: DOUBLE>>"
            >>> df = spark.createDataFrame(data, schema)
            >>> df = df.withColumn("alleles", VariantDirection.alleles(f.col("chrom"), f.col("pos"), f.col("ref"), f.col("alt"), f.col("af"))).select("alleles")
            >>> df.select(f.explode("alleles").alias("allele")).select("allele.*").show(truncate=False)
            +---------+---------+------+-----------------+-------------------------+
            |variantId|direction|strand|isStrandAmbiguous|originalAlleleFrequencies|
            +---------+---------+------+-----------------+-------------------------+
            |1_100_A_G|1        |1     |false            |[{nfe_adj, 0.1}]         |
            |1_100_G_A|-1       |1     |false            |[{nfe_adj, 0.1}]         |
            |1_100_T_C|1        |-1    |false            |[{nfe_adj, 0.1}]         |
            |1_100_C_T|-1       |-1    |false            |[{nfe_adj, 0.1}]         |
            |1_100_T_A|1        |1     |true             |[{nfe_adj, 0.1}]         |
            |1_100_A_T|-1       |1     |true             |[{nfe_adj, 0.1}]         |
            +---------+---------+------+-----------------+-------------------------+
            <BLANKLINE>
        """
        ref = f.upper(ref)
        alt = f.upper(alt)
        forward_direct = cls.variant_id(chrom, pos, ref, alt)
        forward_flipped = cls.variant_id(chrom, pos, alt, ref)
        reverse_direct = cls.variant_id(
            chrom,
            pos,
            cls.reverse(cls.complement(ref)),
            cls.reverse(cls.complement(alt)),
        )
        reverse_flipped = cls.variant_id(
            chrom,
            pos,
            cls.reverse(cls.complement(alt)),
            cls.reverse(cls.complement(ref)),
        )

        return f.when(
            ~cls.is_strand_ambiguous(ref, alt),
            f.array(
                f.struct(
                    forward_direct.alias("variantId"),
                    f.lit(Direction.DIRECT.value).cast(t.ByteType()).alias("direction"),
                    f.lit(Strand.FORWARD.value).cast(t.ByteType()).alias("strand"),
                    f.lit(False).alias("isStrandAmbiguous"),
                    af.alias("originalAlleleFrequencies"),
                ),
                f.struct(
                    forward_flipped.alias("variantId"),
                    f.lit(Direction.FLIPPED.value)
                    .cast(t.ByteType())
                    .alias("direction"),
                    f.lit(Strand.FORWARD.value).cast(t.ByteType()).alias("strand"),
                    f.lit(False).alias("isStrandAmbiguous"),
                    af.alias("originalAlleleFrequencies"),
                ),
                f.struct(
                    reverse_direct.alias("variantId"),
                    f.lit(Direction.DIRECT.value).cast(t.ByteType()).alias("direction"),
                    f.lit(Strand.REVERSE.value).cast(t.ByteType()).alias("strand"),
                    f.lit(False).alias("isStrandAmbiguous"),
                    af.alias("originalAlleleFrequencies"),
                ),
                f.struct(
                    reverse_flipped.alias("variantId"),
                    f.lit(Direction.FLIPPED.value)
                    .cast(t.ByteType())
                    .alias("direction"),
                    f.lit(Strand.REVERSE.value).cast(t.ByteType()).alias("strand"),
                    f.lit(False).alias("isStrandAmbiguous"),
                    af.alias("originalAlleleFrequencies"),
                ),
            ),
        ).otherwise(
            f.array(
                f.struct(
                    forward_direct.alias("variantId"),
                    f.lit(Direction.DIRECT.value).cast(t.ByteType()).alias("direction"),
                    f.lit(Strand.FORWARD.value).cast(t.ByteType()).alias("strand"),
                    f.lit(True).alias("isStrandAmbiguous"),
                    af.alias("originalAlleleFrequencies"),
                ),
                f.struct(
                    forward_flipped.alias("variantId"),
                    f.lit(Direction.FLIPPED.value)
                    .cast(t.ByteType())
                    .alias("direction"),
                    f.lit(Strand.FORWARD.value).cast(t.ByteType()).alias("strand"),
                    f.lit(True).alias("isStrandAmbiguous"),
                    af.alias("originalAlleleFrequencies"),
                ),
            )
        )

    @classmethod
    def variant_id(cls, chrom: Column, pos: Column, ref: Column, alt: Column) -> Column:
        """Get the variant id.

        Args:
            chrom (Column): Chromosome column.
            pos (Column): Position column.
            ref (Column): Reference allele column.
            alt (Column): Alternate allele column.

        Returns:
            Column: Variant ID column in the format "chrom_pos_ref_alt".
        """
        ref = f.upper(ref)
        alt = f.upper(alt)
        return f.concat_ws("_", chrom, pos, ref, alt)

    @classmethod
    def from_variant_index(cls, variant_index: VariantIndex) -> VariantDirection:
        """Prepare the variant direction DataFrame with DIRECT and FLIPPED entries.

        Args:
            variant_index (VariantIndex): Variant index dataset.

        Returns:
            VariantDirection: Variant direction dataset.
        """
        lut = variant_index.df.select(
            f.col("chromosome"),
            f.col("variantId").alias("originalVariantId"),
            cls.variant_type(f.col("referenceAllele"), f.col("alternateAllele")).alias(
                "type"
            ),
            f.explode(
                cls.alleles(
                    f.col("chromosome"),
                    f.col("position"),
                    f.col("referenceAllele"),
                    f.col("alternateAllele"),
                    f.col("alleleFrequencies"),
                ).alias("alleles")
            ).alias("allele"),
        ).select(
            f.col("chromosome"),
            f.col("originalVariantId"),
            f.col("type"),
            f.col("allele.variantId").alias("variantId"),
            f.col("allele.direction").alias("direction"),
            f.col("allele.strand").alias("strand"),
            f.col("allele.isStrandAmbiguous").alias("isStrandAmbiguous"),
            f.col("allele.originalAlleleFrequencies").alias(
                "originalAlleleFrequencies"
            ),
        )

        return VariantDirection(_df=lut)

alleles(chrom: Column, pos: Column, ref: Column, alt: Column, af: Column) -> Column classmethod

Get the alleles of the variant.

Parameters:

Name Type Description Default
chrom Column

Chromosome column.

required
pos Column

Position column.

required
ref Column

Reference allele column.

required
alt Column

Alternate allele column.

required
af Column

Allele frequencies column.

required

Returns:

Name Type Description
Column Column

Array of structs with variantId, direction, strand, isStrandAmbiguous, alleleFrequencies.

Examples:

>>> data = [("1", 100, "A", "G", [("nfe_adj", 0.1),]), ("1", 100, "T", "A", [("nfe_adj", 0.1),])]
>>> schema = "chrom STRING, pos INT, ref STRING, alt STRING, af ARRAY<STRUCT<populationName: STRING, alleleFrequency: DOUBLE>>"
>>> df = spark.createDataFrame(data, schema)
>>> df = df.withColumn("alleles", VariantDirection.alleles(f.col("chrom"), f.col("pos"), f.col("ref"), f.col("alt"), f.col("af"))).select("alleles")
>>> df.select(f.explode("alleles").alias("allele")).select("allele.*").show(truncate=False)
+---------+---------+------+-----------------+-------------------------+
|variantId|direction|strand|isStrandAmbiguous|originalAlleleFrequencies|
+---------+---------+------+-----------------+-------------------------+
|1_100_A_G|1        |1     |false            |[{nfe_adj, 0.1}]         |
|1_100_G_A|-1       |1     |false            |[{nfe_adj, 0.1}]         |
|1_100_T_C|1        |-1    |false            |[{nfe_adj, 0.1}]         |
|1_100_C_T|-1       |-1    |false            |[{nfe_adj, 0.1}]         |
|1_100_T_A|1        |1     |true             |[{nfe_adj, 0.1}]         |
|1_100_A_T|-1       |1     |true             |[{nfe_adj, 0.1}]         |
+---------+---------+------+-----------------+-------------------------+
Source code in src/gentropy/dataset/variant_direction.py
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
@classmethod
def alleles(
    cls, chrom: Column, pos: Column, ref: Column, alt: Column, af: Column
) -> Column:
    """Get the alleles of the variant.

    Args:
        chrom (Column): Chromosome column.
        pos (Column): Position column.
        ref (Column): Reference allele column.
        alt (Column): Alternate allele column.
        af (Column): Allele frequencies column.

    Returns:
        Column: Array of structs with variantId, direction, strand, isStrandAmbiguous, alleleFrequencies.

    Examples:
        >>> data = [("1", 100, "A", "G", [("nfe_adj", 0.1),]), ("1", 100, "T", "A", [("nfe_adj", 0.1),])]
        >>> schema = "chrom STRING, pos INT, ref STRING, alt STRING, af ARRAY<STRUCT<populationName: STRING, alleleFrequency: DOUBLE>>"
        >>> df = spark.createDataFrame(data, schema)
        >>> df = df.withColumn("alleles", VariantDirection.alleles(f.col("chrom"), f.col("pos"), f.col("ref"), f.col("alt"), f.col("af"))).select("alleles")
        >>> df.select(f.explode("alleles").alias("allele")).select("allele.*").show(truncate=False)
        +---------+---------+------+-----------------+-------------------------+
        |variantId|direction|strand|isStrandAmbiguous|originalAlleleFrequencies|
        +---------+---------+------+-----------------+-------------------------+
        |1_100_A_G|1        |1     |false            |[{nfe_adj, 0.1}]         |
        |1_100_G_A|-1       |1     |false            |[{nfe_adj, 0.1}]         |
        |1_100_T_C|1        |-1    |false            |[{nfe_adj, 0.1}]         |
        |1_100_C_T|-1       |-1    |false            |[{nfe_adj, 0.1}]         |
        |1_100_T_A|1        |1     |true             |[{nfe_adj, 0.1}]         |
        |1_100_A_T|-1       |1     |true             |[{nfe_adj, 0.1}]         |
        +---------+---------+------+-----------------+-------------------------+
        <BLANKLINE>
    """
    ref = f.upper(ref)
    alt = f.upper(alt)
    forward_direct = cls.variant_id(chrom, pos, ref, alt)
    forward_flipped = cls.variant_id(chrom, pos, alt, ref)
    reverse_direct = cls.variant_id(
        chrom,
        pos,
        cls.reverse(cls.complement(ref)),
        cls.reverse(cls.complement(alt)),
    )
    reverse_flipped = cls.variant_id(
        chrom,
        pos,
        cls.reverse(cls.complement(alt)),
        cls.reverse(cls.complement(ref)),
    )

    return f.when(
        ~cls.is_strand_ambiguous(ref, alt),
        f.array(
            f.struct(
                forward_direct.alias("variantId"),
                f.lit(Direction.DIRECT.value).cast(t.ByteType()).alias("direction"),
                f.lit(Strand.FORWARD.value).cast(t.ByteType()).alias("strand"),
                f.lit(False).alias("isStrandAmbiguous"),
                af.alias("originalAlleleFrequencies"),
            ),
            f.struct(
                forward_flipped.alias("variantId"),
                f.lit(Direction.FLIPPED.value)
                .cast(t.ByteType())
                .alias("direction"),
                f.lit(Strand.FORWARD.value).cast(t.ByteType()).alias("strand"),
                f.lit(False).alias("isStrandAmbiguous"),
                af.alias("originalAlleleFrequencies"),
            ),
            f.struct(
                reverse_direct.alias("variantId"),
                f.lit(Direction.DIRECT.value).cast(t.ByteType()).alias("direction"),
                f.lit(Strand.REVERSE.value).cast(t.ByteType()).alias("strand"),
                f.lit(False).alias("isStrandAmbiguous"),
                af.alias("originalAlleleFrequencies"),
            ),
            f.struct(
                reverse_flipped.alias("variantId"),
                f.lit(Direction.FLIPPED.value)
                .cast(t.ByteType())
                .alias("direction"),
                f.lit(Strand.REVERSE.value).cast(t.ByteType()).alias("strand"),
                f.lit(False).alias("isStrandAmbiguous"),
                af.alias("originalAlleleFrequencies"),
            ),
        ),
    ).otherwise(
        f.array(
            f.struct(
                forward_direct.alias("variantId"),
                f.lit(Direction.DIRECT.value).cast(t.ByteType()).alias("direction"),
                f.lit(Strand.FORWARD.value).cast(t.ByteType()).alias("strand"),
                f.lit(True).alias("isStrandAmbiguous"),
                af.alias("originalAlleleFrequencies"),
            ),
            f.struct(
                forward_flipped.alias("variantId"),
                f.lit(Direction.FLIPPED.value)
                .cast(t.ByteType())
                .alias("direction"),
                f.lit(Strand.FORWARD.value).cast(t.ByteType()).alias("strand"),
                f.lit(True).alias("isStrandAmbiguous"),
                af.alias("originalAlleleFrequencies"),
            ),
        )
    )

complement(allele: Column) -> Column staticmethod

Complement the allele string.

Parameters:

Name Type Description Default
allele Column

Allele column.

required

Returns:

Name Type Description
Column Column

Complemented allele column.

Examples:

>>> data = [("A",), ("C",), ("G",), ("T",), ("AT",), ("GTC",)]
>>> schema = "allele STRING"
>>> df = spark.createDataFrame(data, schema)
>>> df.withColumn("complemented", VariantDirection.complement(f.col("allele"))).show()
+------+------------+
|allele|complemented|
+------+------------+
|     A|           T|
|     C|           G|
|     G|           C|
|     T|           A|
|    AT|          TA|
|   GTC|         CAG|
+------+------------+
Source code in src/gentropy/dataset/variant_direction.py
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
@staticmethod
def complement(allele: Column) -> Column:
    """Complement the allele string.

    Args:
        allele (Column): Allele column.

    Returns:
        Column: Complemented allele column.

    Examples:
        >>> data = [("A",), ("C",), ("G",), ("T",), ("AT",), ("GTC",)]
        >>> schema = "allele STRING"
        >>> df = spark.createDataFrame(data, schema)
        >>> df.withColumn("complemented", VariantDirection.complement(f.col("allele"))).show()
        +------+------------+
        |allele|complemented|
        +------+------------+
        |     A|           T|
        |     C|           G|
        |     G|           C|
        |     T|           A|
        |    AT|          TA|
        |   GTC|         CAG|
        +------+------------+
        <BLANKLINE>

    """
    return f.translate(f.upper(allele), "ACGT", "TGCA")

from_variant_index(variant_index: VariantIndex) -> VariantDirection classmethod

Prepare the variant direction DataFrame with DIRECT and FLIPPED entries.

Parameters:

Name Type Description Default
variant_index VariantIndex

Variant index dataset.

required

Returns:

Name Type Description
VariantDirection VariantDirection

Variant direction dataset.

Source code in src/gentropy/dataset/variant_direction.py
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
@classmethod
def from_variant_index(cls, variant_index: VariantIndex) -> VariantDirection:
    """Prepare the variant direction DataFrame with DIRECT and FLIPPED entries.

    Args:
        variant_index (VariantIndex): Variant index dataset.

    Returns:
        VariantDirection: Variant direction dataset.
    """
    lut = variant_index.df.select(
        f.col("chromosome"),
        f.col("variantId").alias("originalVariantId"),
        cls.variant_type(f.col("referenceAllele"), f.col("alternateAllele")).alias(
            "type"
        ),
        f.explode(
            cls.alleles(
                f.col("chromosome"),
                f.col("position"),
                f.col("referenceAllele"),
                f.col("alternateAllele"),
                f.col("alleleFrequencies"),
            ).alias("alleles")
        ).alias("allele"),
    ).select(
        f.col("chromosome"),
        f.col("originalVariantId"),
        f.col("type"),
        f.col("allele.variantId").alias("variantId"),
        f.col("allele.direction").alias("direction"),
        f.col("allele.strand").alias("strand"),
        f.col("allele.isStrandAmbiguous").alias("isStrandAmbiguous"),
        f.col("allele.originalAlleleFrequencies").alias(
            "originalAlleleFrequencies"
        ),
    )

    return VariantDirection(_df=lut)

get_schema() -> t.StructType classmethod

Provides the schema for the variant index dataset.

Returns:

Type Description
StructType

t.StructType: Schema for the VariantIndex dataset

Source code in src/gentropy/dataset/variant_direction.py
110
111
112
113
114
115
116
117
@classmethod
def get_schema(cls: type[VariantDirection]) -> t.StructType:
    """Provides the schema for the variant index dataset.

    Returns:
        t.StructType: Schema for the VariantIndex dataset
    """
    return parse_spark_schema("variant_direction.json")

is_strand_ambiguous(ref: Column, alt: Column) -> Column classmethod

Check if the variant is strand ambiguous.

Parameters:

Name Type Description Default
ref Column

Reference allele column.

required
alt Column

Alternate allele column.

required

Returns:

Name Type Description
Column Column

Boolean column indicating if the variant is palindromic.

Examples:

>>> data = [("A", "T"), ("C", "G"), ("A", "G"), ("AC", "GT"), ("AT", "TA"), ("A", "AT")]
>>> schema = "ref STRING, alt STRING"
>>> df = spark.createDataFrame(data, schema)
>>> df.withColumn("isStrandAmbiguous", VariantDirection.is_strand_ambiguous(f.col("ref"), f.col("alt"))).show()
+---+---+-----------------+
|ref|alt|isStrandAmbiguous|
+---+---+-----------------+
|  A|  T|             true|
|  C|  G|             true|
|  A|  G|            false|
| AC| GT|             true|
| AT| TA|            false|
|  A| AT|            false|
+---+---+-----------------+
Source code in src/gentropy/dataset/variant_direction.py
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
@classmethod
def is_strand_ambiguous(cls, ref: Column, alt: Column) -> Column:
    """Check if the variant is strand ambiguous.

    Args:
        ref (Column): Reference allele column.
        alt (Column): Alternate allele column.

    Returns:
        Column: Boolean column indicating if the variant is palindromic.

    Examples:
        >>> data = [("A", "T"), ("C", "G"), ("A", "G"), ("AC", "GT"), ("AT", "TA"), ("A", "AT")]
        >>> schema = "ref STRING, alt STRING"
        >>> df = spark.createDataFrame(data, schema)
        >>> df.withColumn("isStrandAmbiguous", VariantDirection.is_strand_ambiguous(f.col("ref"), f.col("alt"))).show()
        +---+---+-----------------+
        |ref|alt|isStrandAmbiguous|
        +---+---+-----------------+
        |  A|  T|             true|
        |  C|  G|             true|
        |  A|  G|            false|
        | AC| GT|             true|
        | AT| TA|            false|
        |  A| AT|            false|
        +---+---+-----------------+
        <BLANKLINE>

    """
    ref_len = f.length(ref)
    alt_len = f.length(alt)
    ref = f.upper(ref)
    alt = f.upper(alt)
    return f.when(
        (ref_len == alt_len) & (cls.reverse(cls.complement(alt)) == ref), True
    ).otherwise(False)

reverse(allele: Column) -> Column staticmethod

Reverse the allele string.

Parameters:

Name Type Description Default
allele Column

Allele column.

required

Returns:

Name Type Description
Column Column

Reversed allele column.

Examples:

>>> data = [("A",), ("AT",), ("GTC",)]
>>> schema = "allele STRING"
>>> df = spark.createDataFrame(data, schema)
>>> df.withColumn("reversed", VariantDirection.reverse(f.col("allele"))).show()
+------+--------+
|allele|reversed|
+------+--------+
|     A|       A|
|    AT|      TA|
|   GTC|     CTG|
+------+--------+
Source code in src/gentropy/dataset/variant_direction.py
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
@staticmethod
def reverse(allele: Column) -> Column:
    """Reverse the allele string.

    Args:
        allele (Column): Allele column.

    Returns:
        Column: Reversed allele column.

    Examples:
        >>> data = [("A",), ("AT",), ("GTC",)]
        >>> schema = "allele STRING"
        >>> df = spark.createDataFrame(data, schema)
        >>> df.withColumn("reversed", VariantDirection.reverse(f.col("allele"))).show()
        +------+--------+
        |allele|reversed|
        +------+--------+
        |     A|       A|
        |    AT|      TA|
        |   GTC|     CTG|
        +------+--------+
        <BLANKLINE>

    """
    return f.reverse(allele)

variant_id(chrom: Column, pos: Column, ref: Column, alt: Column) -> Column classmethod

Get the variant id.

Parameters:

Name Type Description Default
chrom Column

Chromosome column.

required
pos Column

Position column.

required
ref Column

Reference allele column.

required
alt Column

Alternate allele column.

required

Returns:

Name Type Description
Column Column

Variant ID column in the format "chrom_pos_ref_alt".

Source code in src/gentropy/dataset/variant_direction.py
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
@classmethod
def variant_id(cls, chrom: Column, pos: Column, ref: Column, alt: Column) -> Column:
    """Get the variant id.

    Args:
        chrom (Column): Chromosome column.
        pos (Column): Position column.
        ref (Column): Reference allele column.
        alt (Column): Alternate allele column.

    Returns:
        Column: Variant ID column in the format "chrom_pos_ref_alt".
    """
    ref = f.upper(ref)
    alt = f.upper(alt)
    return f.concat_ws("_", chrom, pos, ref, alt)

variant_type(ref: Column, alt: Column) -> Column classmethod

Get the variant type.

Parameters:

Name Type Description Default
ref Column

Reference allele column.

required
alt Column

Alternate allele column.

required

Returns:

Name Type Description
Column Column

Variant type column.

Note

Variant type coding follows VariantType enum: - 1: SNP (Single Nucleotide Polymorphism) - 2: INS (Insertion) - 3: DEL (Deletion) - 4: MNP (Multi-Nucleotide Polymorphism)

Examples:

>>> data = [("A", "G"), ("A", "AT"), ("AT", "A"), ("AT", "GC")]
>>> schema = "ref STRING, alt STRING"
>>> df = spark.createDataFrame(data, schema)
>>> df.withColumn("type", VariantDirection.variant_type(f.col("ref"), f.col("alt"))).show()
+---+---+----+
|ref|alt|type|
+---+---+----+
|  A|  G|   1|
|  A| AT|   2|
| AT|  A|   3|
| AT| GC|   4|
+---+---+----+
Source code in src/gentropy/dataset/variant_direction.py
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
@classmethod
def variant_type(cls, ref: Column, alt: Column) -> Column:
    """Get the variant type.

    Args:
        ref (Column): Reference allele column.
        alt (Column): Alternate allele column.

    Returns:
        Column: Variant type column.

    Note:
        Variant type coding follows VariantType enum:
        - 1: SNP (Single Nucleotide Polymorphism)
        - 2: INS (Insertion)
        - 3: DEL (Deletion)
        - 4: MNP (Multi-Nucleotide Polymorphism)

    Examples:
        >>> data = [("A", "G"), ("A", "AT"), ("AT", "A"), ("AT", "GC")]
        >>> schema = "ref STRING, alt STRING"
        >>> df = spark.createDataFrame(data, schema)
        >>> df.withColumn("type", VariantDirection.variant_type(f.col("ref"), f.col("alt"))).show()
        +---+---+----+
        |ref|alt|type|
        +---+---+----+
        |  A|  G|   1|
        |  A| AT|   2|
        | AT|  A|   3|
        | AT| GC|   4|
        +---+---+----+
        <BLANKLINE>
    """
    ref = f.upper(ref)
    alt = f.upper(alt)
    expr = (
        f.when((f.length(alt) > f.length(ref)), f.lit(VariantType.INS.value))
        .when((f.length(alt) < f.length(ref)), f.lit(VariantType.DEL.value))
        .when(
            ((f.length(alt) == 1) & (f.length(ref) == 1)),
            f.lit(VariantType.SNP.value),
        )
        .otherwise(f.lit(VariantType.MNP.value))
    )
    return expr.cast(t.ByteType())

Schema

root
 |-- chromosome: string (nullable = true)
 |-- originalVariantId: string (nullable = false)
 |-- type: byte (nullable = false)
 |-- variantId: string (nullable = false)
 |-- direction: byte (nullable = false)
 |-- strand: byte (nullable = false)
 |-- isStrandAmbiguous: boolean (nullable = false)
 |-- originalAlleleFrequencies: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- populationName: string (nullable = true)
 |    |    |-- alleleFrequency: double (nullable = true)