aboutsummaryrefslogtreecommitdiff
path: root/gn3/db/partial_correlations.py
blob: 72dbf1a932c8ad1f911282995537d645c6d83e64 (plain)
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
"""
This module contains the code and queries for fetching data from the database,
that relates to partial correlations.

It is intended to replace the functions in `gn3.db.traits` and `gn3.db.datasets`
modules with functions that fetch the data enmasse, rather than one at a time.

This module is part of the optimisation effort for the partial correlations.
"""

from functools import reduce, partial
from typing import Any, Dict, Tuple, Union, Sequence

from MySQLdb.cursors import DictCursor

from gn3.function_helpers import  compose
from gn3.db.traits import (
    build_trait_name,
    with_samplelist_data_setup,
    without_samplelist_data_setup)

def organise_trait_data_by_trait(
        traits_data_rows: Tuple[Dict[str, Any], ...]) -> Dict[
            str, Dict[str, Any]]:
    """
    Organise the trait data items by their trait names.
    """
    def __organise__(acc, row):
        trait_name = row["trait_name"]
        return {
            **acc,
            trait_name: acc.get(trait_name, tuple()) + ({
                key: val for key, val in row.items() if key != "trait_name"},)
        }
    if traits_data_rows:
        return reduce(__organise__, traits_data_rows, {})
    return {}

def temp_traits_data(conn, traits):
    """
    Retrieve trait data for `Temp` traits.
    """
    query = (
        "SELECT "
        "Temp.Name AS trait_name, Strain.Name AS sample_name, TempData.value, "
        "TempData.SE AS se_error, TempData.NStrain AS nstrain, "
        "TempData.Id AS id "
        "FROM TempData, Temp, Strain "
        "WHERE TempData.StrainId = Strain.Id "
        "AND TempData.Id = Temp.DataId "
        f"AND Temp.name IN ({', '.join(['%s'] * len(traits))}) "
        "ORDER BY Strain.Name")
    with conn.cursor(cursorclass=DictCursor) as cursor:
        cursor.execute(
            query,
            tuple(trait["trait_name"] for trait in traits))
        return organise_trait_data_by_trait(cursor.fetchall())
    return {}

def publish_traits_data(conn, traits):
    """
    Retrieve trait data for `Publish` traits.
    """
    dataset_ids = tuple(set(
        trait["db"]["dataset_id"] for trait in traits
        if trait["db"].get("dataset_id") is not None))
    query = (
        "SELECT "
        "PublishXRef.Id AS trait_name, Strain.Name AS sample_name, "
        "PublishData.value, PublishSE.error AS se_error, "
        "NStrain.count AS nstrain, PublishData.Id AS id "
        "FROM (PublishData, Strain, PublishXRef, PublishFreeze) "
        "LEFT JOIN PublishSE "
        "ON (PublishSE.DataId = PublishData.Id "
        "AND PublishSE.StrainId = PublishData.StrainId) "
        "LEFT JOIN NStrain "
        "ON (NStrain.DataId = PublishData.Id "
        "AND NStrain.StrainId = PublishData.StrainId) "
        "WHERE PublishXRef.InbredSetId = PublishFreeze.InbredSetId "
        "AND PublishData.Id = PublishXRef.DataId "
        f"AND PublishXRef.Id  IN ({', '.join(['%s'] * len(traits))}) "
        "AND PublishFreeze.Id IN "
        f"({', '.join(['%s'] * len(dataset_ids))}) "
        "AND PublishData.StrainId = Strain.Id "
        "ORDER BY Strain.Name")
    if len(dataset_ids) > 0:
        with conn.cursor(cursorclass=DictCursor) as cursor:
            cursor.execute(
                query,
                tuple(trait["trait_name"] for trait in traits) +
                tuple(dataset_ids))
            return organise_trait_data_by_trait(cursor.fetchall())
    return {}

