Skip to content

obj

Define Sake dataclass.

Classes:

  • Sake

    Class that let user extract variants from sake.

Sake dataclass

Sake(
    *,
    sake_path: Path,
    threads: int | None = cpu_count(),
    activate_tqdm: bool | None = False,
    aggregations_path: Path | None = None,
    annotations_path: Path | None = None,
    partitions_path: Path | None = None,
    prescriptions_path: Path | None = None,
    samples_path: Path | None = None,
    transmissions_path: Path | None = None,
    variants_path: Path | None = None
)

Class that let user extract variants from sake.

Methods:

add_annotations

add_annotations(
    variants: DataFrame,
    name: str,
    version: str,
    *,
    rename_column: bool = True,
    select_columns: list[str] | None = None
) -> DataFrame

Add annotations to variants.

Require id column in variants value

Source code in src/sake/obj.py
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
def add_annotations(
    self,
    variants: polars.DataFrame,
    name: str,
    version: str,
    *,
    rename_column: bool = True,
    select_columns: list[str] | None = None,
) -> polars.DataFrame:
    """Add annotations to variants.

    Require `id` column in variants value
    """
    # annotations_path are set in __post_init__
    annotation_path = self.annotations_path / f"{name}" / f"{version}"  # type: ignore[operator]

    schema = polars.read_parquet_schema(annotation_path / "1.parquet")
    if "id" in schema:
        del schema["id"]
    columns = ",".join([f"a.{col}" for col in schema if select_columns is None or col in select_columns])

    all_annotations = []
    iterator = (
        tqdm(variants.group_by(["chr"]), total=variants.get_column("chr").unique().len())
        if self.activate_tqdm
        else variants.group_by(["chr"])
    )

    query = f"""
    select
        v.*, {columns}
    from
        _data as v
    left join
        read_parquet($path) as a
    on
        v.id == a.id
    """  # noqa: S608 we accept risk of sql inject

    for (chrom, *_), _data in iterator:
        if not (annotation_path / f"{chrom}.parquet").is_file():
            continue

        result = self.db.execute(
            query,
            {
                "path": str(annotation_path / f"{chrom}.parquet"),
            },
        ).pl()

        all_annotations.append(result)

    result = polars.concat(all_annotations)

    if rename_column:
        result = result.rename(
            {col: f"{name}_{col}" for col in schema if select_columns is None or col in select_columns},
        )

    return result

add_genotypes

add_genotypes(
    variants: DataFrame,
    target: str,
    *,
    keep_id_part: bool = False,
    drop_column: list[str] | None = None,
    number_of_bits: int = 8
) -> DataFrame

Add genotype information to variants DataFrame.

Require id column in variants value

Source code in src/sake/obj.py
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
def add_genotypes(
    self,
    variants: polars.DataFrame,
    target: str,
    *,
    keep_id_part: bool = False,
    drop_column: list[str] | None = None,
    number_of_bits: int = 8,
) -> polars.DataFrame:
    """Add genotype information to variants DataFrame.

    Require `id` column in variants value
    """
    variants = sake.utils.add_id_part(variants, number_of_bits=number_of_bits)
    path_with_target = pathlib.Path(str(self.partitions_path).format(target=target))

    if drop_column is None:
        drop_column = []

    if not keep_id_part:
        drop_column.append("id_part")

    all_genotypes = []
    iterator = (
        tqdm(variants.group_by(["id_part"]), total=variants.get_column("id_part").unique().len())
        if self.activate_tqdm
        else variants.group_by(["id_part"])
    )

    for (id_part, *_), _data in iterator:
        part_path = path_with_target / f"id_part={id_part}/0.parquet"

        if not part_path.is_file():
            continue

        query = """
        select
            v.*, g.sample, g.gt, g.ad, g.dp, g.gq
        from
            _data as v
        left join
            read_parquet($path) as g
        on
            v.id == g.id
        """

        result = (
            self.db.execute(
                query,
                {
                    "path": str(part_path),
                },
            )
            .pl()
            .with_columns(
                ad=polars.col("ad").cast(polars.List(polars.String)).list.join(","),
            )
            .drop(drop_column)
        )

        all_genotypes.append(result)

    return polars.concat(all_genotypes)

add_sample_info

add_sample_info(
    _variants: DataFrame,
    *,
    select_columns: list[str] | None = None
) -> DataFrame

Add sample information.

Required sample column in polars.DataFrame.

