-
Notifications
You must be signed in to change notification settings - Fork 8
/
cistarget_db.py
1663 lines (1410 loc) · 70.9 KB
/
cistarget_db.py
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
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import re
from enum import Enum, unique
from typing import List, Optional, Set, Tuple, Type, Union
import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.feather as pf
import orderstatistics
from feather_v1_or_v2 import get_all_column_names_from_feather
@unique
class RegionsOrGenesType(Enum):
"""Enum describing all possible regions or genes types."""
REGIONS = "regions"
GENES = "genes"
@classmethod
def from_str(cls, regions_or_genes_type: str) -> "RegionsOrGenesType":
"""
Create RegionsOrGenesType Enum member from string.
:param regions_or_genes_type: 'regions' or 'genes'.
:return: RegionsOrGenesType Enum member.
"""
regions_or_genes_type = regions_or_genes_type.upper()
regions_or_genes_type_instance = cls.__members__.get(regions_or_genes_type)
if regions_or_genes_type_instance:
return regions_or_genes_type_instance
else:
raise ValueError(
f'Unsupported RegionsOrGenesType "{regions_or_genes_type}".'
)
@unique
class MotifsOrTracksType(Enum):
"""Enum describing all possible motif or track types."""
MOTIFS = "motifs"
TRACKS = "tracks"
@classmethod
def from_str(cls, motifs_or_tracks_type: str) -> "MotifsOrTracksType":
"""
Create MotifsOrTracksType Enum member from string.
:param motifs_or_tracks_type: 'motifs' or 'tracks'.
:return: MotifsOrTracksType Enum member.
"""
motifs_or_tracks_type = motifs_or_tracks_type.upper()
motifs_or_tracks_type_instance = cls.__members__.get(motifs_or_tracks_type)
if motifs_or_tracks_type_instance:
return motifs_or_tracks_type_instance
else:
raise ValueError(
f'Unsupported MotifsOrTracksType "{motifs_or_tracks_type}".'
)
class RegionOrGeneIDs:
"""
RegionOrGeneIDs class represents a unique sorted tuple of region or gene IDs for constructing a Pandas dataframe
index for a cisTarget database.
"""
@staticmethod
def get_region_or_gene_ids_from_bed(
bed_filename: str,
extract_gene_id_from_region_id_regex_replace: Optional[str] = None,
) -> "RegionOrGeneIDs":
"""
Get all region or gene IDs (from column 4) from BED filename:
- When extract_gene_id_from_region_id_regex_replace=None, region IDs are returned and each region ID is only
allowed once in the BED file.
- When extract_gene_id_from_region_id_regex_replace is set to a regex to remove the non gene ID part from the
region IDs, gene IDs are returned and each gene is allowed to appear more than once in the BED file.
:param bed_filename:
BED filename with sequences for region or gene IDs.
:param extract_gene_id_from_region_id_regex_replace:
regex for removing unwanted parts from the region ID to extract the gene ID.
:return: RegionOrGeneIDs object for regions or genes.
"""
gene_ids = set()
region_ids = set()
with open(bed_filename, "r") as fh:
for line in fh:
if line and not line.startswith("#"):
columns = line.strip().split("\t")
if len(columns) < 4:
raise ValueError(
f'Error: BED file "{bed_filename:s}" has less than 4 columns.'
)
# Get region ID from column 4 of the BED file.
region_id = columns[3]
if extract_gene_id_from_region_id_regex_replace:
# Extract gene ID from region ID.
gene_id = re.sub(
extract_gene_id_from_region_id_regex_replace, "", region_id
)
gene_ids.add(gene_id)
else:
# Check if all region IDs only appear once.
if region_id in region_ids:
raise ValueError(
f'Error: region ID "{region_id:s}" is not unique in BED file "{bed_filename:s}".'
)
region_ids.add(region_id)
if extract_gene_id_from_region_id_regex_replace:
return RegionOrGeneIDs(
region_or_gene_ids=gene_ids,
regions_or_genes_type=RegionsOrGenesType.GENES,
)
else:
return RegionOrGeneIDs(
region_or_gene_ids=region_ids,
regions_or_genes_type=RegionsOrGenesType.REGIONS,
)
@staticmethod
def get_region_or_gene_ids_from_fasta(
fasta_filename: str,
extract_gene_id_from_region_id_regex_replace: Optional[str] = None,
) -> "RegionOrGeneIDs":
"""
Get all region or gene IDs from FASTA filename:
- When extract_gene_id_from_region_id_regex_replace=None, region IDs are returned and each region ID is only
allowed once in the FASTA file.
- When extract_gene_id_from_region_id_regex_replace is set to a regex to remove the non gene ID part from the
region IDs, gene IDs are returned and each gene is allowed to appear more than once in the FASTA file.
:param fasta_filename:
FASTA filename with sequences for region or gene IDs.
:param extract_gene_id_from_region_id_regex_replace:
regex for removing unwanted parts from the region ID to extract the gene ID.
:return: RegionOrGeneIDs object for regions or genes.
"""
gene_ids = set()
region_ids = set()
with open(fasta_filename, "r") as fh:
for line in fh:
if line.startswith(">"):
# Get region ID by getting everything after '>' up till the first whitespace.
region_id = line[1:].split(maxsplit=1)[0]
if extract_gene_id_from_region_id_regex_replace:
# Extract gene ID from region ID.
gene_id = re.sub(
extract_gene_id_from_region_id_regex_replace, "", region_id
)
gene_ids.add(gene_id)
else:
# Check if all region IDs only appear once.
if region_id in region_ids:
raise ValueError(
f'Error: region ID "{region_id:s}" is not unique in FASTA file "{fasta_filename:s}".'
)
region_ids.add(region_id)
if extract_gene_id_from_region_id_regex_replace:
return RegionOrGeneIDs(
region_or_gene_ids=gene_ids,
regions_or_genes_type=RegionsOrGenesType.GENES,
)
else:
return RegionOrGeneIDs(
region_or_gene_ids=region_ids,
regions_or_genes_type=RegionsOrGenesType.REGIONS,
)
def __init__(
self,
region_or_gene_ids: Union[List[str], Set[str], Tuple[str, ...]],
regions_or_genes_type: Union[RegionsOrGenesType, str],
):
"""
Create unique sorted tuple of region or gene IDs from a list, set or tuple of region or gene IDs,
annotated with RegionsOrGenesType Enum.
:param region_or_gene_ids: list, set or tuple of region or gene IDs.
:param regions_or_genes_type: RegionsOrGenesType.REGIONS ("regions") or RegionsOrGenesType.GENES ("genes").
"""
if isinstance(regions_or_genes_type, str):
regions_or_genes_type = RegionsOrGenesType.from_str(regions_or_genes_type)
self.ids = tuple(sorted(set(region_or_gene_ids)))
self.type = regions_or_genes_type
def __repr__(self) -> str:
return f"RegionOrGeneIDs(\n region_or_gene_ids={self.ids},\n regions_or_genes_type={self.type}\n)"
def __eq__(self, other: object) -> bool:
if not isinstance(other, RegionOrGeneIDs):
return NotImplemented
return self.type == other.type and self.ids == other.ids
def __len__(self) -> int:
return len(self.ids)
def issubset(self, other: "RegionOrGeneIDs") -> bool:
"""
Check if all region or gene IDs in the current RegionOrGeneIDs object are at least present in the other
RegionOrGeneIDs object.
:param other: RegionOrGeneIDs object
:return: True or False
"""
if not isinstance(other, RegionOrGeneIDs):
return NotImplemented
assert (
self.type == other.type
), "RegionOrGeneIDs objects are of a different type."
return set(self.ids).issubset(other.ids)
def issuperset(self, other: "RegionOrGeneIDs") -> bool:
"""
Check if all region or gene IDs in the other RegionOrGeneIDs object are at least present in the current
RegionOrGeneIDs object.
:param other: RegionOrGeneIDs object
:return: True or False
"""
if not isinstance(other, RegionOrGeneIDs):
return NotImplemented
assert (
self.type == other.type
), "RegionOrGeneIDs objects are of a different type."
return set(self.ids).issuperset(set(other.ids))
class MotifOrTrackIDs:
"""
MotifOrTrackIDs class represents a unique sorted tuple of motif IDs or track IDs for constructing a Pandas
dataframe index for a cisTarget database.
"""
def __init__(
self,
motif_or_track_ids: Union[List[str], Set[str], Tuple[str, ...]],
motifs_or_tracks_type: Union[MotifsOrTracksType, str],
):
"""
Create unique sorted tuple of motif IDs or track IDs from a list, set or tuple of motif IDs or track IDs,
annotated with MotifsOrTracksType Enum.
:param motif_or_track_ids: list, set or tuple of motif IDs or track IDs.
:param motifs_or_tracks_type: MotifsOrTracksType.MOTIFS ("motifs") or MotifsOrTracksType.TRACKS ("tracks").
"""
if isinstance(motifs_or_tracks_type, str):
motifs_or_tracks_type = MotifsOrTracksType.from_str(motifs_or_tracks_type)
self.ids = tuple(sorted(set(motif_or_track_ids)))
self.type = motifs_or_tracks_type
def __repr__(self) -> str:
return f"MotifOrTrackIDs(\n motif_or_track_ids={self.ids},\n motifs_or_tracks_type={self.type}\n)"
def __eq__(self, other: object) -> bool:
if not isinstance(other, MotifOrTrackIDs):
return NotImplemented
return self.type == other.type and self.ids == other.ids
def __len__(self) -> int:
return len(self.ids)
@unique
class DatabaseTypes(Enum):
"""
Enum describing all cisTarget database types.
"""
def __init__(self, scores_or_rankings: str, column_kind: str, row_kind: str):
# Type of data contained in the cisTarget database: scores or rankings.
self._scores_or_rankings = scores_or_rankings
# Describe type of data in the column index of the cisTarget database.
self._column_kind = column_kind
# Describe type of data in the row index of the cisTarget database.
self._row_kind = row_kind
SCORES_DB_MOTIFS_VS_REGIONS = ("scores", "motifs", "regions")
SCORES_DB_MOTIFS_VS_GENES = ("scores", "motifs", "genes")
SCORES_DB_TRACKS_VS_REGIONS = ("scores", "tracks", "regions")
SCORES_DB_TRACKS_VS_GENES = ("scores", "tracks", "genes")
SCORES_DB_REGIONS_VS_MOTIFS = ("scores", "regions", "motifs")
SCORES_DB_GENES_VS_MOTIFS = ("scores", "genes", "motifs")
SCORES_DB_REGIONS_VS_TRACKS = ("scores", "regions", "tracks")
SCORES_DB_GENES_VS_TRACKS = ("scores", "genes", "tracks")
RANKINGS_DB_MOTIFS_VS_REGIONS = ("rankings", "motifs", "regions")
RANKINGS_DB_MOTIFS_VS_GENES = ("rankings", "motifs", "genes")
RANKINGS_DB_TRACKS_VS_REGIONS = ("rankings", "tracks", "regions")
RANKINGS_DB_TRACKS_VS_GENES = ("rankings", "tracks", "genes")
RANKINGS_DB_REGIONS_VS_MOTIFS = ("rankings", "regions", "motifs")
RANKINGS_DB_GENES_VS_MOTIFS = ("rankings", "genes", "motifs")
RANKINGS_DB_REGIONS_VS_TRACKS = ("rankings", "regions", "tracks")
RANKINGS_DB_GENES_VS_TRACKS = ("rankings", "genes", "tracks")
@classmethod
def from_str(cls, database_type: str) -> "DatabaseTypes":
"""
Create DatabaseTypes Enum member from string.
:param database_type: Type of database as string (member of DatabaseTypes Enum).
:return: DatabaseTypes Enum member.
"""
database_type = database_type.upper()
if database_type.startswith("DATABASETYPES."):
database_type = database_type[14:]
database_type_instance = cls.__members__.get(database_type)
if database_type_instance:
return database_type_instance
else:
raise ValueError(f'Unsupported DatabaseTypes "{database_type}".')
@classmethod
def from_strings(
cls, scores_or_rankings: str, column_kind: str, row_kind: str
) -> "DatabaseTypes":
"""
Create DatabaseTypes Enum member.
:param scores_or_rankings:
Type of data contained in the cisTarget database: "scores" or "rankings".
:param column_kind:
Type of data in the column index of the cisTarget database: 'regions', 'genes', 'motifs' or 'tracks'.
:param row_kind:
Type of data in the row index of the cisTarget database: 'regions', 'genes', 'motifs' or 'tracks'.
:return: DatabaseTypes Enum member.
"""
database_type_tuple = (scores_or_rankings, column_kind, row_kind)
for database_type in DatabaseTypes.__members__.values():
if database_type.value == database_type_tuple:
return database_type
raise ValueError(
f'"{database_type_tuple}" could not be converted to a valid DatabaseTypes member.'
)
@classmethod
def create_database_type_and_db_prefix_and_extension_from_db_filename(
cls, db_filename: str
) -> Tuple["DatabaseTypes", str, str]:
"""
Create DatabaseTypes Enum member from cisTarget database filename.
:param db_filename:
cisTarget database filename (in a format generated by create_db_name() on a DatabaseTypes Enum member).
:return:
DatabaseTypes Enum member and database prefix and extension.
"""
db_filename_dot_splitted = db_filename.split(".")
if len(db_filename_dot_splitted) < 4:
raise ValueError(
f'Database filename "{db_filename}" does not contain 3 dots.'
)
db_prefix = ".".join(db_filename_dot_splitted[0:-3])
extension = db_filename_dot_splitted[-1]
scores_or_rankings = db_filename_dot_splitted[-2]
column_kind_vs_row_kind = db_filename_dot_splitted[-3].split("_vs_")
if len(column_kind_vs_row_kind) != 2:
raise ValueError(
f'Database filename "{db_filename}" does not contain "_vs_" in "{db_filename_dot_splitted[-3]}" part.'
)
column_kind, row_kind = column_kind_vs_row_kind
return (
cls.from_strings(scores_or_rankings, column_kind, row_kind),
db_prefix,
extension,
)
def create_db_filename(self, db_prefix: str, extension: str = "feather") -> str:
"""
Create cisTarget database filename based on a database prefix string and extension.
Between the database prefix string and extension the database type will be encoded.
:param db_prefix: Database prefix.
:param extension: Database extension.
:return: Database filename.
"""
return f"{db_prefix}.{self._column_kind}_vs_{self._row_kind}.{self._scores_or_rankings}.{extension}"
@property
def is_scores_db(self) -> bool:
"""Check if cisTarget database contains scores."""
return "scores" == self._scores_or_rankings
@property
def is_rankings_db(self) -> bool:
"""Check if cisTarget database contains rankings."""
return "rankings" == self._scores_or_rankings
def _is_some_kind_of_db_by_checking_column_and_row_kind(
self, some_kind: str
) -> bool:
"""Check if cisTarget database has some_kind set in column_kind or row_kind."""
return some_kind == self._column_kind or some_kind == self._row_kind
@property
def is_regions_db(self) -> bool:
"""Check if cisTarget database has regions in columns or rows."""
return self._is_some_kind_of_db_by_checking_column_and_row_kind("regions")
@property
def is_genes_db(self) -> bool:
"""Check if cisTarget database has genes in columns or rows."""
return self._is_some_kind_of_db_by_checking_column_and_row_kind("genes")
@property
def is_motifs_db(self) -> bool:
"""Check if cisTarget database has motifs in columns or rows."""
return self._is_some_kind_of_db_by_checking_column_and_row_kind("motifs")
@property
def is_tracks_db(self) -> bool:
"""Check if cisTarget database has tracks in columns or rows."""
return self._is_some_kind_of_db_by_checking_column_and_row_kind("tracks")
@property
def allowed_as_cross_species_rankings_db_input(self) -> bool:
"""
Check if cisTarget database is allowed as CistargetDatabase.create_cross_species_rankings_db() input database.
"""
return self.is_rankings_db and self._column_kind == "motifs"
@property
def scores_or_rankings(self) -> str:
"""Return 'scores' or 'rankings' for DatabaseTypes member."""
return self._scores_or_rankings
@property
def regions_or_genes_type(self) -> "RegionsOrGenesType":
"""Return RegionsOrGenesType Enum member for DatabaseTypes member."""
if self.is_regions_db:
return RegionsOrGenesType.REGIONS
elif self.is_genes_db:
return RegionsOrGenesType.GENES
assert False, f'"regions_or_genes_type" is not handled for {self}'
@property
def motifs_or_tracks_type(self) -> "MotifsOrTracksType":
"""Return MotifsOrTracksType Enum member for DatabaseTypes member."""
if self.is_motifs_db:
return MotifsOrTracksType.MOTIFS
elif self.is_tracks_db:
return MotifsOrTracksType.TRACKS
assert False, f'"motifs_or_tracks_type" is not handled for {self}'
@property
def column_kind(self) -> str:
"""Return column kind for DatabaseTypes member."""
return self._column_kind
@property
def row_kind(self) -> str:
"""Return row kind for DatabaseTypes member."""
return self._row_kind
@property
def has_regions_or_genes_column_kind(self) -> bool:
"""Check if cisTarget database has regions or genes in columns."""
return self._column_kind == "regions" or self._column_kind == "genes"
@property
def has_motifs_or_tracks_column_kind(self) -> bool:
"""Check if cisTarget database has motifs or tracks in columns."""
return self._column_kind == "motifs" or self._column_kind == "tracks"
def get_dtype(
self, nbr_regions_or_genes: int
) -> Type[Union[np.core.single, np.core.short, np.core.intc]]:
"""
Get optimal dtype for storing values in cisTarget database.
:param nbr_regions_or_genes: Number of regions or genes in the database.
:return: dtype most suited for DatabaseTypes member.
"""
if self.is_scores_db:
# The precision of a 32-bit float should be good enough for storing scores in the database.
return np.float32
elif self.is_rankings_db:
# Rankings databases store the zero-based rankings as optimally as possible in a:
# - 16-bit signed integer: max value = 2^15 - 1 = 32767 ==> can store 32768 rankings.
# - 32-bit signed integer: max value = 2^31 - 1 = 2147483647 ==> can store 2147483648
if nbr_regions_or_genes <= 2**15:
# Range int16: -2^15 (= -32768) to 2^15 - 1 (= 32767).
return np.int16
else:
# Range int32: -2^31 (= -2147483648) to 2^31 - 1 (= 2147483647).
return np.int32
assert False, f'"get_dtype" is not handled for {self}'
class CisTargetDatabase:
"""
Class to create/update/read/write cisTarget databases.
"""
@staticmethod
def create_db(
db_type: Union["DatabaseTypes", str],
region_or_gene_ids: RegionOrGeneIDs,
motif_or_track_ids: MotifOrTrackIDs,
db_numpy_array: Optional[np.ndarray] = None,
order: Optional[str] = None,
) -> "CisTargetDatabase":
"""
Create cisTarget scores or rankings database of one of the DatabaseTypes types for RegionOrGeneIDs vs
MotifOrTrackIDs or vice versa.
:param db_type: Type of database.
:param region_or_gene_ids: RegionOrGeneIDs object or list, set or tuple of region or gene IDs.
:param motif_or_track_ids: MotifOrTrackIDs object or list, set or tuple of motif or track IDs.
:param db_numpy_array: 2D numpy array with the correct dtype and shape. If None, a zeroed database is created.
:param order: Layout numpy array in 'C' (C-like index order) or 'F' (Fortran-like index order) order when
creating a new zeroed cisTarget database.
:return: CisTargetDatabase object.
"""
if not isinstance(db_type, DatabaseTypes):
if isinstance(db_type, str):
# If the database type was given as a string, try to convert it to a member of DatabaseTypes Enum.
try:
db_type = DatabaseTypes.from_str(database_type=db_type)
except ValueError as e:
raise e
else:
raise ValueError('db_type must be of "DatabaseTypes" type.')
if not isinstance(region_or_gene_ids, RegionOrGeneIDs):
if (
isinstance(region_or_gene_ids, List)
or isinstance(region_or_gene_ids, Set)
or isinstance(region_or_gene_ids, Tuple)
):
# If region or gene IDs were given as a list, set or tuple, convert it to a RegionOrGeneIDs object.
region_or_gene_ids = RegionOrGeneIDs(
region_or_gene_ids=region_or_gene_ids,
regions_or_genes_type=db_type.regions_or_genes_type,
)
else:
raise ValueError(
'region_or_gene_ids must be of "RegionOrGeneIDs" type.'
)
else:
if region_or_gene_ids.type != db_type.regions_or_genes_type:
raise ValueError(
f'"region_or_gene_ids" type ({region_or_gene_ids.type}) is not of the same as the one defined for '
f'"db_type" ({db_type.regions_or_genes_type}).'
)
if not isinstance(motif_or_track_ids, MotifOrTrackIDs):
if (
isinstance(motif_or_track_ids, List)
or isinstance(motif_or_track_ids, Set)
or isinstance(motif_or_track_ids, Tuple)
):
# If motif or track IDs were given as a list, set or tuple, convert it to a MotifOrTrackIDs object.
motif_or_track_ids = MotifOrTrackIDs(
motif_or_track_ids=motif_or_track_ids,
motifs_or_tracks_type=db_type.motifs_or_tracks_type,
)
else:
raise ValueError(
'motif_or_track_ids must be of "MotifOrTrackIDs" type.'
)
else:
if motif_or_track_ids.type != db_type.motifs_or_tracks_type:
raise ValueError(
f'"motif_or_track_ids" type ({motif_or_track_ids.type}) is not of the same as the one defined for '
f'"db_type" ({db_type.motifs_or_tracks_type}).'
)
# Get info in which dimension of the 2D numpy array the region or gene IDs and motif or track IDs are stored.
region_or_gene_ids_shape_idx, motifs_or_tracks_ids_shape_idx = (
(1, 0)
if db_type.column_kind == "regions" or db_type.column_kind == "genes"
else (0, 1)
)
if isinstance(db_numpy_array, np.ndarray):
if len(db_numpy_array.shape) != 2:
raise ValueError(
f"Numpy array needs to have exactly 2 dimensions ({len(db_numpy_array)} dimensions found)."
)
if (
db_type.get_dtype(
nbr_regions_or_genes=db_numpy_array.shape[
region_or_gene_ids_shape_idx
]
)
!= db_numpy_array.dtype
):
raise ValueError(
f"dtype of numpy array ({db_numpy_array.dtype}) should be "
f"{db_type.get_dtype(nbr_regions_or_genes=db_numpy_array.shape[region_or_gene_ids_shape_idx])}."
)
# Create region or gene IDs index and motif or track IDs index.
region_or_gene_ids_idx = pd.Index(
data=region_or_gene_ids.ids, name=region_or_gene_ids.type.value
)
motif_or_track_ids_idx = pd.Index(
data=motif_or_track_ids.ids, name=motif_or_track_ids.type.value
)
if db_type.has_regions_or_genes_column_kind:
if isinstance(db_numpy_array, np.ndarray):
if (
len(motif_or_track_ids)
!= db_numpy_array.shape[motifs_or_tracks_ids_shape_idx]
):
raise ValueError(
f"Numpy array needs to have same number of rows as {db_type.row_kind}: "
f"{db_numpy_array.shape[motifs_or_tracks_ids_shape_idx]} vs {len(motif_or_track_ids)}"
)
if (
len(region_or_gene_ids)
!= db_numpy_array.shape[region_or_gene_ids_shape_idx]
):
raise ValueError(
f"Numpy array needs to have same number of columns as {db_type.column_kind}: "
f"{db_numpy_array.shape[region_or_gene_ids_shape_idx]} vs {len(region_or_gene_ids)}"
)
# Create dataframe from numpy array for all region or gene IDs vs all motif or track IDs.
df = pd.DataFrame(
data=db_numpy_array,
index=motif_or_track_ids_idx,
columns=region_or_gene_ids_idx,
)
else:
# Create zeroed dataframe for all region or gene IDs vs all motif or track IDs.
df = pd.DataFrame(
data=np.zeros(
(len(motif_or_track_ids), len(region_or_gene_ids)),
dtype=db_type.get_dtype(
nbr_regions_or_genes=len(region_or_gene_ids)
),
order=order,
),
index=motif_or_track_ids_idx,
columns=region_or_gene_ids_idx,
)
elif db_type.has_motifs_or_tracks_column_kind:
if isinstance(db_numpy_array, np.ndarray):
if (
len(region_or_gene_ids)
!= db_numpy_array.shape[region_or_gene_ids_shape_idx]
):
raise ValueError(
f"Numpy array needs to have same number of rows as {db_type.row_kind}: "
f"{db_numpy_array.shape[region_or_gene_ids_shape_idx]} vs {len(region_or_gene_ids)}"
)
if (
len(motif_or_track_ids)
!= db_numpy_array.shape[motifs_or_tracks_ids_shape_idx]
):
raise ValueError(
f"Numpy array needs to have same number of columns as {db_type.column_kind}: "
f"{db_numpy_array.shape[motifs_or_tracks_ids_shape_idx]} vs {len(motif_or_track_ids)}"
)
# Create dataframe from numpy array for all motif or track IDs vs all region or gene IDs.
df = pd.DataFrame(
data=db_numpy_array,
index=region_or_gene_ids_idx,
columns=motif_or_track_ids_idx,
)
else:
# Create zeroed dataframe for all motif or track IDs vs all region or gene IDs.
df = pd.DataFrame(
data=np.zeros(
(len(region_or_gene_ids), len(motif_or_track_ids)),
dtype=db_type.get_dtype(
nbr_regions_or_genes=len(region_or_gene_ids)
),
order=order,
),
index=region_or_gene_ids_idx,
columns=motif_or_track_ids_idx,
)
return CisTargetDatabase(db_type, df)
@staticmethod
def create_cross_species_rankings_db(
species_rankings_db_filenames=Union[List[str], Tuple[str]]
):
for species_rankings_db_filename in species_rankings_db_filenames:
# Get database type for each provided cisTarget database Feather file and check if it is a supported type
# for creating cross-species rankings databases.
(
species_rankings_db_type,
db_prefix,
extension,
) = DatabaseTypes.create_database_type_and_db_prefix_and_extension_from_db_filename(
db_filename=species_rankings_db_filename
)
assert (
species_rankings_db_type.allowed_as_cross_species_rankings_db_input
), f'"{species_rankings_db_filename}" ({species_rankings_db_type}) is not allowed as input database type.'
# Create Feather dataset object with all provided cisTarget rankings databases (from different species).
multiple_species_rankings_feather_dataset = pf.FeatherDataset(
path_or_paths=species_rankings_db_filenames, validate_schema=True
)
# Read Feather dataset object in a pyarrow table. Each column in the Feather dataset consists of X amount of
# chunks (where X is the number of Feather databases).
multiple_species_rankings_table = (
multiple_species_rankings_feather_dataset.read_table(columns=None)
)
# Check if a "regions" or "genes" column name (row index column) is found in the Feather database.
if (
species_rankings_db_type.row_kind
in multiple_species_rankings_table.column_names
):
regions_or_genes_type = RegionsOrGenesType.from_str(
species_rankings_db_type.row_kind
)
else:
raise ValueError(
'Feather rankings databases for creating cross-species rankings need to have a column named "regions" '
'or "genes".'
)
# Get region or gene IDs from the regions/genes column from the first Feather database, by taking the data from
# the first chunk of the pyarrow table.
region_or_gene_ids_tuple = tuple(
multiple_species_rankings_table.column(regions_or_genes_type.value)
.chunk(0)
.to_pylist()
)
region_or_gene_ids = RegionOrGeneIDs(
region_or_gene_ids=region_or_gene_ids_tuple,
regions_or_genes_type=regions_or_genes_type,
)
# Check if Feather databases were created with the CisTargetDatabase class (RegionOrGeneIDs are made unique and
# are sorted).
assert len(region_or_gene_ids.ids) == len(
region_or_gene_ids_tuple
), f'{regions_or_genes_type.value} IDs are not unique in "{species_rankings_db_filenames[0]}".'
# Check if each database contains exactly the same regions/genes and in the same order.
for chunk_idx in range(
1,
multiple_species_rankings_table.column(
regions_or_genes_type.value
).num_chunks,
):
assert region_or_gene_ids_tuple == tuple(
multiple_species_rankings_table.column(regions_or_genes_type.value)
.chunk(chunk_idx)
.to_pylist()
), (
f'Feather rankings database "{species_rankings_db_filenames[chunk_idx]}" contains different region '
f'or gene IDs or in a different order than in "{species_rankings_db_filenames[0]}".'
)
# Get all motif IDs by getting all column names except the "regions" or "genes" column name.
motif_or_track_ids = MotifOrTrackIDs(
motif_or_track_ids=tuple(
motif_id
for motif_id in multiple_species_rankings_table.column_names
if motif_id != regions_or_genes_type.value
),
motifs_or_tracks_type=species_rankings_db_type.column_kind,
)
# Create zeroed rankings database for storing cross-species rankings.
cross_species_rankings_ct = CisTargetDatabase.create_db(
db_type=species_rankings_db_type,
region_or_gene_ids=region_or_gene_ids,
motif_or_track_ids=motif_or_track_ids,
)
for motif_id in motif_or_track_ids.ids:
# Get all rankings for a motif (each chunk contains the rankings from one species which were stored in a
# separate cisTarget rankings database) and transpose them so each row contains the ranking for each species
# for one region/gene. After transposition the motif_id_rankings_per_species array is in 'C' order again, so
# is more cache friendly for usage in orderstatistics.create_cross_species_ranking_for_motif().
motif_id_rankings_per_species = np.array(
multiple_species_rankings_table.column(motif_id).chunks, order="F"
).transpose()
# Create cross-species ranking for current motif by combining the individual ranking in each species per
# region/gene with order statistics.
cross_species_rankings_ct.df.loc[
:, motif_id
] = orderstatistics.create_cross_species_ranking_for_motif(
motif_id_rankings_per_species=motif_id_rankings_per_species
)
# Return cisTarget cross-species rankings database.
return cross_species_rankings_ct
@staticmethod
def read_db(
db_filename_or_dbs_filenames: Union[str, List, Tuple],
db_type: Optional[Union["DatabaseTypes", str]] = None,
) -> "CisTargetDatabase":
"""
Read cisTarget database from Feather file(s) to CisTargetDatabase object.
:param db_filename_or_dbs_filenames: Feather database filename or database filenames.
:param db_type: Type of database (can be automatically determined from the filename if written with write_db).
:return: CisTargetDatabase object.
"""
assert db_filename_or_dbs_filenames is not None
if isinstance(db_filename_or_dbs_filenames, str):
db_filename = db_filename_or_dbs_filenames
# Convert to a tuple with one element.
db_filename_or_dbs_filenames = (db_filename_or_dbs_filenames,)
elif isinstance(db_filename_or_dbs_filenames, List) or isinstance(
db_filename_or_dbs_filenames, Tuple
):
# Look at the first (partial) cisTarget database for most checks when multiple databases are given.
db_filename = db_filename_or_dbs_filenames[0]
else:
ValueError('Unsupported type for "db_filename_or_dbs_filenames".')
# Try to extract the database type from database filename if database type was not specified.
if not db_type:
try:
(
db_type,
db_prefix,
extension,
) = DatabaseTypes.create_database_type_and_db_prefix_and_extension_from_db_filename(
db_filename=db_filename
)
except ValueError:
raise ValueError(
"cisTarget database type could not be automatically determined from db_filename_or_dbs_filenames. "
"Specify db_type instead."
)
else:
if not isinstance(db_type, DatabaseTypes):
if isinstance(db_type, str):
# If the database type was given as a string, try to convert it to a member of DatabaseTypes Enum.
try:
db_type = DatabaseTypes.from_str(database_type=db_type)
except ValueError as e:
raise e
else:
raise ValueError('db_type must be of "DatabaseTypes" type.')
if db_type.has_motifs_or_tracks_column_kind:
if len(db_filename_or_dbs_filenames) == 1:
# Only one motif or track vs regions or genes cisTarget scores/rankings database file.
# Read cisTarget database file in pyarrow table.
# Read one Feather database files in a pyarrow table.
pa_table = pf.FeatherDataset(
path_or_paths=db_filename_or_dbs_filenames, validate_schema=True
).read_table(columns=None)
else:
# Multiple partial motif or track vs regions or genes cisTarget scores/rankings database files.
# Partial motif or track vs regions or genes cisTarget scores/rankings databases have the same number
# of rows (regions or genes), but a different columns names (motif or tracks).
# pyarrow.feather.FeatherDataset can not read multiple files with a different schema.
#
# This is solved below by reading each partial motif or track vs regions or genes cisTarget
# scores/rankings database file as a pyarrow table and constructing the full motif or track vs
# regions or genes cisTarget database by appending all columns (motifs or tracks) from multiple files.
# Read each partial motif or track vs regions or genes cisTarget scores/rankings database file as a
# pyarrow Table and save them as an element in a list.
pa_table_partial_list = [
pf.FeatherDataset(
path_or_paths=[
db_filename,
],
validate_schema=True,
).read_table(columns=None)
for db_filename in db_filename_or_dbs_filenames
]
# Get region or gene column from the first partial motif or track vs regions or genes cisTarget
# scores/rankings database.
regions_or_genes_column = pa_table_partial_list[0].column(
db_type.row_kind
)
# Remove region or gene column from first partial motif or track vs regions or genes cisTarget
# scores/rankings database from pyarrow table representation.
pa_table = pa_table_partial_list[0].drop([db_type.row_kind])
# Create merged motif or track vs regions or genes cisTarget scores/rankings database from partial
# databases, by adding each column of the partial motif or track vs regions or genes cisTarget
# scores/rankings database (starting from the second partial database as the first partial motif or
# track vs regions or genes cisTarget scores/rankings database can be used to start from.
for df_partial in pa_table_partial_list[1:]:
for column in df_partial.itercolumns():
if column._name != db_type.row_kind:
# Append column to merged motif or track vs regions or genes cisTarget scores/rankings
# database pyarrow table if the column is a scores/rankings column (no "regions" or "genes"
# column).
pa_table = pa_table.append_column(column._name, column)
else:
# Check if the "regions" or "genes" column contains the same list of genes/regions across
# all partial databases.
if column != regions_or_genes_column:
raise ValueError(
f"Partial cisTarget databases do not all contain the same {db_type.row_kind}."
)
# Get all column names (without "regions" or "genes" column) and sort them alphabetically.
column_names = pa_table.column_names
column_names_sorted = sorted(column_names)
# Reorder column names if necessary.
if column_names != column_names_sorted:
pa_table = pa_table.select(column_names)
# Add "regions" or "genes" column as last column.
pa_table = pa_table.append_column(
db_type.row_kind, regions_or_genes_column
)
elif db_type.has_regions_or_genes_column_kind:
# Read one or more cisTarget Feather database files in a pyarrow table.
# For partial regions or genes vs motifs or track partial databases, the number of columns (regions or
# genes) is the same for each partial database.
pa_table = pf.FeatherDataset(
path_or_paths=db_filename_or_dbs_filenames, validate_schema=True
).read_table(columns=None)
# Get all column names.
all_column_names = pa_table.column_names
try:
# Check if we have an old database that still used a "features" column and rename it.
features_idx = all_column_names.index("features")
all_column_names[features_idx] = db_type.row_kind
pa_table = pa_table.rename_columns(all_column_names)
except ValueError:
pass
if db_type.row_kind in all_column_names:
# Sort column names (non-index columns) and add index column as last column.
column_names_sorted_and_index = sorted(
[
column_name
for column_name in all_column_names
if column_name != db_type.row_kind
]
)
column_names_sorted_and_index.append(db_type.row_kind)