def cellid_traits_data(conn, traits):
    """
    Retrieve trait data for `Probe Data` types.
    """
    cellids = tuple(trait["cellid"] for trait in traits)
    dataset_names = set(trait["db"]["dataset_name"] for trait in traits)
    query = (
        "SELECT "
        "ProbeSet.Name AS trait_name, Strain.Name AS sample_name, "
        "ProbeData.value, ProbeSE.error AS se_error, ProbeData.Id AS id "
        "FROM (ProbeData, ProbeFreeze, ProbeSetFreeze, ProbeXRef, Strain, "
        "Probe, ProbeSet) "
        "LEFT JOIN ProbeSE "
        "ON (ProbeSE.DataId = ProbeData.Id "
        "AND ProbeSE.StrainId = ProbeData.StrainId) "
        f"WHERE Probe.Name IN ({', '.join(['%s'] * len(cellids))}) "
        f"AND ProbeSet.Name IN ({', '.join(['%s'] * len(traits))}) "
        "AND Probe.ProbeSetId = ProbeSet.Id "
        "AND ProbeXRef.ProbeId = Probe.Id "
        "AND ProbeXRef.ProbeFreezeId = ProbeFreeze.Id "
        "AND ProbeSetFreeze.ProbeFreezeId = ProbeFreeze.Id "
        f"AND ProbeSetFreeze.Name IN ({', '.join(['%s'] * len(dataset_names))}) "
        "AND ProbeXRef.DataId = ProbeData.Id "
        "AND ProbeData.StrainId = Strain.Id "
        "ORDER BY Strain.Name")
    with conn.cursor(cursorclass=DictCursor) as cursor:
        cursor.execute(
            query,
            cellids + tuple(trait["trait_name"] for trait in traits) +
            tuple(dataset_names))
        return organise_trait_data_by_trait(cursor.fetchall())
    return {}

def probeset_traits_data(conn, traits):
    """
    Retrieve trait data for `ProbeSet` traits.
    """
    dataset_names = set(trait["db"]["dataset_name"] for trait in traits)
    query = (
        "SELECT ProbeSet.Name AS trait_name, Strain.Name AS sample_name, "
        "ProbeSetData.value, ProbeSetSE.error AS se_error, "
        "ProbeSetData.Id AS id "
        "FROM (ProbeSetData, ProbeSetFreeze, Strain, ProbeSet, ProbeSetXRef) "
        "LEFT JOIN ProbeSetSE ON "
        "(ProbeSetSE.DataId = ProbeSetData.Id "
        "AND ProbeSetSE.StrainId = ProbeSetData.StrainId) "
        f"WHERE ProbeSet.Name IN ({', '.join(['%s'] * len(traits))})"
        "AND ProbeSetXRef.ProbeSetId = ProbeSet.Id "
        "AND ProbeSetXRef.ProbeSetFreezeId = ProbeSetFreeze.Id "
        f"AND ProbeSetFreeze.Name IN ({', '.join(['%s']*len(dataset_names))}) "
        "AND ProbeSetXRef.DataId = ProbeSetData.Id "
        "AND ProbeSetData.StrainId = Strain.Id "
        "ORDER BY Strain.Name")
    with conn.cursor(cursorclass=DictCursor) as cursor:
        cursor.execute(
            query,
            tuple(trait["trait_name"] for trait in traits) +
            tuple(dataset_names))
        return organise_trait_data_by_trait(cursor.fetchall())
    return {}

def species_ids(conn, traits):
    """
    Retrieve the IDS of the related species from the given list of traits.
    """
    groups = tuple(set(
        trait["db"]["group"] for trait in traits
        if trait["db"].get("group") is not None))
    query = (
        "SELECT Name AS `group`, SpeciesId AS species_id "
        "FROM InbredSet "
        f"WHERE Name IN ({', '.join(['%s'] * len(groups))})")
    if len(groups) > 0:
        with conn.cursor(cursorclass=DictCursor) as cursor:
            cursor.execute(query, groups)
            return tuple(row for row in cursor.fetchall())
    return tuple()

