-
Notifications
You must be signed in to change notification settings - Fork 22
/
test_schema_compliance.py
2456 lines (2157 loc) · 109 KB
/
test_schema_compliance.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
"""
Tests for schema compliance of an AnnData object
"""
import tempfile
import unittest
import anndata
import fixtures.examples_validate as examples
import numpy
import pandas as pd
import pytest
import scipy.sparse
from cellxgene_schema.schema import get_schema_definition
from cellxgene_schema.utils import getattr_anndata
from cellxgene_schema.validate import (
ERROR_SUFFIX_VISIUM_AND_IS_SINGLE_TRUE,
VISIUM_AND_IS_SINGLE_TRUE_MATRIX_SIZE,
Validator,
)
from cellxgene_schema.write_labels import AnnDataLabelAppender
schema_def = get_schema_definition()
@pytest.fixture(scope="module")
def validator() -> Validator:
validator = Validator()
# Override the schema definition here
validator._set_schema_def()
# lower threshold for low gene count warning
validator.schema_def["components"]["var"]["warn_if_less_than_rows"] = 1
return validator
@pytest.fixture
def validator_with_adata(validator) -> Validator:
validator.adata = examples.adata.copy()
return validator
@pytest.fixture
def validator_with_tissue_type(validator_with_adata) -> Validator:
obs = validator_with_adata.adata.obs
obs.loc[obs.index[0], "tissue_type"] = "tissue"
obs.loc[obs.index[0], "tissue_ontology_term_id"] = "UBERON:0001062"
return validator
@pytest.fixture()
def validator_with_validated_adata(validator_with_adata) -> Validator:
validator_with_adata.validate_adata()
return validator_with_adata
@pytest.fixture
def adata_with_labels() -> anndata.AnnData:
# Manually created data (positive control)
return examples.adata_with_labels.copy()
@pytest.fixture
def validator_with_adata_missing_raw(validator) -> Validator:
validator.adata = examples.adata_non_raw.copy()
return validator
@pytest.fixture
def validator_with_spatial_and_is_single_false(validator) -> Validator:
validator.adata = examples.adata_spatial_is_single_false.copy()
return validator
@pytest.fixture
def validator_with_visium_assay(validator) -> Validator:
validator.adata = examples.adata_visium.copy()
validator.visium_and_is_single_true_matrix_size = 2
return validator
@pytest.fixture
def validator_with_slide_seq_v2_assay(validator) -> Validator:
validator.adata = examples.adata_slide_seqv2.copy()
return validator
@pytest.fixture
def label_writer(validator_with_validated_adata) -> AnnDataLabelAppender:
"""
Fixture that returns an AnnDataLabelAppender object
"""
label_writer = AnnDataLabelAppender(validator_with_validated_adata)
label_writer._add_labels()
return label_writer
def save_and_read_adata(adata: anndata.AnnData) -> anndata.AnnData:
"""
Saves adata to a temporary file and reads it back. Used to test read/write errors.
:param adata: AnnData object
:return: AnnData object
"""
with tempfile.NamedTemporaryFile(suffix=".h5ad") as f:
adata.write_h5ad(f.name)
return anndata.read(f.name)
class TestValidAnndata:
"""
Tests a valid AnnData object. Most other tests below modify this AnnData object and test for failure cases.
The valid AnnData object has all valid cases described in the schema.
"""
def test_valid_anndata(self, validator_with_adata):
validator = validator_with_adata
validator.validate_adata()
assert not validator.errors
class TestH5adValidation:
"""
Checks that validation from h5ad works, only does one invalid example as extensive testing is done in the classes
below
"""
def test_validate(self, validator):
h5ad_valid_file = examples.h5ad_valid
assert validator.validate_adata(h5ad_valid_file)
def test_invalidate(self, validator):
h5ad_invalid_file = examples.h5ad_invalid
assert not validator.validate_adata(h5ad_invalid_file)
class TestExpressionMatrix:
"""
Fail cases for expression matrices (anndata.X and anndata.raw.X)
"""
def test_shapes(self, validator_with_adata):
"""
All matrix layers MUST have the same shape, and have the same cell labels and gene labels.
"""
validator = validator_with_adata
# Creates a raw layer
validator.adata.raw = validator.adata
validator.adata.raw.var.drop("feature_is_filtered", axis=1, inplace=True)
validator.adata.X = examples.adata_non_raw.X.copy()
# remove one gene
validator.adata = validator.adata[:, 1:]
validator.validate_adata()
assert "ERROR: Number of genes in X (3) is different than raw.X (4)." in validator.errors
def test_sparsity(self, validator_with_adata):
"""
In any layer, if a matrix has 50% or more values that are zeros, it is STRONGLY RECOMMENDED that
the matrix be encoded as a scipy.sparse.csr_matrix
"""
validator = validator_with_adata
sparse_X = numpy.zeros([validator.adata.obs.shape[0], validator.adata.var.shape[0]], dtype=numpy.float32)
sparse_X[0, 1] = 1
sparse_X[1, 1] = 1
validator.adata.X = sparse_X
validator.validate_adata()
assert validator.warnings == [
"WARNING: Sparsity of 'X' is 0.75 which is greater than 0.5, "
"and it is not a 'scipy.sparse.csr_matrix'. It is "
"STRONGLY RECOMMENDED to use this type of matrix for "
"the given sparsity."
]
@pytest.mark.parametrize("invalid_value", [1.5, -1])
def test_raw_values__invalid(self, validator_with_adata, invalid_value):
"""
When both `adata.X` and `adata.raw.X` are present, but `adata.raw.X` contains negative or non-integer values,
an error is raised.
"""
validator = validator_with_adata
validator.adata.raw.X[0, 1] = invalid_value
validator.validate_adata()
assert validator.errors == [
"ERROR: All non-zero values in raw matrix must be positive integers of type numpy.float32.",
"ERROR: Raw data may be missing: data in 'raw.X' does not meet schema requirements.",
]
@pytest.mark.parametrize("invalid_value", [1.5, -1])
def test_raw_values__invalid_spatial(self, validator_with_visium_assay, invalid_value):
"""
When both `adata.X` and `adata.raw.X` are present, but `adata.raw.X` contains negative or non-integer values,
an error is raised.
"""
validator = validator_with_visium_assay
validator.adata.raw.X[0, 1] = invalid_value
validator.validate_adata()
assert validator.errors == [
"ERROR: All non-zero values in raw matrix must be positive integers of type numpy.float32.",
"ERROR: Raw data may be missing: data in 'raw.X' does not meet schema requirements.",
]
@pytest.mark.parametrize("datatype", [int, "float16", "float64"])
def test_raw_values__wrong_datatype(self, validator_with_adata, datatype):
"""
When both `adata.X` and `adata.raw.X` are present, but `adata.raw.X` values are stored as the wrong datatype
"""
validator = validator_with_adata
raw = anndata.AnnData(X=validator.adata.raw.X, obs=validator.adata.obs, var=validator.adata.raw.var)
raw.X = raw.X.astype(datatype)
validator.adata.raw = raw
validator.validate_adata()
assert validator.errors == [
"ERROR: Raw matrix values must have type numpy.float32.",
"ERROR: Raw data may be missing: data in 'raw.X' does not meet schema requirements.",
]
def test_raw_values__contains_zero_row(self, validator_with_adata):
"""
When both `adata.X` and `adata.raw.X` are present, but `adata.raw.X` contains a row with all zeros
"""
validator = validator_with_adata
validator.adata.raw.X[0] = numpy.zeros(validator.adata.var.shape[0], dtype=numpy.float32)
validator.validate_adata()
assert validator.errors == [
"ERROR: Each cell must have at least one non-zero value in its row in the raw matrix.",
"ERROR: Raw data may be missing: data in 'raw.X' does not meet schema requirements.",
]
def test_raw_values__contains_zero_row_in_tissue_1(self, validator_with_visium_assay):
"""
Raw Matrix contains a row with all zeros and in_tissue is 1, but no values are in_tissue 0.
"""
validator = validator_with_visium_assay
validator.adata.obs["in_tissue"] = 1
validator.adata.X[0] = numpy.zeros(validator.adata.var.shape[0], dtype=numpy.float32)
validator.adata.raw.X[0] = numpy.zeros(validator.adata.var.shape[0], dtype=numpy.float32)
validator.validate_adata()
assert validator.errors == [
"ERROR: Each cell must have at least one non-zero value in its row in the raw matrix.",
"ERROR: Raw data may be missing: data in 'raw.X' does not meet schema requirements.",
]
def test_raw_values__contains_zero_row_in_tissue_1_mixed_in_tissue_values(self, validator_with_visium_assay):
"""
Raw Matrix contains a row with all zeros and in_tissue is 1, and there are also values with in_tissue 0.
"""
validator = validator_with_visium_assay
validator.adata.X[1] = numpy.zeros(validator.adata.var.shape[0], dtype=numpy.float32)
validator.adata.raw.X[1] = numpy.zeros(validator.adata.var.shape[0], dtype=numpy.float32)
validator.validate_adata()
assert validator.errors == [
"ERROR: Each observation with obs['in_tissue'] == 1 must have at least one "
"non-zero value in its row in the raw matrix.",
"ERROR: Raw data may be missing: data in 'raw.X' does not meet schema requirements.",
]
def test_raw_values__contains_all_zero_rows_in_tissue_0(self, validator_with_visium_assay):
"""
When both `adata.X` and `adata.raw.X` are present, but `adata.raw.X` contains all rows with all zeros
and in_tissue is 0
"""
validator = validator_with_visium_assay
validator.adata.obs["in_tissue"] = 0
validator.adata.obs["cell_type_ontology_term_id"] = "unknown"
validator.adata.X = numpy.zeros(
[validator.adata.obs.shape[0], validator.adata.var.shape[0]], dtype=numpy.float32
)
validator.adata.raw = validator.adata.copy()
validator.adata.raw.var.drop("feature_is_filtered", axis=1, inplace=True)
validator.validate_adata()
assert validator.errors == [
"ERROR: If obs['in_tissue'] contains at least one value 0, then there must be at least "
"one row with obs['in_tissue'] == 0 that has a non-zero value in the raw matrix.",
"ERROR: Raw data may be missing: data in 'raw.X' does not meet schema requirements.",
]
def test_raw_values__contains_some_zero_rows_in_tissue_0(self, validator_with_visium_assay):
"""
When both `adata.X` and `adata.raw.X` are present, but `adata.raw.X` contains some rows with all zeros
and in_tissue is 0. Success case.
"""
validator = validator_with_visium_assay
validator.adata.obs["in_tissue"] = 0
validator.adata.obs["cell_type_ontology_term_id"] = "unknown"
validator.adata.X[0] = numpy.zeros(validator.adata.var.shape[0], dtype=numpy.float32)
validator.adata.raw.X[0] = numpy.zeros(validator.adata.var.shape[0], dtype=numpy.float32)
validator.validate_adata()
assert validator.errors == []
def test_raw_values__invalid_visium_and_is_single_true_row_length(self, validator_with_visium_assay):
"""
Dataset is visium and uns['is_single'] is True, but raw.X is the wrong length.
"""
validator = validator_with_visium_assay
validator.visium_and_is_single_true_matrix_size = VISIUM_AND_IS_SINGLE_TRUE_MATRIX_SIZE
validator.validate_adata()
assert validator.errors == [
f"ERROR: When {ERROR_SUFFIX_VISIUM_AND_IS_SINGLE_TRUE}, the raw matrix must be the "
"unfiltered feature-barcode matrix 'raw_feature_bc_matrix'. It must have exactly "
f"{validator.visium_and_is_single_true_matrix_size} rows. Raw matrix row count is 2.",
"ERROR: Raw data may be missing: data in 'raw.X' does not meet schema requirements.",
]
def test_raw_values__multiple_invalid_in_tissue_errors(self, validator_with_visium_assay):
"""
Dataset is visium and uns['is_single'] is True, in_tissue has both 0 and 1 values and there
are issues validating rows of both in the matrix.
"""
validator = validator_with_visium_assay
validator.visium_and_is_single_true_matrix_size = VISIUM_AND_IS_SINGLE_TRUE_MATRIX_SIZE
validator.adata.X = numpy.zeros(
[validator.adata.obs.shape[0], validator.adata.var.shape[0]], dtype=numpy.float32
)
validator.adata.raw = validator.adata.copy()
validator.adata.raw.var.drop("feature_is_filtered", axis=1, inplace=True)
validator.validate_adata()
assert validator.errors == [
f"ERROR: When {ERROR_SUFFIX_VISIUM_AND_IS_SINGLE_TRUE}, the raw matrix must be the "
"unfiltered feature-barcode matrix 'raw_feature_bc_matrix'. It must have exactly "
f"{validator.visium_and_is_single_true_matrix_size} rows. Raw matrix row count is 2.",
"ERROR: If obs['in_tissue'] contains at least one value 0, then there must be at least "
"one row with obs['in_tissue'] == 0 that has a non-zero value in the raw matrix.",
"ERROR: Each observation with obs['in_tissue'] == 1 must have at least one "
"non-zero value in its row in the raw matrix.",
"ERROR: Raw data may be missing: data in 'raw.X' does not meet schema requirements.",
]
def test_raw_values__multiple_errors(self, validator_with_adata):
"""
When both `adata.X` and `adata.raw.X` are present, but `adata.raw.X` contains multiple errors and all are
reported
"""
validator = validator_with_adata
validator.adata.raw.X[0] = numpy.zeros(validator.adata.var.shape[0], dtype=numpy.float32)
validator.adata.raw.X[1, 1] = 1.5
validator.validate_adata()
assert validator.errors == [
"ERROR: Each cell must have at least one non-zero value in its row in the raw matrix.",
"ERROR: All non-zero values in raw matrix must be positive integers of type numpy.float32.",
"ERROR: Raw data may be missing: data in 'raw.X' does not meet schema requirements.",
]
def test_raw_values__non_rna(self, validator_with_adata):
"""
Except for ATAC-seq and methylation data, raw data is REQUIRED
"""
# ATAC - raw layer not required
# The assignment above makes X to not be raw: validator.adata.uns["X_normalization"] = "CPM"
# The following line makes it to be scATAC-seq data (EFO:0010891)
# Missing raw data in atac-seq data is allowed, thus the following should not return an error message
validator = validator_with_adata
obs = validator.adata.obs
validator.errors = []
obs["assay_ontology_term_id"] = "EFO:0010891"
obs["suspension_type"] = "nucleus"
obs.loc[:, ["suspension_type"]] = obs.astype("category")
validator.validate_adata()
assert validator.errors == []
def test_raw_values__matrix_chunks(self, validator_with_adata):
"""
Test adata is validated correctly when matrix is larger than the chunk size
"""
with unittest.mock.patch.object(validator_with_adata._chunk_matrix, "__defaults__", (1,)):
validator = validator_with_adata
validator.validate_adata()
assert validator.errors == []
def test_missing_raw_matrix(self, validator_with_adata_missing_raw):
"""
Test error message appears if dataset with RNA assay is missing raw matrix
"""
validator = validator_with_adata_missing_raw
validator.validate_adata()
assert validator.errors == [
"ERROR: All non-zero values in raw matrix must be positive integers of type numpy.float32.",
"ERROR: Raw data is missing: there is only a normalized matrix in X and no raw.X",
]
def test_final_strongly_recommended(self, validator_with_adata):
"""
Except for ATAC-seq and methylation data, final matrix is STRONGLY RECOMMENDED
"""
# move raw to X amd: i.e. there is no final
validator = validator_with_adata
validator.adata.X = validator.adata.raw.X
del validator.adata.raw
validator.validate_adata()
assert validator.warnings == [
"WARNING: Only raw data was found, i.e. there is no 'raw.X'. "
"It is STRONGLY RECOMMENDED that 'final' (normalized) data is provided."
]
class TestObs:
"""
Fail cases in adata.obs
"""
def get_format_error_message(self, error_message_suffix: str, detail: str) -> str:
return detail + " " + error_message_suffix
@pytest.mark.parametrize(
"column",
[
"development_stage_ontology_term_id",
"disease_ontology_term_id",
"self_reported_ethnicity_ontology_term_id",
"is_primary_data",
"sex_ontology_term_id",
"tissue_ontology_term_id",
"donor_id",
"suspension_type",
],
)
def test_column_presence(self, validator_with_adata, column):
"""
obs is a pandas.DataFrame. Curators MUST annotate the following columns in the obs dataframe.
"""
validator = validator_with_adata
validator.adata.obs.drop(column, axis=1, inplace=True)
# Remove batch condition because it has a dependency with is_primary_data
validator.adata.uns.pop("batch_condition")
validator.validate_adata()
assert f"ERROR: Dataframe 'obs' is missing " f"column '{column}'." in validator.errors
def test_column_presence_organism(self, validator_with_adata):
"""
obs is a pandas.DataFrame. Curators MUST annotate the following columns in the obs dataframe.
A separate check is need for organism_ontology_term_id because removing from anndata results in multiple
errors given that other columns depend on its presence
"""
validator = validator_with_adata
validator.adata.obs.drop("organism_ontology_term_id", axis=1, inplace=True)
validator.validate_adata()
assert validator.errors == [
"ERROR: Dataframe 'obs' is missing column " "'organism_ontology_term_id'.",
"ERROR: Checking values with dependencies failed for "
"adata.obs['self_reported_ethnicity_ontology_term_id'], this is likely due "
"to missing dependent column in adata.obs.",
"ERROR: Checking values with dependencies failed for "
"adata.obs['development_stage_ontology_term_id'], this is likely due "
"to missing dependent column in adata.obs.",
]
def test_column_presence_assay(self, validator_with_adata):
"""
obs is a pandas.DataFrame. Curators MUST annotate the following columns in the obs dataframe.
A separate check is need for assay_ontology_term_id because removing from anndata results in multiple
errors given that other columns depend on its presence
"""
validator = validator_with_adata
validator.adata.obs.drop("assay_ontology_term_id", axis=1, inplace=True)
validator.validate_adata()
assert validator.errors == [
"ERROR: Dataframe 'obs' is missing column " "'assay_ontology_term_id'.",
"ERROR: Checking values with dependencies failed for "
"adata.obs['suspension_type'], this is likely due "
"to missing dependent column in adata.obs.",
]
@pytest.mark.parametrize("reserved_column", schema_def["components"]["obs"]["reserved_columns"])
def test_obs_reserved_columns_presence(self, validator_with_adata, reserved_column):
"""
Reserved columns must NOT be used in obs
"""
validator = validator_with_adata
validator.adata.obs[reserved_column] = "dummy_value"
validator.validate_adata()
assert validator.errors == [
f"ERROR: Column '{reserved_column}' is a reserved column name "
f"of 'obs'. Remove it from h5ad and try again."
]
def test_obsolete_term_id(self, validator_with_adata):
"""
Terms documented as obsolete in an ontology MUST NOT be used. For example, EFO:0009310
for obsolete_10x v2 was marked as obsolete in EFO version 3.31.0 and replaced by
EFO:0009899 for 10x 3' v2.
https://www.ebi.ac.uk/ols/ontologies/efo/terms?short_form=EFO_0009310
"""
# Not a valid term
validator = validator_with_adata
error_message_suffix = validator.schema_def["components"]["obs"]["columns"]["assay_ontology_term_id"][
"error_message_suffix"
]
validator.adata.obs.loc[validator.adata.obs.index[0], "assay_ontology_term_id"] = "EFO:0009310"
validator.validate_adata()
assert validator.errors == [
self.get_format_error_message(
error_message_suffix,
"ERROR: 'EFO:0009310' in 'assay_ontology_term_id' is a deprecated term id of 'EFO'.",
)
]
@pytest.mark.parametrize(
"assay_ontology_term_id,error",
[
("CL:000001", "ERROR: 'CL:000001' in 'assay_ontology_term_id' is not a valid ontology term id of 'EFO'."),
("EFO:0000001", "ERROR: 'EFO:0000001' in 'assay_ontology_term_id' is not an allowed term id."),
("EFO:0002772", "ERROR: 'EFO:0002772' in 'assay_ontology_term_id' is not an allowed term id."),
("EFO:0010183", "ERROR: 'EFO:0010183' in 'assay_ontology_term_id' is not an allowed term id."),
(
"EFO:0010183 (sci-plex)",
"ERROR: 'EFO:0010183 (sci-plex)' in 'assay_ontology_term_id' is not a valid ontology term id of 'EFO'.",
),
],
)
def test_assay_ontology_term_id(self, validator_with_adata, assay_ontology_term_id, error):
"""
assay_ontology_term_id categorical with str categories.
This MUST be an EFO term that is a descendant of either "EFO:0002772" or "EFO:0010183"
"""
validator = validator_with_adata
validator.adata.obs.loc[validator.adata.obs.index[0], "assay_ontology_term_id"] = assay_ontology_term_id
validator.validate_adata()
error_message_suffix = validator.schema_def["components"]["obs"]["columns"]["assay_ontology_term_id"][
"error_message_suffix"
]
assert validator.errors == [self.get_format_error_message(error_message_suffix, error)]
def test_cell_type_ontology_term_id_invalid_term(self, validator_with_adata):
validator = validator_with_adata
validator.adata.obs.loc[validator.adata.obs.index[0], "cell_type_ontology_term_id"] = "EFO:0000001"
validator.validate_adata()
assert validator.errors == [
"ERROR: 'EFO:0000001' in 'cell_type_ontology_term_id' is not a valid ontology term id of 'CL'.",
]
@pytest.mark.parametrize(
"term",
schema_def["components"]["obs"]["columns"]["cell_type_ontology_term_id"]["curie_constraints"]["forbidden"][
"terms"
],
)
def test_cell_type_ontology_term_id(self, validator_with_adata, term):
"""
cell_type_ontology_term_id categorical with str categories. This MUST be a CL term, and must NOT match forbidden
columns defined in schema
"""
validator = validator_with_adata
validator.adata.obs.loc[validator.adata.obs.index[0], "cell_type_ontology_term_id"] = term
validator.validate_adata()
# Forbidden columns may be marked as either "not allowed" or "deprecated"
assert validator.errors == [
f"ERROR: '{term}' in 'cell_type_ontology_term_id' is not allowed."
] or validator.errors == [f"ERROR: '{term}' in 'cell_type_ontology_term_id' is a deprecated term id of 'CL'."]
def test_development_stage_ontology_term_id_human(self, validator_with_adata):
"""
development_stage_ontology_term_id categorical with str categories. If unavailable, this MUST be "unknown".
If organism_ontolology_term_id is "NCBITaxon:9606" for Homo sapiens,
this MUST be the most accurate HsapDv term.
"""
validator = validator_with_adata
obs = validator.adata.obs
obs.loc[obs.index[0], "organism_ontology_term_id"] = "NCBITaxon:9606"
obs.loc[obs.index[0], "development_stage_ontology_term_id"] = "EFO:0000001"
validator.validate_adata()
assert validator.errors == [
"ERROR: 'EFO:0000001' in 'development_stage_ontology_term_id' is "
"not a valid ontology term id of 'HsapDv'. When 'organism_ontology_term_id' is 'NCBITaxon:9606' "
"(Homo sapiens), 'development_stage_ontology_term_id' MUST be a term id of 'HsapDv' or unknown."
]
def test_development_stage_ontology_term_id_mouse(self, validator_with_adata):
"""
If organism_ontolology_term_id is "NCBITaxon:10090" for Mus musculus,
this MUST be the most accurate MmusDv term
"""
validator = validator_with_adata
obs = validator.adata.obs
obs.loc[obs.index[0], "organism_ontology_term_id"] = "NCBITaxon:10090"
obs.loc[obs.index[0], "development_stage_ontology_term_id"] = "EFO:0000001"
obs.loc[
obs.index[0],
"self_reported_ethnicity_ontology_term_id",
] = "na"
validator.validate_adata()
assert validator.errors == [
"ERROR: 'EFO:0000001' in 'development_stage_ontology_term_id' is "
"not a valid ontology term id of 'MmusDv'. When 'organism_ontology_term_id' is 'NCBITaxon:10090' "
"(Mus musculus), 'development_stage_ontology_term_id' MUST be a term id of 'MmusDv' or unknown."
]
def test_development_stage_ontology_term_id_all_species(self, validator_with_adata):
"""
All other it MUST be descendants of UBERON:0000105 and not UBERON:0000071
"""
validator = validator_with_adata
obs = validator.adata.obs
# Fail case not an UBERON term
obs.loc[obs.index[0], "organism_ontology_term_id"] = "NCBITaxon:10114"
obs.loc[obs.index[0], "development_stage_ontology_term_id"] = "EFO:0000001"
obs.loc[
obs.index[0],
"self_reported_ethnicity_ontology_term_id",
] = "na"
validator.validate_adata()
assert validator.errors == [
"ERROR: 'EFO:0000001' in 'development_stage_ontology_term_id' is "
"not a valid ontology term id of 'UBERON'. When 'organism_ontology_term_id' is not 'NCBITaxon:10090' "
"nor 'NCBITaxon:9606', 'development_stage_ontology_term_id' MUST be a descendant term id of "
"'UBERON:0000105' excluding 'UBERON:0000071', or unknown."
]
# All other it MUST be descendants of UBERON:0000105 and not UBERON:0000071
# Fail case UBERON:0000071
validator.errors = []
obs.loc[obs.index[0], "organism_ontology_term_id"] = "NCBITaxon:10114"
obs.loc[obs.index[0], "development_stage_ontology_term_id"] = "UBERON:0000071"
obs.loc[
obs.index[0],
"self_reported_ethnicity_ontology_term_id",
] = "na"
validator.validate_adata()
assert validator.errors == [
"ERROR: 'UBERON:0000071' in 'development_stage_ontology_term_id' is not allowed. When "
"'organism_ontology_term_id' is not 'NCBITaxon:10090' "
"nor 'NCBITaxon:9606', 'development_stage_ontology_term_id' MUST be a descendant term id of "
"'UBERON:0000105' excluding 'UBERON:0000071', or unknown.",
]
def test_disease_ontology_term_id(self, validator_with_adata):
"""
disease_ontology_term_id categorical with str categories. This MUST be one of:
- PATO:0000461 for normal or healthy
- descendant of MONDO:0000001 for disease
- self or descendant of MONDO:0021178 for injury
"""
validator = validator_with_adata
obs = validator.adata.obs
# Invalid ontology
obs.loc[obs.index[0], "disease_ontology_term_id"] = "EFO:0000001"
validator.validate_adata()
assert validator.errors == [
"ERROR: 'EFO:0000001' in 'disease_ontology_term_id' is not a valid ontology term id of 'MONDO, PATO'. "
"Only 'PATO:0000461' (normal), 'MONDO:0021178' (injury) or descendant terms thereof, or descendant terms of 'MONDO:0000001' (disease) are allowed"
]
# Invalid PATO term id
validator.errors = []
obs.loc[obs.index[0], "disease_ontology_term_id"] = "PATO:0001894"
validator.validate_adata()
assert validator.errors == [
"ERROR: 'PATO:0001894' in 'disease_ontology_term_id' is not an allowed term id. "
"Only 'PATO:0000461' (normal), 'MONDO:0021178' (injury) or descendant terms thereof, or descendant terms of 'MONDO:0000001' (disease) are allowed"
]
# Invalid MONDO term id - disease characteristic
validator.errors = []
obs.loc[obs.index[0], "disease_ontology_term_id"] = "MONDO:0021125"
validator.validate_adata()
assert validator.errors == [
"ERROR: 'MONDO:0021125' in 'disease_ontology_term_id' is not an allowed term id. "
"Only 'PATO:0000461' (normal), 'MONDO:0021178' (injury) or descendant terms thereof, or descendant terms of 'MONDO:0000001' (disease) are allowed"
]
# Invalid MONDO term id - disease parent term
validator.errors = []
obs.loc[obs.index[0], "disease_ontology_term_id"] = "MONDO:0000001"
validator.validate_adata()
assert validator.errors == [
"ERROR: 'MONDO:0000001' in 'disease_ontology_term_id' is not an allowed term id. "
"Only 'PATO:0000461' (normal), 'MONDO:0021178' (injury) or descendant terms thereof, or descendant terms of 'MONDO:0000001' (disease) are allowed"
]
# Valid PATO term id - healthy
validator.errors = []
obs.loc[obs.index[0], "disease_ontology_term_id"] = "PATO:0000461"
validator.validate_adata()
assert validator.errors == []
# Valid MONDO term id - disease descendant term
validator.errors = []
obs.loc[obs.index[0], "disease_ontology_term_id"] = "MONDO:0005491"
validator.validate_adata()
assert validator.errors == []
# Valid MONDO term id - injury parent term
validator.errors = []
obs.loc[obs.index[0], "disease_ontology_term_id"] = "MONDO:0021178"
validator.validate_adata()
assert validator.errors == []
# Valid MONDO term id - injury descendant term
validator.errors = []
obs.loc[obs.index[0], "disease_ontology_term_id"] = "MONDO:0015796"
validator.validate_adata()
assert validator.errors == []
def test_self_reported_ethnicity_ontology_term_id__unknown(self, validator_with_adata):
"""
Test 'unknown' self_reported_ethnicity_ontology_term is valid when used as single term
"""
validator = validator_with_adata
obs = validator.adata.obs
obs.loc[
obs.index[0],
"self_reported_ethnicity_ontology_term_id",
] = "unknown"
assert validator.validate_adata()
assert validator.errors == []
def test_cell_type_ontology_term_id__unknown(self, validator_with_adata):
"""
Test 'unknown' cell_type_ontology_term_id is valid
"""
validator = validator_with_adata
obs = validator.adata.obs
obs.at["Y", "cell_type_ontology_term_id"] = "unknown"
assert validator.validate_adata()
assert validator.errors == []
def test_tissue_ontology_term_id__unknown(self, validator_with_adata):
"""
Test 'unknown' tissue_ontology_term_id is valid if tissue_type is 'cell culture'
"""
validator = validator_with_adata
obs = validator.adata.obs
# Arrange -- relies on "tissue_type" value for index "Y" being "cell culture", set explicitly
obs.at["Y", "tissue_type"] = "cell culture"
obs.at["Y", "tissue_ontology_term_id"] = "unknown"
assert validator.validate_adata()
assert validator.errors == []
def test_tissue_ontology_term_id__unknown_invalid(self, validator_with_adata):
"""
Test 'unknown' tissue_ontology_term_id is invalid if tissue_type is NOT 'cell culture'
"""
validator = validator_with_adata
obs = validator.adata.obs
# Arrange -- 'tissue_ontology_term_id' cannot be "unknown" when 'tissue_type is "tissue"
obs.at["Y", "tissue_type"] = "tissue"
obs.at["Y", "tissue_ontology_term_id"] = "unknown"
assert not validator.validate_adata()
assert validator.errors == [
"ERROR: 'unknown' in 'tissue_ontology_term_id' is not a valid ontology term id of 'UBERON'. "
"When 'tissue_type' is 'tissue' or 'organoid', 'tissue_ontology_term_id' MUST be a descendant "
"term id of 'UBERON:0001062' (anatomical entity)."
]
def test_self_reported_ethnicity_ontology_term_id__unknown_in_multi_term(self, validator_with_adata):
"""
Test 'unknown' self_reported_ethnicity_ontology_term is invalid when used in multi-term comma-delimited str
"""
validator = validator_with_adata
error_message_suffix = validator.schema_def["components"]["obs"]["columns"][
"self_reported_ethnicity_ontology_term_id"
]["dependencies"][0]["error_message_suffix"]
validator.adata.obs.loc[
validator.adata.obs.index[0],
"self_reported_ethnicity_ontology_term_id",
] = "HANCESTRO:0005,HANCESTRO:0014,unknown"
validator.validate_adata()
assert validator.errors == [
self.get_format_error_message(
error_message_suffix,
"ERROR: 'unknown' in 'self_reported_ethnicity_ontology_term_id' is not a valid ontology term id "
"of 'HANCESTRO'.",
)
]
def test_self_reported_ethnicity_ontology_term_id__invalid_ontology(self, validator_with_adata):
"""
Test self_reported_ethnicity_ontology_term error message when passed a valid term from an invalid ontology
"""
validator = validator_with_adata
error_message_suffix = validator.schema_def["components"]["obs"]["columns"][
"self_reported_ethnicity_ontology_term_id"
]["dependencies"][0]["error_message_suffix"]
validator.adata.obs.loc[
validator.adata.obs.index[0],
"self_reported_ethnicity_ontology_term_id",
] = "EFO:0000001"
validator.validate_adata()
assert validator.errors == [
self.get_format_error_message(
error_message_suffix,
"ERROR: 'EFO:0000001' in 'self_reported_ethnicity_ontology_term_id' is not a valid ontology term "
"id of 'HANCESTRO'.",
)
]
def test_self_reported_ethnicity_ontology_term_id__forbidden_term(self, validator_with_adata):
"""
Test self_reported_ethnicity_ontology_term error message when passed an explicitly forbidden ontology term that
is otherwise valid
"""
validator = validator_with_adata
error_message_suffix = validator.schema_def["components"]["obs"]["columns"][
"self_reported_ethnicity_ontology_term_id"
]["dependencies"][0]["error_message_suffix"]
validator.adata.obs.loc[
validator.adata.obs.index[0],
"self_reported_ethnicity_ontology_term_id",
] = "HANCESTRO:0003"
validator.validate_adata()
assert validator.errors == [
self.get_format_error_message(
error_message_suffix,
"ERROR: 'HANCESTRO:0003' in 'self_reported_ethnicity_ontology_term_id' is not allowed.",
)
]
def test_self_reported_ethnicity_ontology_term_id__forbidden_term_ancestor(self, validator_with_adata):
"""
Test self_reported_ethnicity_ontology_term error message when passed an ontology term that has
both itself and its descendants forbidden
"""
validator = validator_with_adata
error_message_suffix = validator.schema_def["components"]["obs"]["columns"][
"self_reported_ethnicity_ontology_term_id"
]["dependencies"][0]["error_message_suffix"]
validator.adata.obs.loc[
validator.adata.obs.index[0],
"self_reported_ethnicity_ontology_term_id",
] = "HANCESTRO:0002"
validator.validate_adata()
assert validator.errors == [
self.get_format_error_message(
error_message_suffix,
"ERROR: 'HANCESTRO:0002' in 'self_reported_ethnicity_ontology_term_id' is not allowed.",
)
]
def test_self_reported_ethnicity_ontology_term_id__forbidden_term_descendant(self, validator_with_adata):
"""
Test self_reported_ethnicity_ontology_term error message when passed the descendant term of an ontology term that has
both itself and its descendants forbidden
"""
validator = validator_with_adata
error_message_suffix = validator.schema_def["components"]["obs"]["columns"][
"self_reported_ethnicity_ontology_term_id"
]["dependencies"][0]["error_message_suffix"]
validator.adata.obs.loc[
validator.adata.obs.index[0],
"self_reported_ethnicity_ontology_term_id",
] = "HANCESTRO:0306"
validator.validate_adata()
assert validator.errors == [
self.get_format_error_message(
error_message_suffix,
"ERROR: 'HANCESTRO:0306' in 'self_reported_ethnicity_ontology_term_id' is not allowed. Descendant terms "
"of 'HANCESTRO:0304' are not allowed.",
)
]
def test_self_reported_ethnicity_ontology_term_id__forbidden_term_in_multi_term(self, validator_with_adata):
"""
Test error message for self_reported_ethnicity_ontology_term_id involving a forbidden term among an otherwise
valid comma-delimited str of multiple terms
"""
validator = validator_with_adata
error_message_suffix = validator.schema_def["components"]["obs"]["columns"][
"self_reported_ethnicity_ontology_term_id"
]["dependencies"][0]["error_message_suffix"]
validator.adata.obs.loc[
validator.adata.obs.index[0],
"self_reported_ethnicity_ontology_term_id",
] = "HANCESTRO:0005,HANCESTRO:0014,HANCESTRO:0018"
validator.validate_adata()
assert validator.errors == [
self.get_format_error_message(
error_message_suffix,
"ERROR: 'HANCESTRO:0018' in 'self_reported_ethnicity_ontology_term_id' is not allowed.",
)
]
def test_self_reported_ethnicity_ontology_term_id__non_human(self, validator_with_adata):
"""
Test self_reported_ethnicity_ontology_term error message if term is not 'na' for a non-human organism
"""
validator = validator_with_adata
error_message_suffix = validator.schema_def["components"]["obs"]["columns"][
"self_reported_ethnicity_ontology_term_id"
]["error_message_suffix"]
# Mouse organism ID
validator.adata.obs.loc[validator.adata.obs.index[0], "organism_ontology_term_id"] = "NCBITaxon:10090"
# Required to set to avoid development_stage_ontology_term_id errors
validator.adata.obs.loc[validator.adata.obs.index[0], "development_stage_ontology_term_id"] = "MmusDv:0000003"
validator.adata.obs.loc[
validator.adata.obs.index[0],
"self_reported_ethnicity_ontology_term_id",
] = "HANCESTRO:0005"
validator.validate_adata()
assert validator.errors == [
self.get_format_error_message(
error_message_suffix,
"ERROR: 'HANCESTRO:0005' in 'self_reported_ethnicity_ontology_term_id' is not a "
"valid value of 'self_reported_ethnicity_ontology_term_id'.",
)
]
def test_self_reported_ethnicity_ontology_term_id__unsorted(self, validator_with_adata):
"""
Test error message for self_reported_ethnicity_ontology_term_id with valid comma-delimited terms in a str,
but NOT in ascending lexical order
"""
validator = validator_with_adata
error_message_suffix = validator.schema_def["components"]["obs"]["columns"][
"self_reported_ethnicity_ontology_term_id"
]["dependencies"][0]["error_message_suffix"]
validator.adata.obs.loc[
validator.adata.obs.index[0],
"self_reported_ethnicity_ontology_term_id",
] = "HANCESTRO:0014,HANCESTRO:0005"
validator.validate_adata()
assert validator.errors == [
self.get_format_error_message(
error_message_suffix,
"ERROR: 'HANCESTRO:0014,HANCESTRO:0005' in 'self_reported_ethnicity_ontology_term_id' is not in "
"ascending lexical order.",
)
]
def test_self_reported_ethnicity_ontology_term_id__invalid_delimiters(self, validator_with_adata):
"""
Test error message for self_reported_ethnicity_ontology_term_id involving
delimiters that are not specified in the schema definition yaml, such as whitespace
"""
validator = validator_with_adata
error_message_suffix = validator.schema_def["components"]["obs"]["columns"][
"self_reported_ethnicity_ontology_term_id"
]["dependencies"][0]["error_message_suffix"]
validator.adata.obs.loc[
validator.adata.obs.index[0],
"self_reported_ethnicity_ontology_term_id",
] = "HANCESTRO:0005, HANCESTRO:0014"
validator.validate_adata()
assert validator.errors == [
self.get_format_error_message(
error_message_suffix,
"ERROR: ' HANCESTRO:0014' in 'self_reported_ethnicity_ontology_term_id' is not a valid ontology "
"term id of 'HANCESTRO'.",
)
]
def test_self_reported_ethnicity_ontology_term_id__multiple_errors_in_multi_term(self, validator_with_adata):
"""
Test that multiple distinct error messages are reported for self_reported_ethnicity_ontology_term_id with
multiple different error types in a comma-delimited multi term str
"""
validator = validator_with_adata
error_message_suffix = validator.schema_def["components"]["obs"]["columns"][
"self_reported_ethnicity_ontology_term_id"
]["dependencies"][0]["error_message_suffix"]
validator.adata.obs.loc[
validator.adata.obs.index[0],
"self_reported_ethnicity_ontology_term_id",
] = "EFO:0000001,HANCESTRO:0004,HANCESTRO:0014,HANCESTRO:1"
validator.validate_adata()
assert validator.errors == [
self.get_format_error_message(
error_message_suffix,
"ERROR: 'EFO:0000001' in 'self_reported_ethnicity_ontology_term_id' is not a valid ontology term "
"id of 'HANCESTRO'.",
),
self.get_format_error_message(
error_message_suffix,
"ERROR: 'HANCESTRO:0004' in 'self_reported_ethnicity_ontology_term_id' is not allowed.",
),
self.get_format_error_message(
error_message_suffix,
"ERROR: 'HANCESTRO:1' in 'self_reported_ethnicity_ontology_term_id' is not a valid ontology term "
"id of 'HANCESTRO'.",
),