input4mips_validation.cvs.drs#
input4mips_validation.cvs.drs
#
Data reference syntax data model
This module needs a re-write. The rules are not clear enough and the code misrepresents the logic.
For the re-write:
- change to just having a
parse_filepathandparse_filenamefunction for each DRS- introduce a prototype to allow different DRS handlers to be injected as needed
- then you just do wrappers around this DRS handling
- get metadata from filename
- get metadata from path
- create filename
- create path
- validate file correctly written according to DRS
- etc.
- remove the ability to inject the DRS via a string
- fundamentally, it doesn't make sense and is too hard to get the logic right
- it also hides the fact that there is lots of logic that can't be handled in a single string
- as a result of the above, remove the DRS from the CVs entirely
- maybe use a string as a key
- maybe put the DRS in a separate package to allow better re-use
- maybe, because there are some couplings here that might mean you can't do a clean split from the CVs/other logic that easily
DATA_REFERENCE_SYNTAX_FILENAME: str = 'input4MIPs_DRS.json'
module-attribute
#
Default name of the file in which the data reference syntax is saved
DEFAULT_REPLACEMENTS: dict[str, str] = {'.': '-'}
module-attribute
#
Default replacements for characters in directories and file names
DataReferenceSyntaxUnstructured: TypeAlias = dict[str, str]
module-attribute
#
Form into which the DRS is serialised for the CVs
DRSSubstitution
#
A substitution to apply to a DRS template
Source code in src/input4mips_validation/cvs/drs.py
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 | |
optional: bool
instance-attribute
#
Whether this substitution is optional or not.
If the substitution is optional, then,
if metadata is not present when calling self.apply_substitution,
self.string_to_replace is simply deleted from the DRS template.
If the substitution is not optional, then,
if metadata is not present when calling self.apply_substitution,
a KeyError is raised.
replacement_string: str
instance-attribute
#
String to use to replace self.string_to_replace in the DRS template
This contains placeholders.
The actual replacement is generated by calling replacement_string.format
as part of self.format_replacement_string.
required_metadata: tuple[str, ...]
instance-attribute
#
The metadata required to correctly apply the substitution
string_to_replace: str
instance-attribute
#
String in the DRS template to replace
apply_substitution(start, metadata, to_directory_path, validate_substituted_metadata=True)
#
Apply the substitution
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start
|
str
|
String to which to apply the substitution |
required |
metadata
|
dict[str, str]
|
Metadata from which the substitution values can be retrieved |
required |
to_directory_path
|
bool
|
Are the substitutions being applied to create a directory path? If |
required |
validate_substituted_metadata
|
bool
|
If |
True
|
Returns:
| Type | Description |
|---|---|
str
|
|
Source code in src/input4mips_validation/cvs/drs.py
DataReferenceSyntax
#
Data reference syntax definition
This defines how directories and filepaths should be created.
Within the templates, we apply the following rules for parsing the templates.
Carets ("<" and ">") are placeholders for values
that should be replaced with metadata values.
E.g. assuming that the data's model_id is "BD29",
"CMIP/
Square brackets ("[" and "]") indicate that the part of the template is optional.
If the optional metadata isn't there, this part of the DRS will not be included.
E.g. assuming that the data's frequency is "mon" and the model ID is "AB34",
"
Paths are handled using pathlib.Path, hence unix-like paths can be used in the template and they will still work on Windows machines.
Source code in src/input4mips_validation/cvs/drs.py
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 | |
directory_path_example: str
instance-attribute
#
Example of a complete directory path
directory_path_template: str
instance-attribute
#
Template for creating directories
filename_example: str
instance-attribute
#
Example of a complete filename
filename_template: str
instance-attribute
#
Template for creating filenames
extract_metadata_from_filename(filename)
#
Extract metadata from a filename
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
Filename from which to extract the metadata |
required |
Returns:
| Type | Description |
|---|---|
dict[str, str | None]
|
Extracted metadata |
Source code in src/input4mips_validation/cvs/drs.py
extract_metadata_from_path(directory, include_root_data_dir=False)
#
Extract metadata from a path
To be specific, the bit of the path
that corresponds to self.directory_path_template.
In other words,
path should only be the directory/folder bit of the full filepath,
the filename should not be part of path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory
|
Path
|
Directory from which to extract the metadata |
required |
include_root_data_dir
|
bool
|
Should the key "root_data_dir" be included in the output? The value of this key specifies the (inferred) root directory of the data. |
False
|
Returns:
| Type | Description |
|---|---|
dict[str, str | None]
|
Extracted metadata |
Source code in src/input4mips_validation/cvs/drs.py
get_esgf_dataset_master_id(file)
#
Get the ESGF's master ID for the dataset to which a file belongs
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
Path
|
File for which to get the dataset ID |
required |
Returns:
| Type | Description |
|---|---|
str
|
ESGF master ID for the dataset to which |
Examples:
>>> drs = DataReferenceSyntax(
... directory_path_template="<model_id>/v<version>",
... directory_path_example="ACCESS/v20240726",
... filename_template="<variable_id>_<model_id>.nc",
... filename_example="tas_ACCESS.nc",
... )
>>> file = Path("/path/to/somewhere/CanESM/v20240812/tas_CanESM.nc")
>>> drs.get_esgf_dataset_master_id(file)
'CanESM.v20240812'
Source code in src/input4mips_validation/cvs/drs.py
get_file_path(root_data_dir, available_attributes, time_start=None, time_end=None, frequency_metadata_key='frequency', version=None)
#
Get the (full) path to a file based on the DRS
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
root_data_dir
|
Path
|
Root directory in which the data is to be written. The generated path will be relative to |
required |
available_attributes
|
dict[str, str]
|
The available metadata attributes for creating the path. All the elements expected by the DRS must be provided.
For example, if the DRS' filename template is
" |
required |
time_start
|
datetime | datetime | datetime64 | None
|
The earliest time point in the data's time axis. This is a special case. Some DRS definitions expect time range information, but this metadata is not contained in any of the file's metadata, hence the end time must be supplied so that the time range information can be included. |
None
|
time_end
|
datetime | datetime | datetime64 | None
|
The latest time point in the data's time axis. This is a special case. Some DRS definitions expect time range information, but this metadata is not contained in any of the file's metadata, hence the end time must be supplied so that the time range information can be included. |
None
|
frequency_metadata_key
|
str
|
The key in the data's metadata which points to information about the data's frequency. |
'frequency'
|
version
|
str | None
|
The version to use when creating the path. This is a special case. Some DRS definitions expect version metadata, but this metadata is not contained in any of the file's metadata, hence must be supplied separately. If not supplied and version is required, we simply use today's date, formatted as YYYYMMDD. |
None
|
Returns:
| Type | Description |
|---|---|
The path in which to write the file according to the DRS
|
|
Raises:
| Type | Description |
|---|---|
KeyError
|
A metadata attribute expected by the DRS is not supplied. |
ValueError
|
Time range information is required by the DRS,
but |
Source code in src/input4mips_validation/cvs/drs.py
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 | |
get_regexp_for_capturing_directory_information(root_data_dir_group='root_data_dir')
cached
#
Get a regular expression for capturing information from a directory
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
root_data_dir_group
|
str
|
Group name for the group which captures the root data directory. |
'root_data_dir'
|
Returns:
| Type | Description |
|---|---|
str
|
Regular expression which can be used to capture information from a directory. |
Notes
According to
the DRS description,
there are no restrictions on the directory characters
(there are only restrictions on the characters in the filename,
see
get_regexp_for_capturing_filename_information).
Source code in src/input4mips_validation/cvs/drs.py
get_regexp_for_capturing_filename_information()
cached
#
Get a regular expression for capturing information from a filename
Returns:
| Type | Description |
|---|---|
str
|
Regular expression which can be used to capture information from a directory. |
Notes
According to the DRS description:
- only [a-zA-Z0-9-] are allowed in file path names except where underscore is used as a separator.
We use this to significantly simplify our regular expression.
Source code in src/input4mips_validation/cvs/drs.py
parse_drs_template(drs_template)
cached
staticmethod
#
Parse a DRS template string
For the rules about parsing, see
DataReferenceSyntax.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
drs_template
|
str
|
DRS template to parse |
required |
Returns:
| Type | Description |
|---|---|
Substitutions defined by `drs_template`
|
|
Source code in src/input4mips_validation/cvs/drs.py
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 | |
validate_file_written_according_to_drs(file, frequency_metadata_keys=FrequencyMetadataKeys(), time_dimension='time', xr_variable_processor=XRVariableHelper())
#
Validate that a file is correctly written in the DRS
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
Path
|
File to validate |
required |
frequency_metadata_keys
|
FrequencyMetadataKeys
|
Metadata definitions for frequency information |
FrequencyMetadataKeys()
|
time_dimension
|
str
|
The time dimension of the data |
'time'
|
xr_variable_processor
|
XRVariableProcessorLike
|
Helper to use for processing the variables in xarray objects. |
XRVariableHelper()
|
Raises:
| Type | Description |
|---|---|
ValueError
|
The file is not correctly written in the DRS |
Source code in src/input4mips_validation/cvs/drs.py
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 | |
apply_known_replacements(inp, known_replacements=None)
#
Apply known replacements of characters in metadata values
This helps ensure that only valid characters appear in our populated DRS templates.
For further details about the characters which are valid,
see assert_all_metadata_substitutions_only_contain_valid_characters
and assert_full_filepath_only_contains_valid_characters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inp
|
str
|
Input metadata value |
required |
known_replacements
|
dict[str, str] | None
|
Known replacements to apply. If |
None
|
Result
:
inp with known replacements applied.
Source code in src/input4mips_validation/cvs/drs.py
apply_substitutions(drs_template, substitutions, metadata, to_directory_path, validate_substituted_metadata=True)
#
Apply a series of substitutions to a DRS template
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
drs_template
|
str
|
DRS template to which the substitutions should be applied |
required |
substitutions
|
Iterable[DRSSubstitution]
|
Substitutions to apply |
required |
metadata
|
dict[str, str]
|
Metadata from which the substitution values can be retrieved |
required |
to_directory_path
|
bool
|
Are the substitutions being applied to create a directory path? If |
required |
validate_substituted_metadata
|
bool
|
Passed to
|
True
|
Returns:
| Type | Description |
|---|---|
str
|
DRS template, with all substitutions in |
Source code in src/input4mips_validation/cvs/drs.py
assert_all_metadata_substitutions_only_contain_valid_characters(metadata, to_directory_path)
#
Assert that all the metadata substitutions only contain valid characters
For metadata being applied to a DRS template, only certain characters are allowed.
According to the DRS description:
All strings appearing in the file name are constructed using only the following characters: a-z, A-Z, 0-9, and the hyphen ("-"), except the hyphen must not appear in variable_id. Underscores are prohibited throughout except as shown in the template.
We prohibit the use of underscores in the filenames, following the DRS description. However, we've clearly ignored the rule about no hyphens in variable IDs in input4MIPs, so we allow hyphens to appear in the variable ID part of the file name. Hyphens will only appear in the variable ID part of the file name when the original variable had underscores, and these underscores have been replaced with hyphens to avoid breaking the DRS.
Nothing is said about the directory names, so all values are allowed for directory names.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metadata
|
dict[str, str]
|
Metadata substitutions to check |
required |
to_directory_path
|
bool
|
Are the substitutions being applied to create a directory path? If |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
One of the metadata substitutions contains invalid characters |
Source code in src/input4mips_validation/cvs/drs.py
assert_full_filepath_only_contains_valid_characters(full_filepath)
#
Assert that a filepath only contains valid characters
According to the DRS description:
- only [a-zA-Z0-9-] are allowed in file path names except where underscore is used as a separator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
full_filepath
|
str | Path
|
Full filepath (directories and filename) to validate |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
|
Source code in src/input4mips_validation/cvs/drs.py
assert_only_valid_chars(inp, valid_chars)
#
Assert that the input only contains valid characters
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inp
|
str | Path
|
Input to validate |
required |
valid_chars
|
set[str]
|
Set of valid characters |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
|
Source code in src/input4mips_validation/cvs/drs.py
convert_drs_to_unstructured_cv(drs)
#
Convert the data reference syntax (DRS) to the raw CV form
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
drs
|
DataReferenceSyntax
|
DRS |
required |
Returns:
| Type | Description |
|---|---|
Raw CV data
|
|
Source code in src/input4mips_validation/cvs/drs.py
convert_unstructured_cv_to_drs(unstructured)
#
Convert the raw CV data to its structured form
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
unstructured
|
DataReferenceSyntaxUnstructured
|
Unstructured CV data |
required |
Returns:
| Type | Description |
|---|---|
Data reference syntax
|
|
Source code in src/input4mips_validation/cvs/drs.py
format_date_for_time_range(date, ds_frequency)
#
Format date for providing time range information
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
date
|
datetime | datetime | datetime64
|
Date to format |
required |
ds_frequency
|
str
|
Frequency of the data in the underlying dataset |
required |
Returns:
| Type | Description |
|---|---|
Formatted date
|
|
Examples:
>>> format_date_for_time_range(dt.datetime(2024, 7, 12), "yr")
'2024'
>>> format_date_for_time_range(dt.datetime(2024, 7, 12), "mon")
'202407'
>>> format_date_for_time_range(dt.datetime(2024, 7, 12), "day")
'20240712'
>>> format_date_for_time_range(dt.datetime(2024, 7, 12, 4, 30, 30), "3hr")
'202407120430'
Source code in src/input4mips_validation/cvs/drs.py
get_regexp_from_template_and_substitutions(drs_template, substitutions, capturing_allowed_chars='[a-zA-Z0-9-]')
#
Get a capturing regular expression from a template and substitutions
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
drs_template
|
str
|
DRS template from which to generate the regexp |
required |
substitutions
|
Iterable[DRSSubstitution]
|
Substitutions that can be applied to the DRS template |
required |
capturing_allowed_chars
|
str
|
Specification for characters that are allowed in the capturing groups. |
'[a-zA-Z0-9-]'
|
Returns:
| Type | Description |
|---|---|
str
|
Generated regexp, which will capture metadata according to the DRS |
Examples:
>>> template_str = "<model_id>[_<optional_id>]_<time_range>.nc"
>>> substitutions = DataReferenceSyntax.parse_drs_template(template_str)
>>> get_regexp_from_template_and_substitutions(
... template_str,
... substitutions,
... capturing_allowed_chars="[a-z]",
... )
'(?P<model_id>[a-z]+)(_(?P<optional_id>[a-z]+))?_(?P<time_range>[a-z]+).nc'
Source code in src/input4mips_validation/cvs/drs.py
key_in_substitutions(key, substitutions)
#
Return whether a key is in the DRS or not
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Metadata key |
required |
substitutions
|
tuple[DRSSubstitution, ...]
|
Substitutions that will be applied to the DRS |
required |
Returns:
| Type | Description |
|---|---|
`True` if the key is in the DRS, otherwise `False`.
|
|
Source code in src/input4mips_validation/cvs/drs.py
key_required_for_substitutions(key, substitutions)
#
Return whether a key is required metadata or not for populating the DRS
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Metadata key |
required |
substitutions
|
tuple[DRSSubstitution, ...]
|
Substitutions that will be applied to the DRS |
required |
Returns:
| Type | Description |
|---|---|
`True` if the key is required metadata to populate the DRS, otherwise `False`.
|
|
Source code in src/input4mips_validation/cvs/drs.py
load_drs(raw_cvs_loader, filename=DATA_REFERENCE_SYNTAX_FILENAME)
#
Load the DRS in the CVs
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raw_cvs_loader
|
RawCVLoader
|
Loader of raw CVs data. |
required |
filename
|
str
|
Name of the file from which to load the CVs. Passed to
|
DATA_REFERENCE_SYNTAX_FILENAME
|
Returns:
| Type | Description |
|---|---|
Loaded DRS
|
|