def geno_traits_data(conn, traits):
    """
    Retrieve trait data for `Geno` traits.
    """
    sp_ids = tuple(item["species_id"] for item in species_ids(conn, traits))
    dataset_names = set(trait["db"]["dataset_name"] for trait in traits)
    query = (
        "SELECT Geno.Name AS trait_name, Strain.Name AS sample_name, "
        "GenoData.value, GenoSE.error AS se_error, GenoData.Id AS id "
        "FROM (GenoData, GenoFreeze, Strain, Geno, GenoXRef) "
        "LEFT JOIN GenoSE ON "
        "(GenoSE.DataId = GenoData.Id AND GenoSE.StrainId = GenoData.StrainId) "
        f"WHERE Geno.SpeciesId IN ({', '.join(['%s'] * len(sp_ids))}) "
        f"AND Geno.Name IN ({', '.join(['%s'] * len(traits))}) "
        "AND GenoXRef.GenoId = Geno.Id "
        "AND GenoXRef.GenoFreezeId = GenoFreeze.Id "
        f"AND GenoFreeze.Name IN ({', '.join(['%s'] * len(dataset_names))}) "
        "AND GenoXRef.DataId = GenoData.Id "
        "AND GenoData.StrainId = Strain.Id "
        "ORDER BY Strain.Name")
    if len(sp_ids) > 0 and len(dataset_names) > 0:
        with conn.cursor(cursorclass=DictCursor) as cursor:
            cursor.execute(
                query,
                sp_ids +
                tuple(trait["trait_name"] for trait in traits) +
                tuple(dataset_names))
            return organise_trait_data_by_trait(cursor.fetchall())
    return {}

def traits_data(
        conn: Any, traits: Tuple[Dict[str, Any], ...],
        samplelist: Tuple[str, ...] = tuple()) -> Dict[str, Dict[str, Any]]:
    """
    Retrieve trait data for multiple `traits`

    This is a rework of the `gn3.db.traits.retrieve_trait_data` function.
    """
    def __organise__(acc, trait):
        dataset_type = trait["db"]["dataset_type"]
        if dataset_type == "Temp":
            return {**acc, "Temp": acc.get("Temp", tuple()) + (trait,)}
        if dataset_type == "Publish":
            return {**acc, "Publish": acc.get("Publish", tuple()) + (trait,)}
        if trait.get("cellid"):
            return {**acc, "cellid": acc.get("cellid", tuple()) + (trait,)}
        if dataset_type == "ProbeSet":
            return {**acc, "ProbeSet": acc.get("ProbeSet", tuple()) + (trait,)}
        return {**acc, "Geno": acc.get("Geno", tuple()) + (trait,)}

    def __setup_samplelist__(data):
        if samplelist:
            return tuple(
                item for item in
                map(with_samplelist_data_setup(samplelist), data)
                if item is not None)
        return tuple(
            item for item in
            map(without_samplelist_data_setup(), data)
            if item is not None)

    def __process_results__(results):
        flattened = reduce(lambda acc, res: {**acc, **res}, results)
        return {
            trait_name: {"data": dict(map(
                lambda item: (
                    item["sample_name"],
                    {
                        key: val for key, val in item.items()
                        if item != "sample_name"
                    }),
                __setup_samplelist__(data)))}
            for trait_name, data in flattened.items()}

    traits_data_fns = {
        "Temp": temp_traits_data,
        "Publish": publish_traits_data,
        "cellid": cellid_traits_data,
        "ProbeSet": probeset_traits_data,
        "Geno": geno_traits_data
    }
    return __process_results__(tuple(# type: ignore[var-annotated]
        traits_data_fns[key](conn, vals)
        for key, vals in reduce(__organise__, traits, {}).items()))

def merge_traits_and_info(traits, info_results):
    """
    Utility to merge trait info retrieved from the database with the given traits.
    """
    if info_results:
        results = {
            str(trait["trait_name"]): trait for trait in info_results
        }
        return tuple(
            {
                **trait,
                **results.get(trait["trait_name"], {}),
                "haveinfo": bool(results.get(trait["trait_name"]))
            } for trait in traits)
    return tuple({**trait, "haveinfo": False} for trait in traits)

