Required Feature Attributes¶
Overview¶
The RequiredFeatureAttributes class is a subclass of CalculationRequirement that is used to check if a list of attributes is set for a feature of an object. This is useful when a calculation requires a specific set of attributes to be present for a feature, and it is necessary to check if they exist before proceeding with the calculation.
Usage¶
This requirement can be instantiated with a list of attributes that need to be present for each feature of an object. Below there is an example of how to use this requirement:
requirement = RequiredFeatureAttributes(object_name="LAN-LAN-01", feature_name="cms_amplitude_01_filter", attributes=["feature_options_json"])
After calling check and get_data methods, the data attribute of the requirement will be a dictionary with the feature as the key and a dictionary with the attributes as the value. Below there is an example of how this data is stored:
{
"feature_options_json": {"kind": "amplitude", "sensor": 1, "acquisition": "filter"}
}
Database Requirements¶
This requirement expects that the feature_attributes table is set with the necessary attributes for each feature. This can easily be done with the database function set_attribute. Below is a query example to set the attributes for the feature cms_amplitude_01_filter of the model G97-2.07 of the object LAN-LAN-01:
SELECT * FROM performance.fn_set_feature_attribute('cms_amplitude_01_filter', 'G97-2.07', 'feature_options_json', '{"attribute_value": {"kind": "amplitude", "sensor": 1, "acquisition": "filter"}}');
To check if the attributes are set correctly, go to the v_feature_attributes view in the database.
Class Definition¶
RequiredFeatureAttributes(object_name, feature_name, attributes, optional=False)
¶
Subclass of CalculationRequirement that defines the feature attributes that are required for the calculation.
This will check the performance database for the existence of the required feature attributes for the wanted object and feature.
Parameters:
-
(object_name¶str) –Name of the object for which the feature attributes are required.
-
(feature_name¶str) –Name of the feature for which the attributes are required.
-
(attributes¶list[str]) –The attributes that are required for the feature.
-
(optional¶bool, default:False) –Set to True if this is an optional requirement. by default False
Source code in echo_energycalc/calculation_requirement_feature_attributes.py
def __init__(
self,
object_name: str,
feature_name: str,
attributes: list[str],
optional: bool = False,
) -> None:
"""
Constructor of the RequiredFeatureAttributes class.
This will check the performance database for the existence of the required feature attributes for the wanted object and feature.
Parameters
----------
object_name : str
Name of the object for which the feature attributes are required.
feature_name : str
Name of the feature for which the attributes are required.
attributes : list[str]
The attributes that are required for the feature.
optional : bool, optional
Set to True if this is an optional requirement. by default False
"""
super().__init__(optional)
# check if object_name is a str
if not isinstance(object_name, str):
raise TypeError(f"object_name must be a str, not {type(object_name)}")
self._object = object_name
# check if feature_name is a str
if not isinstance(feature_name, str):
raise TypeError(f"feature_name must be a str, not {type(feature_name)}")
self._feature = feature_name
# check if attributes is a list of str
if not isinstance(attributes, list):
raise TypeError(f"attributes must be a list, not {type(attributes)}")
if not all(isinstance(item, str) for item in attributes):
raise TypeError(f"all attributes items must be str, not {[type(item) for item in attributes]}")
self._attributes = attributes
attributes
property
¶
Attributes that are required for the feature.
Returns:
-
list[str]–The attributes that are required for the feature.
checked
property
¶
Attribute that defines if the requirement has been checked. It's value will start as False and will be set to True after the check method is called.
Returns:
-
bool–True if the requirement has been checked.
data
property
¶
Data required for the calculation.
Returns:
-
dict[str, Any]–Dict with the required feature attributes for the desired feature. The keys are the attribute names and the values are the attribute values.
feature
property
¶
Name of the feature for which the attributes are required.
Returns:
-
str–Name of the feature for which the attributes are required.
fetched
property
¶
Attribute that defines if get_data() has been called on this requirement.
True even when the fetch returned no data (e.g. an optional requirement
that found nothing). Use this to distinguish "never fetched" from "fetched
but empty/None".
Returns:
-
bool–True if get_data() has been called at least once.
object
property
¶
Name of the object for which the feature attributes are required.
Returns:
-
str–Name of the object for which the feature attributes are required.
optional
property
¶
Attribute that defines if the requirement is optional.
If optional is True, the requirement is only validated to check if it could exist, not if it is actually present. This is useful for requirements that are not necessary for all calculations, but are useful for some of them.
Returns:
-
bool–True if the requirement is optional.
check()
¶
Check that the requirement is met.
This concrete implementation handles two concerns automatically so that
subclasses only need to implement _do_check():
- Already-checked guard — returns
Trueimmediately ifcheck()has already succeeded for this instance, avoiding redundant DB round-trips when_fetch_requirements()iterates requirements on every_compute()call. - Per-thread caching — when
_check_cache_key()returns a non-None key, the result produced by_do_check()is stored in a thread-local cache and reused by subsequent instances in the same thread with the same key. Because the cache is never shared across threads, no locking is needed and concurrent Polars operations inside_do_checkcannot deadlock.
The optional guard is intentionally delegated to _do_check() because
different subclasses have different optional semantics (see _do_check docs).
Returns:
-
bool–True if the requirement is met; raises on unmet non-optional requirements.
Source code in echo_energycalc/calculation_requirements_core.py
def check(self) -> bool:
"""
Check that the requirement is met.
This concrete implementation handles two concerns automatically so that
subclasses only need to implement ``_do_check()``:
1. **Already-checked guard** — returns ``True`` immediately if ``check()`` has
already succeeded for this instance, avoiding redundant DB round-trips when
``_fetch_requirements()`` iterates requirements on every ``_compute()`` call.
2. **Per-thread caching** — when ``_check_cache_key()`` returns a non-None key,
the result produced by ``_do_check()`` is stored in a thread-local cache and
reused by subsequent instances in the same thread with the same key. Because
the cache is never shared across threads, no locking is needed and concurrent
Polars operations inside ``_do_check`` cannot deadlock.
The **optional guard** is intentionally delegated to ``_do_check()`` because
different subclasses have different optional semantics (see ``_do_check`` docs).
Returns
-------
bool
True if the requirement is met; raises on unmet non-optional requirements.
"""
if self._checked:
return True
cache_key = self._check_cache_key()
if cache_key is not None:
_tl = type(self)._cache_local # noqa: SLF001
if not hasattr(_tl, "cache"):
_tl.cache = {}
cached = _tl.cache.get(cache_key)
if cached is None:
self._do_check()
_tl.cache[cache_key] = self._get_cache_value()
cached = _tl.cache[cache_key]
else:
logger.debug("Cache hit for %s (key=%s)", type(self).__name__, cache_key)
self._set_from_cache(cached)
else:
self._do_check()
self._checked = True
return True
get_data(**kwargs)
¶
Method used to get the required feature attributes from performance database.
This will not do anything other than call the check() method because the check() method already gets the data.
Returns:
-
dict[str, Any]–Dict in the format {attribute_name: attribute_value, ...}.
Source code in echo_energycalc/calculation_requirement_feature_attributes.py
def get_data(self, **kwargs) -> dict[str, Any]: # noqa: ARG002
"""
Method used to get the required feature attributes from performance database.
This will not do anything other than call the check() method because the check() method already gets the data.
Returns
-------
dict[str, Any]
Dict in the format {attribute_name: attribute_value, ...}.
"""
if not self._checked:
self.check()
self._fetched = True
return self.data