Skip to content

conventions

Naming conventions for the EFTS netCDF file format.

TYPES_CONVERTIBLE_TO_TIMESTAMP module-attribute

TYPES_CONVERTIBLE_TO_TIMESTAMP = [
    str,
    datetime,
    datetime64,
    Timestamp,
]

Definition of a 'type' for type hints.

AttributesErrorLevel

Bases: Enum

Controls the behavior of variable attribute checking functions.

check_hydrologic_variables

check_hydrologic_variables(
    file_path: str,
) -> Dict[str, List[str]]

Checks if the variable names and attributes in a netCDF file comply with the STF convention.

Parameters:

  • file_path (str) –

    The path to the netCDF file.

Returns:

  • Dict[str, List[str]]

    Dict[str, List[str]]: A dictionary with keys "INFO", "WARNING", "ERROR" and values as lists of strings describing compliance issues.

Source code in src/efts_io/conventions.py
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
def check_hydrologic_variables(file_path: str) -> Dict[str, List[str]]:
    """Checks if the variable names and attributes in a netCDF file comply with the STF convention.

    Args:
        file_path (str): The path to the netCDF file.

    Returns:
        Dict[str, List[str]]: A dictionary with keys "INFO", "WARNING", "ERROR" and values as lists of strings describing compliance issues.
    """
    try:
        dataset = None
        dataset = nc.Dataset(file_path, mode="r")
        results = {"INFO": [], "WARNING": [], "ERROR": []}

        for var in dataset.variables:
            if _is_structural_varname(var):
                continue
            if _is_known_hydro_varname(var):
                results["INFO"].append(f"Hydrologic variable '{var}' follows the recommended naming convention.")

                # Check attributes
                for msg in _check_variable_attributes(dataset.variables[var]):
                    results["WARNING"].append(msg)
            else:
                results["WARNING"].append(
                    f"Hydrologic variable '{var}' does not follow the recommended naming convention.",
                )

        return results  # noqa: TRY300

    except Exception as e:  # noqa: BLE001
        return {"ERROR": [f"Error opening or reading file '{file_path}': {e!s}"]}

    finally:
        if dataset:
            dataset.close()

check_index_found

check_index_found(
    index_id: Optional[int],
    identifier: str,
    dimension_id: str,
) -> None

Helper function to check that a value (index) was is indeed found in the dimension.

Source code in src/efts_io/conventions.py
178
179
180
181
182
183
184
185
186
187
188
def check_index_found(
    index_id: Optional[int],
    identifier: str,
    dimension_id: str,
) -> None:
    """Helper function to check that a value (index) was is indeed found in the dimension."""
    # return isinstance(index_id, np.int64)
    if index_id is None:
        raise ValueError(
            f"identifier '{identifier}' not found in the dimension '{dimension_id}'",
        )

check_optional_variable_attributes

check_optional_variable_attributes(
    variable: Any,
    error_threshold: AttributesErrorLevel = AttributesErrorLevel.NONE,
) -> List[str]

Checks if the attributes of the observed variable comply with the conventions.

Source code in src/efts_io/conventions.py
601
602
603
604
605
606
607
608
609
610
611
612
def check_optional_variable_attributes(
    variable: Any,
    error_threshold: AttributesErrorLevel = AttributesErrorLevel.NONE,
) -> List[str]:
    """Checks if the attributes of the observed variable comply with the conventions."""
    missing_attributes_messages = []
    required_attributes = {
        STANDARD_NAME_ATTR_KEY: str,
        LONG_NAME_ATTR_KEY: str,
        UNITS_ATTR_KEY: str,
    }
    return _check_attrs(variable, required_attributes, missing_attributes_messages, error_threshold=error_threshold)

check_stf_compliance

check_stf_compliance(
    file_path: str,
) -> Dict[str, List[str]]

Checks the compliance of a netCDF file with the STF convention.

Parameters:

  • file_path (str) –

    The path to the netCDF file.

Returns:

  • Dict[str, List[str]]

    Dict[str, List[str]]: A dictionary with keys "INFO", "WARNING", "ERROR" and values as lists of strings describing compliance issues.