def publish_traits_info(
        conn: Any, traits: Tuple[Dict[str, Any], ...]) -> Tuple[
            Dict[str, Any], ...]:
    """
    Retrieve trait information for type `Publish` traits.

    This is a rework of `gn3.db.traits.retrieve_publish_trait_info` function:
    this one fetches multiple items in a single query, unlike the original that
    fetches one item per query.
    """
    trait_dataset_ids = set(
        trait["db"]["dataset_id"] for trait in traits
        if trait["db"].get("dataset_id") is not None)
    columns = (
        "PublishXRef.Id, Publication.PubMed_ID, "
        "Phenotype.Pre_publication_description, "
        "Phenotype.Post_publication_description, "
        "Phenotype.Original_description, "
        "Phenotype.Pre_publication_abbreviation, "
        "Phenotype.Post_publication_abbreviation, "
        "Phenotype.Lab_code, Phenotype.Submitter, Phenotype.Owner, "
        "Phenotype.Authorized_Users, "
        "CAST(Publication.Authors AS BINARY) AS Authors, Publication.Title, "
        "Publication.Abstract, Publication.Journal, Publication.Volume, "
        "Publication.Pages, Publication.Month, Publication.Year, "
        "PublishXRef.Sequence, Phenotype.Units, PublishXRef.comments")
    query = (
        "SELECT "
        f"PublishXRef.Id AS trait_name, {columns} "
        "FROM "
        "PublishXRef, Publication, Phenotype, PublishFreeze "
        "WHERE "
        f"PublishXRef.Id IN ({', '.join(['%s'] * len(traits))}) "
        "AND Phenotype.Id = PublishXRef.PhenotypeId "
        "AND Publication.Id = PublishXRef.PublicationId "
        "AND PublishXRef.InbredSetId = PublishFreeze.InbredSetId "
        "AND PublishFreeze.Id IN "
        f"({', '.join(['%s'] * len(trait_dataset_ids))})")
    if trait_dataset_ids:
        with conn.cursor(cursorclass=DictCursor) as cursor:
            cursor.execute(
                query,
                (
                    tuple(trait["trait_name"] for trait in traits) +
                    tuple(trait_dataset_ids)))
            return merge_traits_and_info(traits, cursor.fetchall())
    return tuple({**trait, "haveinfo": False} for trait in traits)

def probeset_traits_info(
        conn: Any, traits: Tuple[Dict[str, Any], ...]):
    """
    Retrieve information for the probeset traits
    """
    dataset_names = set(trait["db"]["dataset_name"] for trait in traits)
    columns = ", ".join(
        [f"ProbeSet.{x}" for x in
         ("name", "symbol", "description", "probe_target_description", "chr",
          "mb", "alias", "geneid", "genbankid", "unigeneid", "omim",
          "refseq_transcriptid", "blatseq", "targetseq", "chipid", "comments",
          "strand_probe", "strand_gene", "probe_set_target_region", "proteinid",
          "probe_set_specificity", "probe_set_blat_score",
          "probe_set_blat_mb_start", "probe_set_blat_mb_end",
          "probe_set_strand", "probe_set_note_by_rw", "flag")])
    query = (
        f"SELECT ProbeSet.Name AS trait_name, {columns} "
        "FROM ProbeSet INNER JOIN ProbeSetXRef "
        "ON ProbeSetXRef.ProbeSetId = ProbeSet.Id "
        "INNER JOIN ProbeSetFreeze "
        "ON ProbeSetFreeze.Id = ProbeSetXRef.ProbeSetFreezeId "
        "WHERE ProbeSetFreeze.Name IN "
        f"({', '.join(['%s'] * len(dataset_names))}) "
        f"AND ProbeSet.Name IN ({', '.join(['%s'] * len(traits))})")
    with conn.cursor(cursorclass=DictCursor) as cursor:
        cursor.execute(
            query,
            tuple(dataset_names) + tuple(
                trait["trait_name"] for trait in traits))
        return merge_traits_and_info(traits, cursor.fetchall())
    return tuple({**trait, "haveinfo": False} for trait in traits)

def geno_traits_info(
        conn: Any, traits: Tuple[Dict[str, Any], ...]):
    """
    Retrieve trait information for type `Geno` traits.

    This is a rework of the `gn3.db.traits.retrieve_geno_trait_info` function.
    """
    dataset_names = set(trait["db"]["dataset_name"] for trait in traits)
    columns = ", ".join([
        f"Geno.{x}" for x in ("name", "chr", "mb", "source2", "sequence")])
    query = (
        "SELECT "
        f"Geno.Name AS trait_name, {columns} "
        "FROM "
        "Geno INNER JOIN GenoXRef ON GenoXRef.GenoId = Geno.Id "
        "INNER JOIN GenoFreeze ON GenoFreeze.Id = GenoXRef.GenoFreezeId "
        f"WHERE GenoFreeze.Name IN ({', '.join(['%s'] * len(dataset_names))}) "
        f"AND Geno.Name IN ({', '.join(['%s'] * len(traits))})")
    with conn.cursor(cursorclass=DictCursor) as cursor:
        cursor.execute(
            query,
            tuple(dataset_names) + tuple(
                trait["trait_name"] for trait in traits))
        return merge_traits_and_info(traits, cursor.fetchall())
    return tuple({**trait, "haveinfo": False} for trait in traits)