Source code in src/sake/obj.py
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
def add_sample_info(
    self,
    _variants: polars.DataFrame,
    *,
    select_columns: list[str] | None = None,
) -> polars.DataFrame:
    """Add sample information.

    Required sample column in polars.DataFrame.
    """
    # sampless_path are set in __post_init__
    schema = polars.read_parquet_schema(self.samples_path)  # type: ignore[arg-type]

    if select_columns is None:
        select_columns = [col for col in schema if col != "sample"]

    columns = ",".join([f"s.{col}" for col in schema if col in select_columns])

    query = f"""
    select
        v.*, {columns}
    from
        _variants as v
    left join
        read_parquet($path) as s
    on
        v.sample == s.sample
    """  # noqa: S608 we accept risk of sql inject

    return self.db.execute(
        query,
        {
            "path": str(self.samples_path),
        },
    ).pl()

add_transmissions

add_transmissions(variants: DataFrame) -> DataFrame

Add transmissions information.

Required pid_crc column in polars.DataFrame.

Source code in src/sake/obj.py
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
def add_transmissions(
    self,
    variants: polars.DataFrame,
) -> polars.DataFrame:
    """Add transmissions information.

    Required pid_crc column in polars.DataFrame.
    """
    all_transmissions = []

    input_columns = ",".join([f"v.{col}" for col in variants.schema if col != "id"])

    iterator = (
        tqdm(variants.group_by(["pid_crc"]), total=variants.get_column("pid_crc").unique().len())
        if self.activate_tqdm
        else variants.group_by(["pid_crc"])
    )

    query = f"""
    select
        {input_columns}, t.*
    from
        _data as v
    left join
        read_parquet($path) as t
    on
        v.id == t.id
    where
        v.kindex == True
    """  # noqa: S608 we accept risk of sql inject

    for (pid_crc, *_), _data in iterator:
        path = pathlib.Path(str(self.transmissions_path).format(target="germline")) / f"{pid_crc}.parquet"

        if not path.is_file():
            continue

        result = (
            self.db.execute(
                query,
                {
                    "path": str(path),
                },
            )
            .pl()
            .cast(
                {
                    "father_gt": polars.UInt8,
                    "mother_gt": polars.UInt8,
                    "index_gt": polars.UInt8,
                    "father_dp": polars.UInt32,
                    "mother_dp": polars.UInt32,
                    "father_gq": polars.UInt32,
                    "mother_gq": polars.UInt32,
                },
            )
            .with_columns(
                father_ad=polars.col("father_ad").cast(polars.List(polars.String)).list.join(","),
                mother_ad=polars.col("mother_ad").cast(polars.List(polars.String)).list.join(","),
                index_ad=polars.col("index_ad").cast(polars.List(polars.String)).list.join(","),
            )
        )

        all_transmissions.append(result)

    return polars.concat(all_transmissions)

add_variants

add_variants(_data: DataFrame, target: str) -> DataFrame

Use id of column polars.DataFrame to get variant information.

Source code in src/sake/obj.py
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
def add_variants(self, _data: polars.DataFrame, target: str) -> polars.DataFrame:
    """Use id of column polars.DataFrame to get variant information."""
    query = """
    select
        v.chr, v.pos, v.ref, v.alt, d.*
    from
        read_parquet($path) as v
    join
        _data as d
    on
        v.id == d.id
    """

    return self.db.execute(
        query,
        {
            "path": sake.utils.fix_variants_path(self.variants_path, target),  # type: ignore[arg-type]
        },
    ).pl()

all_variants

all_variants(target: str) -> DataFrame

Get all variants of a target in present in Sake.

Source code in src/sake/obj.py
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def all_variants(self, target: str) -> polars.DataFrame:
    """Get all variants of a target in present in Sake."""
    query = """
    select
        v.id, v.chr, v.pos, v.ref, v.alt
    from
        read_parquet($path) as v
    """

    return self.db.execute(
        query,
        {
            "path": sake.utils.fix_variants_path(self.variants_path, target, None),  # type: ignore[arg-type]
        },
    ).pl()

get_annotations

get_annotations(
    name: str,
    version: str,
    target: str,
    *,
    rename_column: bool = True,
    select_columns: list[str] | None = None
) -> DataFrame

Get all variants of an annotations.