Source code in src/efts_io/conventions.py
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
def check_stf_compliance(file_path: str) -> Dict[str, List[str]]:
    """Checks the compliance of a netCDF file with the STF convention.

    Args:
        file_path (str): The path to the netCDF file.

    Returns:
        Dict[str, List[str]]: A dictionary with keys "INFO", "WARNING", "ERROR" and values as lists of strings describing compliance issues.
    """
    try:
        dataset = nc.Dataset(file_path, mode="r")
        results = {"INFO": [], "WARNING": [], "ERROR": []}

        # Check for required dimensions
        required_dims = [TIME_DIMNAME, STATION_DIMNAME, LEAD_TIME_DIMNAME, ENS_MEMBER_DIMNAME, STR_LEN_DIMNAME]
        available_dims = dataset.dimensions.keys()

        for dim in required_dims:
            if dim in available_dims:
                results["INFO"].append(f"Dimension '{dim}' is present.")
            else:
                results["ERROR"].append(f"Missing required dimension '{dim}'.")

        # Check global attributes
        required_global_attributes = [
            TITLE_ATTR_KEY,
            INSTITUTION_ATTR_KEY,
            SOURCE_ATTR_KEY,
            CATCHMENT_ATTR_KEY,
            STF_CONVENTION_VERSION_ATTR_KEY,
            STF_NC_SPEC_ATTR_KEY,
            COMMENT_ATTR_KEY,
            HISTORY_ATTR_KEY,
        ]
        available_global_attributes = dataset.ncattrs()

        for attr in required_global_attributes:
            if attr in available_global_attributes:
                results["INFO"].append(f"Global attribute '{attr}' is present.")
            else:
                results["WARNING"].append(f"Missing global attribute '{attr}'.")

        # Check mandatory variables and their attributes
        mandatory_variables = [
            TIME_DIMNAME,
            STATION_ID_VARNAME,
            STATION_NAME_VARNAME,
            ENS_MEMBER_DIMNAME,
            LEAD_TIME_DIMNAME,
            LAT_VARNAME,
            LON_VARNAME,
        ]
        variable_attributes = {
            TIME_DIMNAME: [
                STANDARD_NAME_ATTR_KEY,
                LONG_NAME_ATTR_KEY,
                UNITS_ATTR_KEY,
                TIME_STANDARD_ATTR_KEY,
                AXIS_ATTR_KEY,
            ],
            STATION_ID_VARNAME: [LONG_NAME_ATTR_KEY],
            STATION_NAME_VARNAME: [LONG_NAME_ATTR_KEY],
            ENS_MEMBER_DIMNAME: [STANDARD_NAME_ATTR_KEY, LONG_NAME_ATTR_KEY, UNITS_ATTR_KEY, AXIS_ATTR_KEY],
            LEAD_TIME_DIMNAME: [STANDARD_NAME_ATTR_KEY, LONG_NAME_ATTR_KEY, UNITS_ATTR_KEY, AXIS_ATTR_KEY],
            LAT_VARNAME: [LONG_NAME_ATTR_KEY, UNITS_ATTR_KEY, AXIS_ATTR_KEY],
            LON_VARNAME: [LONG_NAME_ATTR_KEY, UNITS_ATTR_KEY, AXIS_ATTR_KEY],
        }

        for var in mandatory_variables:
            if var in dataset.variables:
                results["INFO"].append(f"Mandatory variable '{var}' is present.")
                # Check attributes
                for attr, required_attrs in variable_attributes.items():
                    if var == attr:
                        for req_attr in required_attrs:
                            if req_attr in dataset.variables[var].ncattrs():
                                results["INFO"].append(f"Attribute '{req_attr}' for variable '{var}' is present.")
                            else:
                                results["WARNING"].append(
                                    f"Missing required attribute '{req_attr}' for variable '{var}'.",
                                )
            else:
                results["ERROR"].append(f"Missing mandatory variable '{var}'.")

        dataset.close()
        return results  # noqa: TRY300

    except Exception as e:  # noqa: BLE001
        return {"ERROR": [f"Error opening file '{file_path}': {e!s}"]}

convert_to_datetime64_utc

convert_to_datetime64_utc(
    x: ConvertibleToTimestamp,
) -> datetime64

Converts a known timestamp representation an np.datetime64.

Source code in src/efts_io/conventions.py
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
def convert_to_datetime64_utc(x: ConvertibleToTimestamp) -> np.datetime64:
    """Converts a known timestamp representation an np.datetime64."""
    if isinstance(x, pd.Timestamp):
        if x.tz is None:
            x = x.tz_localize("UTC")
        x = x.tz_convert("UTC")
    elif isinstance(x, datetime):
        x = pd.Timestamp(x, tz="UTC") if x.tzinfo is None else pd.Timestamp(x).tz_convert("UTC")
    elif isinstance(x, str):
        x_dt = pd.to_datetime(x)
        x = pd.Timestamp(x_dt, tz="UTC") if x_dt.tzinfo is None else pd.Timestamp(x_dt).tz_convert("UTC")
    elif isinstance(x, np.datetime64):
        x = pd.Timestamp(x).tz_localize("UTC")
    else:
        raise TypeError(f"Cannot convert {type(x)} to np.datetime64 with UTC timezone.")

    return x.to_datetime64()

exportable_to_stf2

exportable_to_stf2(data: MdDatasetsType) -> bool

Check if the dataset can be written to a netCDF file compliant with STF 2.0 specification.

This method checks if the underlying xarray dataset or dataarray has the required dimensions and global attributes as specified by the STF 2.0 convention.

Returns:

  • bool ( bool ) –

    True if the dataset can be written to a STF 2.0 compliant netCDF file, False otherwise.