def temp_traits_info(
        conn: Any, traits: Tuple[Dict[str, Any], ...]):
    """
    Retrieve trait information for type `Temp` traits.

    A rework of the `gn3.db.traits.retrieve_temp_trait_info` function.
    """
    query = (
        "SELECT Name as trait_name, name, description FROM Temp "
        f"WHERE Name IN ({', '.join(['%s'] * len(traits))})")
    with conn.cursor(cursorclass=DictCursor) as cursor:
        cursor.execute(
            query,
            tuple(trait["trait_name"] for trait in traits))
        return merge_traits_and_info(traits, cursor.fetchall())
    return tuple({**trait, "haveinfo": False} for trait in traits)

def publish_datasets_names(
        conn: Any, threshold: int, dataset_names: Tuple[str, ...]):
    """
    Get the ID, DataScale and various name formats for a `Publish` trait.

    Rework of the `gn3.db.datasets.retrieve_publish_trait_dataset_name`
    """
    query = (
        "SELECT DISTINCT "
        "Id AS dataset_id, Name AS dataset_name, FullName AS dataset_fullname, "
        "ShortName AS dataset_shortname "
        "FROM PublishFreeze "
        "WHERE "
        "public > %s "
        "AND "
        "(Name IN ({names}) OR FullName IN ({names}) OR ShortName IN ({names}))")
    with conn.cursor(cursorclass=DictCursor) as cursor:
        cursor.execute(
            query.format(names=", ".join(["%s"] * len(dataset_names))),
            (threshold,) +(dataset_names * 3))
        return {ds["dataset_name"]: ds for ds in cursor.fetchall()}
    return {}

def set_bxd(group_info):
    """Set the group value to BXD if it is 'BXD300'."""
    return {
        **group_info,
        "group": (
            "BXD" if group_info.get("Name") == "BXD300"
            else group_info.get("Name", "")),
        "groupid": group_info["Id"]
    }

def organise_groups_by_dataset(
        group_rows: Union[Sequence[Dict[str, Any]], None]) -> Dict[str, Any]:
    """Utility: Organise given groups by their datasets."""
    if group_rows:
        return {
            row["dataset_name"]: set_bxd({
                key: val for key, val in row.items()
                if key != "dataset_name"
            }) for row in group_rows
        }
    return {}

def publish_datasets_groups(conn: Any, dataset_names: Tuple[str]):
    """
    Retrieve the Group, and GroupID values for various Publish trait types.

    Rework of `gn3.db.datasets.retrieve_publish_group_fields` function.
    """
    query = (
        "SELECT PublishFreeze.Name AS dataset_name, InbredSet.Name, "
        "InbredSet.Id "
        "FROM InbredSet, PublishFreeze "
        "WHERE PublishFreeze.InbredSetId = InbredSet.Id "
        f"AND PublishFreeze.Name IN ({', '.join(['%s'] * len(dataset_names))})")
    with conn.cursor(cursorclass=DictCursor) as cursor:
        cursor.execute(query, tuple(dataset_names))
        return organise_groups_by_dataset(cursor.fetchall())
    return {}

def publish_traits_datasets(conn: Any, threshold, traits: Tuple[Dict]):
    """Retrieve datasets for 'Publish' traits."""
    dataset_names = tuple(set(trait["db"]["dataset_name"] for trait in traits))
    dataset_names_info = publish_datasets_names(conn, threshold, dataset_names)
    dataset_groups = publish_datasets_groups(conn, dataset_names) # type: ignore[arg-type]
    return tuple({
        **trait,
        "db": {
            **trait["db"],
            **dataset_names_info.get(trait["db"]["dataset_name"], {}),
            **dataset_groups.get(trait["db"]["dataset_name"], {})
        }
    } for trait in traits)

def probeset_datasets_names(conn: Any, threshold: int, dataset_names: Tuple[str, ...]):
    """
    Get the ID, DataScale and various name formats for a `ProbeSet` trait.
    """
    query = (
        "SELECT Id AS dataset_id, Name AS dataset_name, "
        "FullName AS dataset_fullname, ShortName AS dataset_shortname, "
        "DataScale AS dataset_datascale "
        "FROM ProbeSetFreeze "
        "WHERE "
        "public > %s "
        "AND "
        "(Name IN ({names}) OR FullName IN ({names}) OR ShortName IN ({names}))")
    with conn.cursor(cursorclass=DictCursor) as cursor:
        cursor.execute(
            query.format(names=", ".join(["%s"] * len(dataset_names))),
            (threshold,) +(dataset_names * 3))
        return {ds["dataset_name"]: ds for ds in cursor.fetchall()}
    return {}