Source code in src/sake/obj.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
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
def get_annotations(
    self,
    name: str,
    version: str,
    target: str,
    *,
    rename_column: bool = True,
    select_columns: list[str] | None = None,
) -> polars.DataFrame:
    """Get all variants of an annotations."""
    annotation_path = self.annotations_path / f"{name}" / f"{version}"  # type: ignore[operator]

    schema = polars.read_parquet_schema(annotation_path / "1.parquet")
    chromosomes_list = [
        entry.name.split(".")[0]
        for entry in os.scandir(annotation_path)
        if entry.is_file() and entry.name.endswith(".parquet")
    ]

    if "id" in schema:
        del schema["id"]
        columns = ",".join([f"a.{col}" for col in schema if select_columns is None or col in select_columns])

    query = f"""
    select
        v.*, {columns}
    from
        read_parquet($annotation_path) as a
    join
        read_parquet($variant_path) as v
    on
        v.id = a.id
    """  # noqa: S608 we accept risk of sql inject

    all_annotations = []
    iterator = tqdm(chromosomes_list) if self.activate_tqdm else chromosomes_list
    for chrom in iterator:
        result = self.db.execute(
            query,
            {
                "annotation_path": str(
                    self.annotations_path / f"{name}" / f"{version}" / f"{chrom}.parquet",  # type: ignore[operator]
                ),
                "variant_path": sake.utils.fix_variants_path(self.variants_path, target),  # type: ignore[arg-type]
            },
        ).pl()

        all_annotations.append(result)

    result = polars.concat(all_annotations)

    if rename_column:
        result = result.rename(
            {col: f"{name}_{col}" for col in schema if select_columns is None or col in select_columns},
        )

    return result

get_interval

get_interval(
    target: str, chrom: str, start: int, stop: int
) -> DataFrame

Get variants from chromosome between start and stop.

Source code in src/sake/obj.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
def get_interval(self, target: str, chrom: str, start: int, stop: int) -> polars.DataFrame:
    """Get variants from chromosome between start and stop."""
    query = """
    select
        v.id, v.chr, v.pos, v.ref, v.alt
    from
        read_parquet($path) as v
    where
        v.chr == $chrom
    and
        v.pos > $start
    and
        v.pos < $stop
    """

    return self.db.execute(
        query,
        {
            "path": sake.utils.fix_variants_path(self.variants_path, target, chrom),  # type: ignore[arg-type]
            "chrom": chrom,
            "start": start,
            "stop": stop,
        },
    ).pl()

get_intervals

get_intervals(
    target: str,
    chroms: list[str],
    starts: list[int],
    stops: list[int],
) -> DataFrame

Get variants in multiple intervals.

Source code in src/sake/obj.py
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
def get_intervals(self, target: str, chroms: list[str], starts: list[int], stops: list[int]) -> polars.DataFrame:
    """Get variants in multiple intervals."""
    all_variants = []
    minimal_length = min(len(chroms), len(starts), len(stops))
    iterator = (
        tqdm(zip(chroms, zip(starts, stops)), total=minimal_length)
        if self.activate_tqdm
        else zip(chroms, zip(starts, stops))
    )

    for chrom, (start, stop) in iterator:
        all_variants.append(
            self.get_interval(target, chrom, start, stop),
        )

    return polars.concat(all_variants)

get_variant_of_prescription

get_variant_of_prescription(
    prescription: str, target: str
) -> DataFrame

Get all variants of a prescription.

Source code in src/sake/obj.py
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
def get_variant_of_prescription(self, prescription: str, target: str) -> polars.DataFrame:
    """Get all variants of a prescription."""
    query = """
    select
        v.chr, v.pos, v.ref, v.alt, g.*
    from
        read_parquet($sample_path) as g
    join
        read_parquet($variant_path) as v
    on
        v.id = g.id
    """

    return self.db.execute(
        query,
        {
            "sample_path": str(
                pathlib.Path(str(self.prescriptions_path).format(target=target)) / f"{prescription}.parquet",
            ),
            "variant_path": sake.utils.fix_variants_path(self.variants_path, target),  # type: ignore[arg-type]
        },
    ).pl()

get_variant_of_prescriptions

get_variant_of_prescriptions(
    prescriptions: list[str], target: str
) -> DataFrame

Get all variants of multiple prescriptions.

Source code in src/sake/obj.py
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
def get_variant_of_prescriptions(self, prescriptions: list[str], target: str) -> polars.DataFrame:
    """Get all variants of multiple prescriptions."""
    query = """
    select
        v.chr, v.pos, v.ref, v.alt, g.*
    from
        read_parquet($sample_path) as g
    join
        read_parquet($variant_path) as v
    on
        v.id = g.id
    """

    iterator = tqdm(prescriptions) if self.activate_tqdm else prescriptions

    all_variants = []
    for pid in iterator:
        all_variants.append(
            self.db.execute(
                query,
                {
                    "sample_path": str(
                        pathlib.Path(str(self.prescriptions_path).format(target=target)) / f"{pid}.parquet",
                    ),
                    "variant_path": sake.utils.fix_variants_path(self.variants_path, target),  # type: ignore[arg-type]
                },
            ).pl(),
        )

    return polars.concat(all_variants)