Source code in src/efts_io/conventions.py
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
def exportable_to_stf2(data: MdDatasetsType) -> bool:
    """Check if the dataset can be written to a netCDF file compliant with STF 2.0 specification.

    This method checks if the underlying xarray dataset or dataarray has the required dimensions and global attributes as specified by the STF 2.0 convention.

    Returns:
        bool: True if the dataset can be written to a STF 2.0 compliant netCDF file, False otherwise.
    """
    from efts_io.conventions import has_required_stf2_dimensions, has_required_variables_xr, mandatory_xarray_dimensions  # noqa: I001

    required_stf2_dimensions = has_required_stf2_dimensions(data, mandatory_xarray_dimensions)
    required_attributes = has_required_xarray_global_attributes(data)
    required_variables = has_required_variables_xr(data)
    # Check that station_ids are not strings though:
    if STATION_ID_DIMNAME in data:  # must be, but no harm in checking
        station_ids = data[STATION_ID_DIMNAME].values
        if not np.issubdtype(station_ids.dtype, np.integer):
            return False

    return required_stf2_dimensions and required_attributes and required_variables

get_default_dim_order

get_default_dim_order() -> List[str]

Default order of dimensions in the netCDF file.

Returns:

  • List[str]

    List[str]: dimension names: [lead_time, stations, ensemble_member, time]

Source code in src/efts_io/conventions.py
164
165
166
167
168
169
170
171
172
173
174
175
def get_default_dim_order() -> List[str]:
    """Default order of dimensions in the netCDF file.

    Returns:
        List[str]: dimension names: [lead_time, stations, ensemble_member, time]
    """
    return [
        LEAD_TIME_DIMNAME,
        STATION_DIMNAME,
        ENS_MEMBER_DIMNAME,
        TIME_DIMNAME,
    ]

has_required_global_attributes

has_required_global_attributes(d: MdDatasetsType) -> bool

has_required_global_attributes.

Source code in src/efts_io/conventions.py
275
276
277
278
279
280
281
282
283
def has_required_global_attributes(d: MdDatasetsType) -> bool:
    """has_required_global_attributes."""
    if _is_nc_dataset(d):
        a = d.ncattrs()
        tested = set(a)
    else:
        a = d.attrs.keys()
        tested = set(a)
    return _has_all_members(tested, mandatory_global_attributes)

has_required_stf2_dimensions

has_required_stf2_dimensions(
    d: MdDatasetsType,
    mandatory_dimensions: Optional[Iterable[str]] = None,
) -> bool

Has the dataset the required dimensions for STF conventions.

Parameters:

  • d (MdDatasetsType) –

    data object to check

Returns:

  • bool ( bool ) –

    Has it the minimum STF dimentions

Source code in src/efts_io/conventions.py
246
247
248
249
250
251
252
253
254
255
256
def has_required_stf2_dimensions(d: MdDatasetsType, mandatory_dimensions: Optional[Iterable[str]] = None) -> bool:
    """Has the dataset the required dimensions for STF conventions.

    Args:
        d (MdDatasetsType): data object to check

    Returns:
        bool: Has it the minimum STF dimentions
    """
    mandatory_dimensions = mandatory_dimensions or mandatory_netcdf_dimensions
    return _has_required_dimensions(d, mandatory_dimensions)

has_required_variables_xr

has_required_variables_xr(d: MdDatasetsType) -> bool

has_required_variables.

Source code in src/efts_io/conventions.py
293
294
295
296
297
298
299
300
def has_required_variables_xr(d: MdDatasetsType) -> bool:
    """has_required_variables."""
    a = d.variables.keys()
    tested = set(a)
    # Note: even if xarray, we do not need to check for the 'data_vars' attribute here.
    # a = d.data_vars.keys()
    # tested = set(a)
    return _has_all_members(tested, mandatory_varnames_xr)

has_required_xarray_dimensions

has_required_xarray_dimensions(d: MdDatasetsType) -> bool

Has the dataset the required dimensions for an in memory xarray representation.

Source code in src/efts_io/conventions.py
259
260
261
def has_required_xarray_dimensions(d: MdDatasetsType) -> bool:
    """Has the dataset the required dimensions for an in memory xarray representation."""
    return _has_required_dimensions(d, mandatory_xarray_dimensions)

has_required_xarray_global_attributes

has_required_xarray_global_attributes(
    d: MdDatasetsType,
) -> bool

has_required_xarray_global_attributes.

Source code in src/efts_io/conventions.py
286
287
288
289
290
def has_required_xarray_global_attributes(d: MdDatasetsType) -> bool:
    """has_required_xarray_global_attributes."""
    a = d.attrs.keys()
    tested = set(a)
    return _has_all_members(tested, mandatory_global_attributes_xr)

has_variable

has_variable(d: MdDatasetsType, varname: str) -> bool

has_variable.

Source code in src/efts_io/conventions.py
303
304
305
306
307
def has_variable(d: MdDatasetsType, varname: str) -> bool:
    """has_variable."""
    a = d.variables.keys()
    tested = set(a)
    return varname in tested

is_subset_required_xarray_dimensions

is_subset_required_xarray_dimensions(
    d: MdDatasetsType,
) -> bool

Has the data array or dataset dimensions that are a subset of the spedified dims?

Source code in src/efts_io/conventions.py
264
265
266
def is_subset_required_xarray_dimensions(d: MdDatasetsType) -> bool:
    """Has the data array or dataset dimensions that are a subset of the spedified dims?"""
    return _is_subset_required_dimensions(d, mandatory_xarray_dimensions)