def probeset_datasets_groups(conn, dataset_names):
    """
    Retrieve the Group, and GroupID values for various ProbeSet trait types.
    """
    query = (
        "SELECT ProbeSetFreeze.Name AS dataset_name, InbredSet.Name, "
        "InbredSet.Id "
        "FROM InbredSet, ProbeSetFreeze, ProbeFreeze "
        "WHERE ProbeFreeze.InbredSetId = InbredSet.Id "
        "AND ProbeFreeze.Id = ProbeSetFreeze.ProbeFreezeId "
        f"AND ProbeSetFreeze.Name IN ({', '.join(['%s'] * len(dataset_names))})")
    with conn.cursor(cursorclass=DictCursor) as cursor:
        cursor.execute(query, tuple(dataset_names))
        return organise_groups_by_dataset(cursor.fetchall())
    return {}

def probeset_traits_datasets(conn: Any, threshold, traits: Tuple[Dict]):
    """Retrive datasets for 'ProbeSet' traits."""
    dataset_names = tuple(set(trait["db"]["dataset_name"] for trait in traits))
    dataset_names_info = probeset_datasets_names(conn, threshold, dataset_names)
    dataset_groups = probeset_datasets_groups(conn, dataset_names)
    return tuple({
        **trait,
        "db": {
            **trait["db"],
            **dataset_names_info.get(trait["db"]["dataset_name"], {}),
            **dataset_groups.get(trait["db"]["dataset_name"], {})
        }
    } for trait in traits)

def geno_datasets_names(conn, threshold, dataset_names):
    """
    Get the ID, DataScale and various name formats for a `Geno` trait.
    """
    query = (
        "SELECT Id AS dataset_id, Name AS dataset_name, "
        "FullName AS dataset_fullname, ShortName AS dataset_short_name "
        "FROM GenoFreeze "
        "WHERE "
        "public > %s "
        "AND "
        "(Name IN ({names}) OR FullName IN ({names}) OR ShortName IN ({names}))")
    with conn.cursor(cursorclass=DictCursor) as cursor:
        cursor.execute(
            query.format(names=", ".join(["%s"] * len(dataset_names))),
            (threshold,) + (tuple(dataset_names) * 3))
        return {ds["dataset_name"]: ds for ds in cursor.fetchall()}
    return {}

def geno_datasets_groups(conn, dataset_names):
    """
    Retrieve the Group, and GroupID values for various Geno trait types.
    """
    query = (
        "SELECT GenoFreeze.Name AS dataset_name, InbredSet.Name, InbredSet.Id "
        "FROM InbredSet, GenoFreeze "
        "WHERE GenoFreeze.InbredSetId = InbredSet.Id "
        f"AND GenoFreeze.Name IN ({', '.join(['%s'] * len(dataset_names))})")
    with conn.cursor(cursorclass=DictCursor) as cursor:
        cursor.execute(query, tuple(dataset_names))
        return organise_groups_by_dataset(cursor.fetchall())
    return {}

def geno_traits_datasets(conn: Any, threshold: int, traits: Tuple[Dict]):
    """Retrieve datasets for 'Geno' traits."""
    dataset_names = tuple(set(trait["db"]["dataset_name"] for trait in traits))
    dataset_names_info = geno_datasets_names(conn, threshold, dataset_names)
    dataset_groups = geno_datasets_groups(conn, dataset_names)
    return tuple({
        **trait,
        "db": {
            **trait["db"],
            **dataset_names_info.get(trait["db"]["dataset_name"], {}),
            **dataset_groups.get(trait["db"]["dataset_name"], {})
        }
    } for trait in traits)

