-
Notifications
You must be signed in to change notification settings - Fork 10
/
models.py
1710 lines (1422 loc) · 56.3 KB
/
models.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
from datetime import date, datetime
from enum import Enum
import os
import re
from typing import Any, Dict, List, Literal, Optional, Sequence, Type, TypeVar, Union
from warnings import warn
from pydantic import (
UUID4,
AnyHttpUrl,
BaseModel,
EmailStr,
Field,
GetJsonSchemaHandler,
TypeAdapter,
ValidationInfo,
field_validator,
model_validator,
)
from pydantic.json_schema import JsonSchemaValue
from pydantic_core import CoreSchema
from .consts import DANDI_SCHEMA_VERSION
from .digests.dandietag import DandiETag
from .digests.zarr import ZARR_CHECKSUM_PATTERN, parse_directory_digest
from .types import ByteSizeJsonSchema
from .utils import name2title
# Use DJANGO_DANDI_WEB_APP_URL to point to a specific deployment.
DANDI_INSTANCE_URL: Optional[str]
try:
DANDI_INSTANCE_URL = os.environ["DJANGO_DANDI_WEB_APP_URL"]
except KeyError:
DANDI_INSTANCE_URL = None
DANDI_INSTANCE_URL_PATTERN = ".*"
else:
# Ensure no trailing / for consistency
DANDI_INSTANCE_URL_PATTERN = re.escape(DANDI_INSTANCE_URL.rstrip("/"))
NAME_PATTERN = r"^([\w\s\-\.']+),\s+([\w\s\-\.']+)$"
UUID_PATTERN = (
"[a-f0-9]{8}[-]*[a-f0-9]{4}[-]*" "[a-f0-9]{4}[-]*[a-f0-9]{4}[-]*[a-f0-9]{12}$"
)
ASSET_UUID_PATTERN = r"^dandiasset:" + UUID_PATTERN
VERSION_PATTERN = r"\d{6}/\d+\.\d+\.\d+"
DANDI_DOI_PATTERN = rf"^10.(48324|80507)/dandi\.{VERSION_PATTERN}"
DANDI_PUBID_PATTERN = rf"^DANDI:{VERSION_PATTERN}"
PUBLISHED_VERSION_URL_PATTERN = (
rf"^{DANDI_INSTANCE_URL_PATTERN}/dandiset/{VERSION_PATTERN}$"
)
MD5_PATTERN = r"[0-9a-f]{32}"
SHA256_PATTERN = r"[0-9a-f]{64}"
M = TypeVar("M", bound=BaseModel)
def diff_models(model1: M, model2: M) -> None:
"""Perform a field-wise diff"""
for field in model1.model_fields:
if getattr(model1, field) != getattr(model2, field):
print(f"{field} is different")
class AccessType(Enum):
"""An enumeration of access status options"""
#: The dandiset is openly accessible
OpenAccess = "dandi:OpenAccess"
#: The dandiset is embargoed
EmbargoedAccess = "dandi:EmbargoedAccess"
"""
Uncomment when restricted access is implemented:
#: The dandiset is restricted
RestrictedAccess = "dandi:RestrictedAccess"
"""
class DigestType(Enum):
"""An enumeration of checksum types"""
#: MD5 checksum
md5 = "dandi:md5"
#: SHA1 checksum
sha1 = "dandi:sha1"
#: SHA2-256 checksum
sha2_256 = "dandi:sha2-256"
#: SHA3-256 checksum
sha3_256 = "dandi:sha3-256"
#: BLAKE2B-256 checksum
blake2b_256 = "dandi:blake2b-256"
#: BLAKE3-256 checksum
blake3 = "dandi:blake3"
#: S3-style ETag
dandi_etag = "dandi:dandi-etag"
#: DANDI Zarr checksum
dandi_zarr_checksum = "dandi:dandi-zarr-checksum"
class IdentifierType(Enum):
"""An enumeration of identifiers"""
doi = "dandi:doi"
orcid = "dandi:orcid"
ror = "dandi:ror"
dandi = "dandi:dandi"
rrid = "dandi:rrid"
class LicenseType(Enum):
"""An enumeration of supported licenses"""
CC0_10 = "spdx:CC0-1.0"
CC_BY_40 = "spdx:CC-BY-4.0"
class RelationType(Enum):
"""An enumeration of resource relations"""
#: Indicates that B includes A in a citation
IsCitedBy = "dcite:IsCitedBy"
#: Indicates that A includes B in a citation
Cites = "dcite:Cites"
#: Indicates that A is a supplement to B
IsSupplementTo = "dcite:IsSupplementTo"
#: Indicates that B is a supplement to A
IsSupplementedBy = "dcite:IsSupplementedBy"
#: Indicates A is continued by the work B
IsContinuedBy = "dcite:IsContinuedBy"
#: Indicates A is a continuation of the work B
Continues = "dcite:Continues"
#: Indicates A describes B
Describes = "dcite:Describes"
#: Indicates A is described by B
IsDescribedBy = "dcite:IsDescribedBy"
#: Indicates resource A has additional metadata B
HasMetadata = "dcite:HasMetadata"
#: Indicates additional metadata A for a resource B
IsMetadataFor = "dcite:IsMetadataFor"
#: Indicates A has a version (B)
HasVersion = "dcite:HasVersion"
#: Indicates A is a version of B
IsVersionOf = "dcite:IsVersionOf"
#: Indicates A is a new edition of B
IsNewVersionOf = "dcite:IsNewVersionOf"
#: Indicates A is a previous edition of B
IsPreviousVersionOf = "dcite:IsPreviousVersionOf"
#: Indicates A is a portion of B
IsPartOf = "dcite:IsPartOf"
#: Indicates A includes the part B
HasPart = "dcite:HasPart"
#: Indicates A is used as a source of information by B
IsReferencedBy = "dcite:IsReferencedBy"
#: Indicates B is used as a source of information for A
References = "dcite:References"
#: Indicates B is documentation about/explaining A
IsDocumentedBy = "dcite:IsDocumentedBy"
#: Indicates A is documentation about B
Documents = "dcite:Documents"
#: Indicates B is used to compile or create A
IsCompiledBy = "dcite:IsCompiledBy"
#: Indicates B is the result of a compile or creation event using A
Compiles = "dcite:Compiles"
#: Indicates A is a variant or different form of B
IsVariantFormOf = "dcite:IsVariantFormOf"
#: Indicates A is the original form of B
IsOriginalFormOf = "dcite:IsOriginalFormOf"
#: Indicates that A is identical to B
IsIdenticalTo = "dcite:IsIdenticalTo"
#: Indicates that A is reviewed by B
IsReviewedBy = "dcite:IsReviewedBy"
#: Indicates that A is a review of B
Reviews = "dcite:Reviews"
#: Indicates B is a source upon which A is based
IsDerivedFrom = "dcite:IsDerivedFrom"
#: Indicates A is a source upon which B is based
IsSourceOf = "dcite:IsSourceOf"
#: Indicates A is required by B
IsRequiredBy = "dcite:IsRequiredBy"
#: Indicates A requires B
Requires = "dcite:Requires"
#: Indicates A replaces B
Obsoletes = "dcite:Obsoletes"
#: Indicates A is replaced by B
IsObsoletedBy = "dcite:IsObsoletedBy"
#: Indicates A is published in B
IsPublishedIn = "dcite:IsPublishedIn"
class ParticipantRelationType(Enum):
"""An enumeration of participant relations"""
#: Indicates that A is a child of B
isChildOf = "dandi:isChildOf"
#: Indicates that A is a parent of B
isParentOf = "dandi:isParentOf"
#: Indicates that A is a sibling of B
isSiblingOf = "dandi:isSiblingOf"
#: Indicates that A is a monozygotic twin of B
isMonozygoticTwinOf = "dandi:isMonozygoticTwinOf"
#: Indicates that A is a dizygotic twin of B
isDizygoticTwinOf = "dandi:isDizygoticTwinOf"
class RoleType(Enum):
"""An enumeration of roles"""
#: Author
Author = "dcite:Author"
#: Conceptualization
Conceptualization = "dcite:Conceptualization"
#: Contact Person
ContactPerson = "dcite:ContactPerson"
#: Data Collector
DataCollector = "dcite:DataCollector"
#: Data Curator
DataCurator = "dcite:DataCurator"
#: Data Manager
DataManager = "dcite:DataManager"
#: Formal Analysis
FormalAnalysis = "dcite:FormalAnalysis"
#: Funding Acquisition
FundingAcquisition = "dcite:FundingAcquisition"
#: Investigation
Investigation = "dcite:Investigation"
#: Maintainer
Maintainer = "dcite:Maintainer"
#: Methodology
Methodology = "dcite:Methodology"
#: Producer
Producer = "dcite:Producer"
#: Project Leader
ProjectLeader = "dcite:ProjectLeader"
#: Project Manager
ProjectManager = "dcite:ProjectManager"
#: Project Member
ProjectMember = "dcite:ProjectMember"
#: Project Administration
ProjectAdministration = "dcite:ProjectAdministration"
#: Researcher
Researcher = "dcite:Researcher"
#: Resources
Resources = "dcite:Resources"
#: Software
Software = "dcite:Software"
#: Supervision
Supervision = "dcite:Supervision"
#: Validation
Validation = "dcite:Validation"
#: Visualization
Visualization = "dcite:Visualization"
#: Funder
Funder = "dcite:Funder"
#: Sponsor
Sponsor = "dcite:Sponsor"
#: Participant in a study
StudyParticipant = "dcite:StudyParticipant"
#: Affiliated with an entity
Affiliation = "dcite:Affiliation"
#: Approved ethics protocol
EthicsApproval = "dcite:EthicsApproval"
#: Other
Other = "dcite:Other"
class AgeReferenceType(Enum):
"""An enumeration of age reference"""
#: Age since Birth
BirthReference = "dandi:BirthReference"
#: Age of a pregnancy (https://en.wikipedia.org/wiki/Gestational_age)
GestationalReference = "dandi:GestationalReference"
class DandiBaseModel(BaseModel):
id: Optional[str] = Field(
default=None,
description="Uniform resource identifier",
json_schema_extra={"readOnly": True},
)
schemaKey: str = Field(
"DandiBaseModel", validate_default=True, json_schema_extra={"readOnly": True}
)
def json_dict(self) -> dict:
"""
Recursively convert the instance to a `dict` of JSONable values,
including converting enum values to strings. `None` fields
are omitted.
"""
warn(
"`DandiBaseModel.json_dict()` is deprecated. Use "
"`pydantic.BaseModel.model_dump(mode='json', exclude_none=True)` instead.",
DeprecationWarning,
stacklevel=2,
)
return self.model_dump(mode="json", exclude_none=True)
@field_validator("schemaKey")
@classmethod
def ensure_schemakey(cls, val: str) -> str:
tempval = val
if "Published" in cls.__name__:
tempval = "Published" + tempval
elif "BareAsset" == cls.__name__:
tempval = "Bare" + tempval
if tempval != cls.__name__:
raise ValueError(
f"schemaKey {tempval} does not match classname {cls.__name__}"
)
return val
@classmethod
def unvalidated(__pydantic_cls__: Type[M], **data: Any) -> M:
"""Allow model to be returned without validation"""
warn(
"`DandiBaseModel.unvalidated()` is deprecated. "
"Use `pydantic.BaseModel.model_construct()` instead.",
DeprecationWarning,
stacklevel=2,
)
return __pydantic_cls__.model_construct(**data)
@classmethod
def to_dictrepr(__pydantic_cls__: Type["DandiBaseModel"]) -> str:
return (
__pydantic_cls__.model_construct()
.__repr__()
.replace(__pydantic_cls__.__name__, "dict")
)
@classmethod
def __get_pydantic_json_schema__(
cls,
core_schema_: CoreSchema,
handler: GetJsonSchemaHandler,
) -> JsonSchemaValue:
schema = handler(core_schema_)
schema = handler.resolve_ref_schema(schema)
if schema["title"] == "PropertyValue":
schema["required"] = sorted({"value"}.union(schema.get("required", [])))
schema["title"] = name2title(schema["title"])
if schema["type"] == "object":
schema["required"] = sorted({"schemaKey"}.union(schema.get("required", [])))
for prop, value in schema.get("properties", {}).items():
if schema["title"] == "Person":
if prop == "name":
# JSON schema doesn't support validating unicode
# characters using the \w pattern, but Python does. So
# we are dropping the regex pattern for the schema.
del value["pattern"]
if value.get("title") is None or value["title"] == prop.title():
value["title"] = name2title(prop)
if re.match("\\^https?://", value.get("pattern", "")):
value["format"] = "uri"
if value.get("format", None) == "uri":
value["maxLength"] = 1000
allOf = value.get("allOf")
anyOf = value.get("anyOf")
items = value.get("items")
if allOf is not None:
if len(allOf) == 1 and "$ref" in allOf[0]:
value["$ref"] = allOf[0]["$ref"]
del value["allOf"]
elif len(allOf) > 1:
value["oneOf"] = value["allOf"]
value["type"] = "object"
del value["allOf"]
if anyOf is not None:
if len(anyOf) > 1 and any(["$ref" in val for val in anyOf]):
value["type"] = "object"
if items is not None:
anyOf = items.get("anyOf")
if (
anyOf is not None
and len(anyOf) > 1
and any(["$ref" in val for val in anyOf])
):
value["items"]["type"] = "object"
# In pydantic 1.8+ all Literals are mapped on to enum
# This presently breaks the schema editor UI. Revert
# to const when generating the schema.
# Note: this no longer happens with custom metaclass
if prop == "schemaKey":
if "enum" in value and len(value["enum"]) == 1:
value["const"] = value["enum"][0]
del value["enum"]
else:
value["const"] = value["default"]
if "readOnly" in value:
del value["readOnly"]
return schema
class PropertyValue(DandiBaseModel):
maxValue: Optional[float] = Field(None, json_schema_extra={"nskey": "schema"})
minValue: Optional[float] = Field(None, json_schema_extra={"nskey": "schema"})
unitText: Optional[str] = Field(None, json_schema_extra={"nskey": "schema"})
value: Union[Any, List[Any]] = Field(
None,
validate_default=True,
json_schema_extra={"nskey": "schema"},
description="The value associated with this property.",
)
valueReference: Optional["PropertyValue"] = Field(
None, json_schema_extra={"nskey": "schema"}
) # Note: recursive (circular or not)
propertyID: Optional[Union[IdentifierType, AnyHttpUrl]] = Field(
None,
description="A commonly used identifier for"
"the characteristic represented by the property. "
"For example, a known prefix like DOI or a full URL.",
json_schema_extra={"nskey": "schema"},
)
schemaKey: Literal["PropertyValue"] = Field(
"PropertyValue", validate_default=True, json_schema_extra={"readOnly": True}
)
@field_validator("value")
@classmethod
def ensure_value(cls, val: Union[Any, List[Any]]) -> Union[Any, List[Any]]:
if not val:
raise ValueError(
"The value field of a PropertyValue cannot be None or empty."
)
return val
_ldmeta = {"nskey": "schema"}
# This is mostly not needed at all since self-referencing models
# are automatically resolved by Pydantic in a pretty consistent way even in Pydantic V1
# https://docs.pydantic.dev/1.10/usage/postponed_annotations/#self-referencing-models
# and continue to be so in Pydantic V2
# https://docs.pydantic.dev/latest/concepts/postponed_annotations/#self-referencing-or-recursive-models
PropertyValue.model_rebuild()
Identifier = str
ORCID = str
RORID = str
DANDI = str
RRID = str
class BaseType(DandiBaseModel):
"""Base class for enumerated types"""
identifier: Optional[Union[AnyHttpUrl, str]] = Field(
None,
description="The identifier can be any url or a compact URI, preferably"
" supported by identifiers.org.",
pattern=r"^[a-zA-Z0-9-]+:[a-zA-Z0-9-/\._]+$",
json_schema_extra={"nskey": "schema"},
)
name: Optional[str] = Field(
None,
description="The name of the item.",
max_length=150,
json_schema_extra={"nskey": "schema"},
)
schemaKey: str = Field(
"BaseType", validate_default=True, json_schema_extra={"readOnly": True}
)
_ldmeta = {"rdfs:subClassOf": ["prov:Entity", "schema:Thing"], "nskey": "dandi"}
@classmethod
def __get_pydantic_json_schema__(
cls,
core_schema_: CoreSchema,
handler: GetJsonSchemaHandler,
) -> JsonSchemaValue:
schema = super().__get_pydantic_json_schema__(core_schema_, handler)
for prop, value in schema.get("properties", {}).items():
# This check removes the anyOf field from the identifier property
# in the schema generation. This relates to a UI issue where two
# basic properties, in this case "string", is dropped from the UI.
if prop == "identifier":
for option in value.pop("anyOf", []):
if option.get("format", "") == "uri":
value.update(**option)
value["maxLength"] = 1000
return schema
class AssayType(BaseType):
"""OBI based identifier for the assay(s) used"""
schemaKey: Literal["AssayType"] = Field(
"AssayType", validate_default=True, json_schema_extra={"readOnly": True}
)
class SampleType(BaseType):
"""OBI based identifier for the sample type used"""
schemaKey: Literal["SampleType"] = Field(
"SampleType", validate_default=True, json_schema_extra={"readOnly": True}
)
class Anatomy(BaseType):
"""UBERON or other identifier for anatomical part studied"""
schemaKey: Literal["Anatomy"] = Field(
"Anatomy", validate_default=True, json_schema_extra={"readOnly": True}
)
class StrainType(BaseType):
"""Identifier for the strain of the sample"""
schemaKey: Literal["StrainType"] = Field(
"StrainType", validate_default=True, json_schema_extra={"readOnly": True}
)
class SexType(BaseType):
"""Identifier for the sex of the sample"""
schemaKey: Literal["SexType"] = Field(
"SexType", validate_default=True, json_schema_extra={"readOnly": True}
)
class SpeciesType(BaseType):
"""Identifier for species of the sample"""
schemaKey: Literal["SpeciesType"] = Field(
"SpeciesType", validate_default=True, json_schema_extra={"readOnly": True}
)
class Disorder(BaseType):
"""Biolink, SNOMED, or other identifier for disorder studied"""
dxdate: Optional[List[Union[date, datetime]]] = Field(
None,
title="Dates of diagnosis",
description="Dates of diagnosis",
json_schema_extra={"nskey": "dandi", "rangeIncludes": "schema:Date"},
)
schemaKey: Literal["Disorder"] = Field(
"Disorder", validate_default=True, json_schema_extra={"readOnly": True}
)
class GenericType(BaseType):
"""An object to capture any type for about"""
schemaKey: Literal["GenericType"] = Field(
"GenericType", validate_default=True, json_schema_extra={"readOnly": True}
)
class ApproachType(BaseType):
"""Identifier for approach used"""
schemaKey: Literal["ApproachType"] = Field(
"ApproachType", validate_default=True, json_schema_extra={"readOnly": True}
)
class MeasurementTechniqueType(BaseType):
"""Identifier for measurement technique used"""
schemaKey: Literal["MeasurementTechniqueType"] = Field(
"MeasurementTechniqueType",
validate_default=True,
json_schema_extra={"readOnly": True},
)
class StandardsType(BaseType):
"""Identifier for data standard used"""
schemaKey: Literal["StandardsType"] = Field(
"StandardsType", validate_default=True, json_schema_extra={"readOnly": True}
)
nwb_standard = StandardsType(
name="Neurodata Without Borders (NWB)",
identifier="RRID:SCR_015242",
).model_dump(mode="json", exclude_none=True)
bids_standard = StandardsType(
name="Brain Imaging Data Structure (BIDS)",
identifier="RRID:SCR_016124",
).model_dump(mode="json", exclude_none=True)
class ContactPoint(DandiBaseModel):
email: Optional[EmailStr] = Field(
None,
description="Email address of contact.",
json_schema_extra={"nskey": "schema"},
)
url: Optional[AnyHttpUrl] = Field(
None,
description="A Web page to find information on how to contact.",
json_schema_extra={"nskey": "schema"},
)
schemaKey: Literal["ContactPoint"] = Field(
"ContactPoint", validate_default=True, json_schema_extra={"readOnly": True}
)
_ldmeta = {"nskey": "schema"}
class Contributor(DandiBaseModel):
identifier: Optional[Identifier] = Field(
None,
title="A common identifier",
description="Use a common identifier such as ORCID (orcid.org) for "
"people or ROR (ror.org) for institutions.",
json_schema_extra={"nskey": "schema"},
)
name: Optional[str] = Field(None, json_schema_extra={"nskey": "schema"})
email: Optional[EmailStr] = Field(None, json_schema_extra={"nskey": "schema"})
url: Optional[AnyHttpUrl] = Field(None, json_schema_extra={"nskey": "schema"})
roleName: Optional[List[RoleType]] = Field(
None,
title="Role",
description="Role(s) of the contributor. Multiple roles can be selected.",
json_schema_extra={"nskey": "schema"},
)
includeInCitation: bool = Field(
True,
title="Include contributor in citation",
description="A flag to indicate whether a contributor should be included "
"when generating a citation for the item.",
json_schema_extra={"nskey": "dandi"},
)
awardNumber: Optional[Identifier] = Field(
None,
title="Identifier for an award",
description="Identifier associated with a sponsored or gift award.",
json_schema_extra={"nskey": "dandi"},
)
schemaKey: Literal["Contributor", "Organization", "Person"] = Field(
"Contributor", validate_default=True, json_schema_extra={"readOnly": True}
)
class Organization(Contributor):
identifier: Optional[RORID] = Field(
None,
title="A ror.org identifier",
description="Use an ror.org identifier for institutions.",
pattern=r"^https://ror.org/[a-z0-9]+$",
json_schema_extra={"nskey": "schema"},
)
includeInCitation: bool = Field(
False,
title="Include contributor in citation",
description="A flag to indicate whether a contributor should be included "
"when generating a citation for the item",
json_schema_extra={"nskey": "dandi"},
)
contactPoint: Optional[List[ContactPoint]] = Field(
None,
title="Organization contact information",
description="Contact for the organization",
json_schema_extra={"nskey": "schema"},
)
schemaKey: Literal["Organization"] = Field(
"Organization", validate_default=True, json_schema_extra={"readOnly": True}
)
_ldmeta = {
"rdfs:subClassOf": ["schema:Organization", "prov:Organization"],
"nskey": "dandi",
}
class Affiliation(DandiBaseModel):
identifier: Optional[RORID] = Field(
None,
title="A ror.org identifier",
description="Use an ror.org identifier for institutions.",
pattern=r"^https://ror.org/[a-z0-9]+$",
json_schema_extra={"nskey": "schema"},
)
name: str = Field(
json_schema_extra={"nskey": "schema"}, description="Name of organization"
)
schemaKey: Literal["Affiliation"] = Field(
"Affiliation", validate_default=True, json_schema_extra={"readOnly": True}
)
_ldmeta = {
"rdfs:subClassOf": ["schema:Organization", "prov:Organization"],
"nskey": "dandi",
}
class Person(Contributor):
identifier: Optional[ORCID] = Field(
None,
title="An ORCID identifier",
description="An ORCID (orcid.org) identifier for an individual.",
pattern=r"^\d{4}-\d{4}-\d{4}-(\d{3}X|\d{4})$",
json_schema_extra={"nskey": "schema"},
)
name: str = Field(
description="Use the format: familyname, given names ...",
pattern=NAME_PATTERN,
json_schema_extra={"nskey": "schema"},
examples=["Lovelace, Augusta Ada", "Smith, John", "Chan, Kong-sang"],
)
affiliation: Optional[List[Affiliation]] = Field(
None,
description="An organization that this person is affiliated with.",
json_schema_extra={"nskey": "schema"},
)
schemaKey: Literal["Person"] = Field(
"Person", validate_default=True, json_schema_extra={"readOnly": True}
)
_ldmeta = {"rdfs:subClassOf": ["schema:Person", "prov:Person"], "nskey": "dandi"}
class Software(DandiBaseModel):
identifier: Optional[RRID] = Field(
None,
pattern=r"^RRID\:.*",
title="Research resource identifier",
description="RRID of the software from scicrunch.org.",
json_schema_extra={"nskey": "schema"},
)
name: str = Field(json_schema_extra={"nskey": "schema"})
version: str = Field(json_schema_extra={"nskey": "schema"})
url: Optional[AnyHttpUrl] = Field(
None,
description="Web page for the software.",
json_schema_extra={"nskey": "schema"},
)
schemaKey: Literal["Software"] = Field(
"Software", validate_default=True, json_schema_extra={"readOnly": True}
)
_ldmeta = {
"rdfs:subClassOf": ["schema:SoftwareApplication", "prov:Software"],
"nskey": "dandi",
}
class Agent(DandiBaseModel):
identifier: Optional[Identifier] = Field(
None,
title="Identifier",
description="Identifier for an agent.",
json_schema_extra={"nskey": "schema"},
)
name: str = Field(
json_schema_extra={"nskey": "schema"},
)
url: Optional[AnyHttpUrl] = Field(None, json_schema_extra={"nskey": "schema"})
schemaKey: Literal["Agent"] = Field(
"Agent", validate_default=True, json_schema_extra={"readOnly": True}
)
_ldmeta = {
"rdfs:subClassOf": ["prov:Agent"],
"nskey": "dandi",
}
class EthicsApproval(DandiBaseModel):
"""Information about ethics committee approval for project"""
identifier: Identifier = Field(
json_schema_extra={"nskey": "schema"},
title="Approved protocol identifier",
description="Approved Protocol identifier, often a number or alphanumeric string.",
)
contactPoint: Optional[ContactPoint] = Field(
None,
description="Information about the ethics approval committee.",
json_schema_extra={"nskey": "schema"},
)
schemaKey: Literal["EthicsApproval"] = Field(
"EthicsApproval", validate_default=True, json_schema_extra={"readOnly": True}
)
_ldmeta = {"rdfs:subClassOf": ["schema:Thing", "prov:Entity"], "nskey": "dandi"}
class Resource(DandiBaseModel):
identifier: Optional[Identifier] = Field(
None, json_schema_extra={"nskey": "schema"}
)
name: Optional[str] = Field(
None, title="A title of the resource", json_schema_extra={"nskey": "schema"}
)
url: Optional[AnyHttpUrl] = Field(
None, title="URL of the resource", json_schema_extra={"nskey": "schema"}
)
repository: Optional[str] = Field(
None,
title="Name of the repository",
description="Name of the repository in which the resource is housed.",
json_schema_extra={"nskey": "dandi"},
)
relation: RelationType = Field(
title="Resource relation",
description="Indicates how the resource is related to the dataset. "
"This relation should satisfy: dandiset <relation> resource.",
json_schema_extra={"nskey": "dandi"},
)
schemaKey: Literal["Resource"] = Field(
"Resource", validate_default=True, json_schema_extra={"readOnly": True}
)
_ldmeta = {
"rdfs:subClassOf": ["schema:CreativeWork", "prov:Entity"],
"rdfs:comment": "A resource related to the project (e.g., another "
"dataset, publication, Webpage)",
"nskey": "dandi",
}
@model_validator(mode="after")
def identifier_or_url(self) -> "Resource":
identifier, url = self.identifier, self.url
if identifier is None and url is None:
raise ValueError("Both identifier and url cannot be None")
return self
class AccessRequirements(DandiBaseModel):
"""Information about access options for the dataset"""
status: AccessType = Field(
title="Access status",
description="The access status of the item.",
json_schema_extra={"nskey": "dandi"},
)
contactPoint: Optional[ContactPoint] = Field(
None,
description="Who or where to look for information about access.",
json_schema_extra={"nskey": "schema"},
)
description: Optional[str] = Field(
None,
description="Information about access requirements when embargoed or restricted",
json_schema_extra={"nskey": "schema"},
)
embargoedUntil: Optional[date] = Field(
None,
title="Embargo end date",
description="Date on which embargo ends.",
json_schema_extra={
"readOnly": True,
"nskey": "dandi",
"rangeIncludes": "schema:Date",
},
)
schemaKey: Literal["AccessRequirements"] = Field(
"AccessRequirements",
validate_default=True,
json_schema_extra={"readOnly": True},
)
_ldmeta = {"rdfs:subClassOf": ["schema:Thing", "prov:Entity"], "nskey": "dandi"}
@model_validator(mode="after")
def open_or_embargoed(self) -> "AccessRequirements":
status, embargoed = self.status, self.embargoedUntil
if status == AccessType.EmbargoedAccess and embargoed is None:
raise ValueError(
"An embargo end date is required for NIH awards to be in "
"compliance with NIH resource sharing policy."
)
return self
class AssetsSummary(DandiBaseModel):
"""Summary over assets contained in a dandiset (published or not)"""
# stats which are not stats
numberOfBytes: int = Field(
json_schema_extra={"readOnly": True, "sameas": "schema:contentSize"}
)
numberOfFiles: int = Field(json_schema_extra={"readOnly": True}) # universe
numberOfSubjects: Optional[int] = Field(
None, json_schema_extra={"readOnly": True}
) # NWB + BIDS
numberOfSamples: Optional[int] = Field(
None, json_schema_extra={"readOnly": True}
) # more of NWB
numberOfCells: Optional[int] = Field(None, json_schema_extra={"readOnly": True})
dataStandard: Optional[List[StandardsType]] = Field(
None, json_schema_extra={"readOnly": True}
)
# Web UI: icons per each modality?
approach: Optional[List[ApproachType]] = Field(
None, json_schema_extra={"readOnly": True}
)
# Web UI: could be an icon with number, which if hovered on show a list?
measurementTechnique: Optional[List[MeasurementTechniqueType]] = Field(
None, json_schema_extra={"readOnly": True, "nskey": "schema"}
)
variableMeasured: Optional[List[str]] = Field(
None, json_schema_extra={"readOnly": True, "nskey": "schema"}
)
species: Optional[List[SpeciesType]] = Field(
None, json_schema_extra={"readOnly": True}
)
schemaKey: Literal["AssetsSummary"] = Field(
"AssetsSummary", validate_default=True, json_schema_extra={"readOnly": True}
)
_ldmeta = {
"rdfs:subClassOf": ["schema:CreativeWork", "prov:Entity"],
"nskey": "dandi",
}
class Equipment(DandiBaseModel):