-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinkml_tutorial_2024_pydantic_model.py
204 lines (171 loc) · 10.7 KB
/
linkml_tutorial_2024_pydantic_model.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
from __future__ import annotations
from datetime import (
datetime,
date,
time
)
from decimal import Decimal
from enum import Enum
import re
import sys
from typing import (
Any,
ClassVar,
List,
Literal,
Dict,
Optional,
Union
)
from pydantic import (
BaseModel,
ConfigDict,
Field,
RootModel,
field_validator
)
metamodel_version = "None"
version = "None"
class ConfiguredBaseModel(BaseModel):
model_config = ConfigDict(
validate_assignment = True,
validate_default = True,
extra = "forbid",
arbitrary_types_allowed = True,
use_enum_values = True,
strict = False,
)
pass
class LinkMLMeta(RootModel):
root: Dict[str, Any] = {}
model_config = ConfigDict(frozen=True)
def __getattr__(self, key:str):
return getattr(self.root, key)
def __getitem__(self, key:str):
return self.root[key]
def __setitem__(self, key:str, value):
self.root[key] = value
def __contains__(self, key:str) -> bool:
return key in self.root
linkml_meta = LinkMLMeta({'default_prefix': 'linkml_tutorial_2024',
'default_range': 'string',
'description': 'A repostitory that walks through schema generation.',
'id': 'https://w3id.org/linkml/linkml-tutorial-2024',
'imports': ['linkml:types'],
'license': 'MIT',
'name': 'linkml-tutorial-2024',
'prefixes': {'ENVO': {'prefix_prefix': 'ENVO',
'prefix_reference': 'http://purl.obolibrary.org/obo/ENVO_'},
'KBase': {'prefix_prefix': 'KBase',
'prefix_reference': 'https://kbase.us/'},
'PATO': {'prefix_prefix': 'PATO',
'prefix_reference': 'http://purl.obolibrary.org/obo/PATO_'},
'SIO': {'prefix_prefix': 'SIO',
'prefix_reference': 'http://semanticscience.org/resource/'},
'biolink': {'prefix_prefix': 'biolink',
'prefix_reference': 'https://w3id.org/biolink/'},
'example': {'prefix_prefix': 'example',
'prefix_reference': 'https://example.org/'},
'linkml': {'prefix_prefix': 'linkml',
'prefix_reference': 'https://w3id.org/linkml/'},
'linkml_tutorial_2024': {'prefix_prefix': 'linkml_tutorial_2024',
'prefix_reference': 'https://w3id.org/linkml/linkml-tutorial-2024/'},
'nmdc': {'prefix_prefix': 'nmdc',
'prefix_reference': 'https://w3id.org/nmdc/'},
'obo': {'prefix_prefix': 'obo',
'prefix_reference': 'http://purl.obolibrary.org/obo/'},
'schema': {'prefix_prefix': 'schema',
'prefix_reference': 'http://schema.org/'}},
'see_also': ['https://linkml.github.io/linkml-tutorial-2024'],
'source_file': 'src/linkml_tutorial_2024/schema/linkml_tutorial_2024.yaml',
'title': 'linkml-tutorial-2024'} )
class BiomeTypeEnum(str, Enum):
"""
The type of biome.
"""
forest = "forest"
lake = "lake"
ocean = "ocean"
desert = "desert"
air = "air"
class SpeciesEnum(str):
"""
The species of micro organisms collected in the sample.
"""
pass
class SampleCollection(ConfiguredBaseModel):
"""
A collection of samples.
"""
linkml_meta: ClassVar[LinkMLMeta] = LinkMLMeta({'from_schema': 'https://w3id.org/linkml/linkml-tutorial-2024',
'tree_root': True})
samples: Optional[Dict[str, Union[Sample,AirSample,SoilSample]]] = Field(None, description="""The samples in the collection.""", json_schema_extra = { "linkml_meta": {'alias': 'samples', 'domain_of': ['SampleCollection']} })
class Sample(ConfiguredBaseModel):
"""
A sample is a limited quantity of something (e.g. an individual or set of individuals from a population, or a portion of a substance) to be used for testing, analysis, inspection, investigation, demonstration, or trial use.
"""
linkml_meta: ClassVar[LinkMLMeta] = LinkMLMeta({'aliases': ['Biosample', 'Environmental Sample'],
'class_uri': 'SIO:001050',
'exact_mappings': ['SIO:001050'],
'from_schema': 'https://w3id.org/linkml/linkml-tutorial-2024',
'id_prefixes': ['KBase', 'nmdc']})
id: str = Field(..., description="""The unique identifier for the biosample.""", json_schema_extra = { "linkml_meta": {'alias': 'id', 'domain_of': ['Sample']} })
latitude: Optional[float] = Field(None, description="""Latitude is a geographic coordinate which refers to the angle from a point on the Earth's surface to the equatorial plane.""", ge=-90, le=90, json_schema_extra = { "linkml_meta": {'alias': 'latitude', 'domain_of': ['Sample'], 'slot_uri': 'schema:latitude'} })
longitude: Optional[float] = Field(None, description="""Longitude is a geographic position that refers to the angle east or west of a reference meridian between the two geographical poles to another meridian that passes through an arbitrary point.""", json_schema_extra = { "linkml_meta": {'alias': 'longitude', 'domain_of': ['Sample'], 'slot_uri': 'schema:longitude'} })
species: Optional[List[SpeciesEnum]] = Field(None, description="""The species of micro organisms collected in the sample.""", json_schema_extra = { "linkml_meta": {'alias': 'species', 'domain_of': ['Sample']} })
sample_biome: Optional[BiomeTypeEnum] = Field(None, description="""The biome type of the biosample""", json_schema_extra = { "linkml_meta": {'alias': 'sample_biome', 'domain_of': ['Sample']} })
sample_type: Literal["Sample"] = Field("Sample", description="""The type of sample.""", json_schema_extra = { "linkml_meta": {'alias': 'sample_type', 'designates_type': True, 'domain_of': ['Sample']} })
class AirSample(Sample):
"""
A sample of air
"""
linkml_meta: ClassVar[LinkMLMeta] = LinkMLMeta({'from_schema': 'https://w3id.org/linkml/linkml-tutorial-2024',
'slot_usage': {'id': {'name': 'id', 'pattern': '^airsample:\\d*'}}})
altitude: Optional[float] = Field(None, description="""Altitude is the height of an object or point in relation to a specific reference point, such as the sea level.""", json_schema_extra = { "linkml_meta": {'alias': 'altitude', 'domain_of': ['AirSample']} })
id: str = Field(..., description="""The unique identifier for the biosample.""", json_schema_extra = { "linkml_meta": {'alias': 'id', 'domain_of': ['Sample']} })
latitude: Optional[float] = Field(None, description="""Latitude is a geographic coordinate which refers to the angle from a point on the Earth's surface to the equatorial plane.""", ge=-90, le=90, json_schema_extra = { "linkml_meta": {'alias': 'latitude', 'domain_of': ['Sample'], 'slot_uri': 'schema:latitude'} })
longitude: Optional[float] = Field(None, description="""Longitude is a geographic position that refers to the angle east or west of a reference meridian between the two geographical poles to another meridian that passes through an arbitrary point.""", json_schema_extra = { "linkml_meta": {'alias': 'longitude', 'domain_of': ['Sample'], 'slot_uri': 'schema:longitude'} })
species: Optional[List[SpeciesEnum]] = Field(None, description="""The species of micro organisms collected in the sample.""", json_schema_extra = { "linkml_meta": {'alias': 'species', 'domain_of': ['Sample']} })
sample_biome: Optional[BiomeTypeEnum] = Field(None, description="""The biome type of the biosample""", json_schema_extra = { "linkml_meta": {'alias': 'sample_biome', 'domain_of': ['Sample']} })
sample_type: Literal["AirSample"] = Field("AirSample", description="""The type of sample.""", json_schema_extra = { "linkml_meta": {'alias': 'sample_type', 'designates_type': True, 'domain_of': ['Sample']} })
@field_validator('id')
def pattern_id(cls, v):
pattern=re.compile(r"^airsample:\d*")
if isinstance(v,list):
for element in v:
if not pattern.match(element):
raise ValueError(f"Invalid id format: {element}")
elif isinstance(v,str):
if not pattern.match(v):
raise ValueError(f"Invalid id format: {v}")
return v
class SoilSample(Sample):
"""
A sample of soil
"""
linkml_meta: ClassVar[LinkMLMeta] = LinkMLMeta({'from_schema': 'https://w3id.org/linkml/linkml-tutorial-2024',
'slot_usage': {'id': {'name': 'id', 'pattern': '^soilsample:\\d*'}}})
depth: Optional[int] = Field(None, description="""The depth in centimeters of the biosample.""", json_schema_extra = { "linkml_meta": {'alias': 'depth', 'domain_of': ['SoilSample']} })
id: str = Field(..., description="""The unique identifier for the biosample.""", json_schema_extra = { "linkml_meta": {'alias': 'id', 'domain_of': ['Sample']} })
latitude: Optional[float] = Field(None, description="""Latitude is a geographic coordinate which refers to the angle from a point on the Earth's surface to the equatorial plane.""", ge=-90, le=90, json_schema_extra = { "linkml_meta": {'alias': 'latitude', 'domain_of': ['Sample'], 'slot_uri': 'schema:latitude'} })
longitude: Optional[float] = Field(None, description="""Longitude is a geographic position that refers to the angle east or west of a reference meridian between the two geographical poles to another meridian that passes through an arbitrary point.""", json_schema_extra = { "linkml_meta": {'alias': 'longitude', 'domain_of': ['Sample'], 'slot_uri': 'schema:longitude'} })
species: Optional[List[SpeciesEnum]] = Field(None, description="""The species of micro organisms collected in the sample.""", json_schema_extra = { "linkml_meta": {'alias': 'species', 'domain_of': ['Sample']} })
sample_biome: Optional[BiomeTypeEnum] = Field(None, description="""The biome type of the biosample""", json_schema_extra = { "linkml_meta": {'alias': 'sample_biome', 'domain_of': ['Sample']} })
sample_type: Literal["SoilSample"] = Field("SoilSample", description="""The type of sample.""", json_schema_extra = { "linkml_meta": {'alias': 'sample_type', 'designates_type': True, 'domain_of': ['Sample']} })
@field_validator('id')
def pattern_id(cls, v):
pattern=re.compile(r"^soilsample:\d*")
if isinstance(v,list):
for element in v:
if not pattern.match(element):
raise ValueError(f"Invalid id format: {element}")
elif isinstance(v,str):
if not pattern.match(v):
raise ValueError(f"Invalid id format: {v}")
return v
# Model rebuild
# see https://pydantic-docs.helpmanual.io/usage/models/#rebuilding-a-model
SampleCollection.model_rebuild()
Sample.model_rebuild()
AirSample.model_rebuild()
SoilSample.model_rebuild()