def temp_datasets_groups(conn, dataset_names):
    """
    Retrieve the Group, and GroupID values for `Temp` trait types.
    """
    query = (
        "SELECT Temp.Name AS dataset_name, InbredSet.Name, InbredSet.Id "
        "FROM InbredSet, Temp "
        "WHERE Temp.InbredSetId = InbredSet.Id "
        f"AND Temp.Name IN ({', '.join(['%s'] * len(dataset_names))})")
    with conn.cursor(cursorclass=DictCursor) as cursor:
        cursor.execute(query, tuple(dataset_names))
        return organise_groups_by_dataset(cursor.fetchall())
    return {}

def temp_traits_datasets(conn: Any, threshold: int, traits: Tuple[Dict]): #pylint: disable=[W0613]
    """
    Retrieve datasets for 'Temp' traits.
    """
    dataset_names = tuple(set(trait["db"]["dataset_name"] for trait in traits))
    dataset_groups = temp_datasets_groups(conn, dataset_names)
    return tuple({
        **trait,
        "db": {
            **trait["db"],
            **dataset_groups.get(trait["db"]["dataset_name"], {})
        }
    } for trait in traits)

def set_confidential(traits):
    """
    Set the confidential field for traits of type `Publish`.
    """
    return tuple({
        **trait,
        "confidential": (
            True if (# pylint: disable=[R1719]
                trait.get("pre_publication_description")
                and not trait.get("pubmed_id"))
            else False)
    } for trait in traits)

def query_qtl_info(conn, query, traits, dataset_ids):
    """
    Utility: Run the `query` to get the QTL information for the given `traits`.
    """
    with conn.cursor(cursorclass=DictCursor) as cursor:
        cursor.execute(
            query,
            tuple(trait["trait_name"] for trait in traits) + dataset_ids)
        results = {
            row["trait_name"]: {
                key: val for key, val in row if key != "trait_name"
            } for row in cursor.fetchall()
        }
        return tuple(
            {**trait, **results.get(trait["trait_name"], {})}
            for trait in traits)

def set_publish_qtl_info(conn, qtl, traits):
    """
    Load extra QTL information for `Publish` traits
    """
    if qtl:
        dataset_ids = set(trait["db"]["dataset_id"] for trait in traits)
        query = (
            "SELECT PublishXRef.Id AS trait_name, PublishXRef.Locus, "
            "PublishXRef.LRS, PublishXRef.additive "
            "FROM PublishXRef, PublishFreeze "
            f"WHERE PublishXRef.Id IN ({', '.join(['%s'] * len(traits))}) "
            "AND PublishXRef.InbredSetId = PublishFreeze.InbredSetId "
            f"AND PublishFreeze.Id IN ({', '.join(['%s'] * len(dataset_ids))})")
        return query_qtl_info(conn, query, traits, tuple(dataset_ids))
    return traits

def set_probeset_qtl_info(conn, qtl, traits):
    """
    Load extra QTL information for `ProbeSet` traits
    """
    if qtl:
        dataset_ids = tuple(set(trait["db"]["dataset_id"] for trait in traits))
        query = (
            "SELECT ProbeSet.Name AS trait_name, ProbeSetXRef.Locus, "
            "ProbeSetXRef.LRS, ProbeSetXRef.pValue, "
            "ProbeSetXRef.mean, ProbeSetXRef.additive "
            "FROM ProbeSetXRef, ProbeSet "
            "WHERE ProbeSetXRef.ProbeSetId = ProbeSet.Id "
            f"AND ProbeSet.Name IN ({', '.join(['%s'] * len(traits))}) "
            "AND ProbeSetXRef.ProbeSetFreezeId IN "
            f"({', '.join(['%s'] * len(dataset_ids))})")
        return query_qtl_info(conn, query, traits, tuple(dataset_ids))
    return traits

def set_sequence(conn, traits):
    """
    Retrieve 'ProbeSet' traits sequence information
    """
    dataset_names = set(trait["db"]["dataset_name"] for trait in traits)
    query = (
        "SELECT ProbeSet.Name as trait_name, ProbeSet.BlatSeq "
        "FROM ProbeSet, ProbeSetFreeze, ProbeSetXRef "
        "WHERE ProbeSet.Id=ProbeSetXRef.ProbeSetId "
        "AND ProbeSetFreeze.Id = ProbeSetXRef.ProbeSetFreezeId "
        f"AND ProbeSet.Name IN ({', '.join(['%s'] * len(traits))}) "
        f"AND ProbeSetFreeze.Name IN ({', '.join(['%s'] * len(dataset_names))})")
    with conn.cursor(cursorclass=DictCursor) as cursor:
        cursor.execute(
            query,
            (tuple(trait["trait_name"] for trait in traits) +
             tuple(dataset_names)))
        results = {
            row["trait_name"]: {
                key: val for key, val in row.items() if key != "trait_name"
            } for row in cursor.fetchall()
        }
        return tuple(
            {
                **trait,
                **results.get(trait["trait_name"], {})
            } for trait in traits)
    return traits

def set_homologene_id(conn, traits):
    """
    Retrieve and set the 'homologene_id' values for ProbeSet traits.
    """
    geneids = set(trait.get("geneid") for trait in traits if trait["haveinfo"])
    groups = set(
        trait["db"].get("group") for trait in traits if trait["haveinfo"])
    if len(geneids) > 1 and len(groups) > 1:
        query = (
            "SELECT InbredSet.Name AS `group`, Homologene.GeneId AS geneid, "
            "HomologeneId "
            "FROM Homologene, Species, InbredSet "
            f"WHERE Homologene.GeneId IN ({', '.join(['%s'] * len(geneids))}) "
            f"AND InbredSet.Name IN ({', '.join(['%s'] * len(groups))}) "
            "AND InbredSet.SpeciesId = Species.Id "
            "AND Species.TaxonomyId = Homologene.TaxonomyId")
        with conn.cursor(cursorclass=DictCursor) as cursor:
            cursor.execute(query, (tuple(geneids) + tuple(groups)))
            results = {
                row["group"]: {
                    row["geneid"]: {
                        key: val for key, val in row.items()
                        if key not in ("group", "geneid")
                    }
                } for row in cursor.fetchall()
            }
            return tuple(
                {
                    **trait, **results.get(
                        trait["db"]["group"], {}).get(trait["geneid"], {})
                } for trait in traits)
    return traits

def traits_datasets(conn, threshold, traits):
    """
    Retrieve datasets for various `traits`.
    """
    dataset_fns = {
        "Temp": temp_traits_datasets,
        "Geno": geno_traits_datasets,
        "Publish": publish_traits_datasets,
        "ProbeSet": probeset_traits_datasets
    }
    def __organise_by_type__(acc, trait):
        dataset_type = trait["db"]["dataset_type"]
        return {
            **acc,
            dataset_type: acc.get(dataset_type, tuple()) + (trait,)
        }
    with_datasets = {
        trait["trait_fullname"]: trait for trait in (
            item for sublist in (
                dataset_fns[dtype](conn, threshold, ttraits)
                for dtype, ttraits
                in reduce(__organise_by_type__, traits, {}).items())
            for item in sublist)}
    return tuple(
        {**trait, **with_datasets.get(trait["trait_fullname"], {})}
        for trait in traits)

def traits_info(
        conn: Any, threshold: int, traits_fullnames: Tuple[str, ...],
        qtl=None) -> Tuple[Dict[str, Any], ...]:
    """
    Retrieve basic trait information for multiple `traits`.

    This is a rework of the `gn3.db.traits.retrieve_trait_info` function.
    """
    def __organise_by_dataset_type__(acc, trait):
        dataset_type = trait["db"]["dataset_type"]
        return {
            **acc,
            dataset_type: acc.get(dataset_type, tuple()) + (trait,)
        }
    traits = traits_datasets(
        conn, threshold,
        tuple(build_trait_name(trait) for trait in traits_fullnames))
    traits_fns = {
        "Publish": compose(
            set_confidential, partial(set_publish_qtl_info, conn, qtl),
            partial(publish_traits_info, conn),
            partial(publish_traits_datasets, conn, threshold)),
        "ProbeSet": compose(
            partial(set_sequence, conn),
            partial(set_probeset_qtl_info, conn, qtl),
            partial(set_homologene_id, conn),
            partial(probeset_traits_info, conn),
            partial(probeset_traits_datasets, conn, threshold)),
        "Geno": compose(
            partial(geno_traits_info, conn),
            partial(geno_traits_datasets, conn, threshold)),
        "Temp": compose(
            partial(temp_traits_info, conn),
            partial(temp_traits_datasets, conn, threshold))
    }
    return tuple(
        trait for sublist in (# type: ignore[var-annotated]
            traits_fns[dataset_type](traits)
            for dataset_type, traits
            in reduce(__organise_by_dataset_type__, traits, {}).items())
        for trait in sublist)