flexmeasures.data.models.generic_assets

Functions

flexmeasures.data.models.generic_assets.assets_share_location(assets: list[GenericAsset]) bool

Return True if all assets in this list are located on the same spot. TODO: In the future, we might soften this to compare if assets are in the same “housing” or “site”.

flexmeasures.data.models.generic_assets.create_generic_asset(generic_asset_type: str, **kwargs) GenericAsset

Create a GenericAsset and assigns it an id.

Parameters:
  • generic_asset_type – “asset”, “market” or “weather_sensor”

  • kwargs – should have values for keys “name”, and: - “asset_type_name” or “asset_type” when generic_asset_type is “asset” - “market_type_name” or “market_type” when generic_asset_type is “market” - “weather_sensor_type_name” or “weather_sensor_type” when generic_asset_type is “weather_sensor” - alternatively, “sensor_type” is also fine

Returns:

the created GenericAsset

flexmeasures.data.models.generic_assets.get_center_location_of_assets(user: User | None) tuple[float, float]

Find the center position between all generic assets of the user’s account.

Classes

class flexmeasures.data.models.generic_assets.GenericAsset(**kwargs)

An asset is something that has economic value.

Examples of tangible assets: a house, a ship, a weather station. Examples of intangible assets: a market, a country, a copyright.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

add_annotations(df: DataFrame, annotation_type: str, commit_transaction: bool = False)

Add a data frame describing annotations to the database, and assign the annotations to this asset.

property asset_type: GenericAssetType

This property prepares for dropping the “generic” prefix later

chart(chart_type: str = 'chart_for_multiple_sensors', event_starts_after: datetime | None = None, event_ends_before: datetime | None = None, beliefs_after: datetime | None = None, beliefs_before: datetime | None = None, combine_legend: bool = True, source: DataSource | list[DataSource] | int | list[int] | str | list[str] | None = None, include_data: bool = False, dataset_name: str | None = None, resolution: str | timedelta | None = None, **kwargs) dict

Create a vega-lite chart showing sensor data.

Parameters:
  • chart_type – currently only “bar_chart” # todo: where can we properly list the available chart types?

  • event_starts_after – only return beliefs about events that start after this datetime (inclusive)

  • event_ends_before – only return beliefs about events that end before this datetime (inclusive)

  • beliefs_after – only return beliefs formed after this datetime (inclusive)

  • beliefs_before – only return beliefs formed before this datetime (inclusive)

  • combine_legend – show a combined legend of all plots below the chart

  • source – search only beliefs by this source (pass the DataSource, or its name or id) or list of sources

  • include_data – if True, include data in the chart, or if False, exclude data

  • dataset_name – optionally name the dataset used in the chart (the default name is sensor_<id>)

  • resolution – optionally set the resolution of data being displayed

Returns:

JSON string defining vega-lite chart specs

count_annotations(annotation_starts_after: datetime | None = None, annotations_after: datetime | None = None, annotation_ends_before: datetime | None = None, annotations_before: datetime | None = None, source: DataSource | list[DataSource] | int | list[int] | str | list[str] | None = None, annotation_type: str = None) int

Count the number of annotations assigned to this asset.

get_consumption_price_sensor()

Searches for consumption_price_sensor upwards on the asset tree

get_flex_context() dict

Reconstitutes the asset’s serialized flex-context by gathering flex-contexts upwards in the asset tree.

Flex-context fields of ancestors that are nearer have priority. We return once we collect all flex-context fields or reach the top asset.

get_inflexible_device_sensors()

Searches for inflexible_device_sensors upwards on the asset tree This search will stop once any sensors are found (will not aggregate towards the top of the tree)

get_production_price_sensor()

Searches for production_price_sensor upwards on the asset tree

classmethod get_timerange(sensors: list[Sensor]) dict[str, datetime]

Time range for which sensor data exists.

Parameters:

sensors – sensors to check

Returns:

dictionary with start and end, for example: {

’start’: datetime.datetime(2020, 12, 3, 14, 0, tzinfo=pytz.utc), ‘end’: datetime.datetime(2020, 12, 3, 14, 30, tzinfo=pytz.utc)

}

great_circle_distance(**kwargs)

Query great circle distance (unclear if in km or in miles).

Can be called with an object that has latitude and longitude properties, for example:

great_circle_distance(object=asset)

Can also be called with latitude and longitude parameters, for example:

great_circle_distance(latitude=32, longitude=54) great_circle_distance(lat=32, lng=54)

Requires the following Postgres extensions: earthdistance and cube.

property has_energy_sensors: bool

True if at least one energy sensor is attached

property has_power_sensors: bool

True if at least one power sensor is attached

property offspring: list[GenericAsset]

Returns a flattened list of all offspring, which is looked up recursively.

search_annotations(annotations_after: datetime | None = None, annotations_before: datetime | None = None, source: DataSource | list[DataSource] | int | list[int] | str | list[str] | None = None, annotation_type: str = None, include_account_annotations: bool = False, as_frame: bool = False) list[Annotation] | pd.DataFrame

Return annotations assigned to this asset, and optionally, also those assigned to the asset’s account.

The returned annotations do not include any annotations on public accounts.

Parameters:
  • annotations_after – only return annotations that end after this datetime (exclusive)

  • annotations_before – only return annotations that start before this datetime (exclusive)

search_beliefs(sensors: list['Sensor'] | None = None, event_starts_after: datetime | None = None, event_ends_before: datetime | None = None, beliefs_after: datetime | None = None, beliefs_before: datetime | None = None, horizons_at_least: timedelta | None = None, horizons_at_most: timedelta | None = None, source: DataSource | list[DataSource] | int | list[int] | str | list[str] | None = None, most_recent_beliefs_only: bool = True, most_recent_events_only: bool = False, as_json: bool = False, resolution: timedelta | None = None) BeliefsDataFrame | str

Search all beliefs about events for all sensors of this asset

If you don’t set any filters, you get the most recent beliefs about all events.

Parameters:
  • sensors – only return beliefs about events registered by these sensors

  • event_starts_after – only return beliefs about events that start after this datetime (inclusive)

  • event_ends_before – only return beliefs about events that end before this datetime (inclusive)

  • beliefs_after – only return beliefs formed after this datetime (inclusive)

  • beliefs_before – only return beliefs formed before this datetime (inclusive)

  • horizons_at_least – only return beliefs with a belief horizon equal or greater than this timedelta (for example, use timedelta(0) to get ante knowledge time beliefs)

  • horizons_at_most – only return beliefs with a belief horizon equal or less than this timedelta (for example, use timedelta(0) to get post knowledge time beliefs)

  • source – search only beliefs by this source (pass the DataSource, or its name or id) or list of sources

  • most_recent_events_only – only return (post knowledge time) beliefs for the most recent event (maximum event start)

  • as_json – return beliefs in JSON format (e.g. for use in charts) rather than as BeliefsDataFrame

  • resolution – optionally set the resolution of data being displayed

Returns:

dictionary of BeliefsDataFrames or JSON string (if as_json is True)

set_inflexible_sensors(inflexible_sensor_ids: list[int]) None

Set inflexible sensors for this asset.

Parameters:

inflexible_sensor_ids – list of sensor ids

property timerange: dict[str, datetime]

Time range for which sensor data exists.

Returns:

dictionary with start and end, for example: {

’start’: datetime.datetime(2020, 12, 3, 14, 0, tzinfo=pytz.utc), ‘end’: datetime.datetime(2020, 12, 3, 14, 30, tzinfo=pytz.utc)

}

property timerange_of_sensors_to_show: dict[str, datetime]

Time range for which sensor data exists, for sensors to show.

Returns:

dictionary with start and end, for example: {

’start’: datetime.datetime(2020, 12, 3, 14, 0, tzinfo=pytz.utc), ‘end’: datetime.datetime(2020, 12, 3, 14, 30, tzinfo=pytz.utc)

}

property timezone: str

Timezone relevant to the asset.

If a timezone is not given as an attribute of the asset, it is taken from one of its sensors.

validate_sensors_to_show(suggest_default_sensors: bool = True) list[dict[str, str | None | 'Sensor' | list['Sensor']]]

Validate and transform the ‘sensors_to_show’ attribute into the latest format for use in graph-making code.

This function ensures that the ‘sensors_to_show’ attribute: 1. Follows the latest format, even if the data in the database uses an older format. 2. Contains only sensors that the user has access to (based on the current asset, account, or public availability).

Steps: - The function deserializes the ‘sensors_to_show’ data from the database, ensuring that older formats are parsed correctly. - It checks if each sensor is accessible by the user and filters out any unauthorized sensors. - The sensor structure is rebuilt according to the latest format, which allows for grouping sensors and adding optional titles.

Details on format: - The ‘sensors_to_show’ attribute is defined as a list of sensor IDs or nested lists of sensor IDs (to indicate grouping). - Titles may be associated with rows of sensors. If no title is provided, {“title”: None} will be assigned. - Nested lists of sensors indicate that they should be shown together (e.g., layered in the same chart).

Example inputs: 1. Simple list of sensors, where sensors 42 and 44 are grouped:

sensors_to_show = [40, 35, 41, [42, 44], 43, 45]

  1. List with titles and sensor groupings:
    sensors_to_show = [

    {“title”: “Title 1”, “sensor”: 40}, {“title”: “Title 2”, “sensors”: [41, 42]}, [43, 44], 45, 46

    ]

Parameters: - suggest_default_sensors: If True, the function will suggest default sensors if ‘sensors_to_show’ is not set. - If False, the function will return an empty list if ‘sensors_to_show’ is not set.

Returned structure: - The function returns a list of dictionaries, with each dictionary containing either a ‘sensor’ (for individual sensors) or ‘sensors’ (for groups of sensors), and an optional ‘title’. - Example output:

[

{“title”: “Title 1”, “sensor”: <Sensor object for sensor 40>}, {“title”: “Title 2”, “sensors”: [<Sensor object for sensor 41>, <Sensor object for sensor 42>]}, {“title”: None, “sensors”: [<Sensor object for sensor 43>, <Sensor object for sensor 44>]}, {“title”: None, “sensor”: <Sensor object for sensor 45>}, {“title”: None, “sensor”: <Sensor object for sensor 46>}

]

If the ‘sensors_to_show’ attribute is missing, the function defaults to showing two of the asset’s sensors, grouped together if they share the same unit, or separately if not. If the suggest_default_sensors flag is set to False, the function will not suggest default sensors and will return an empty list if ‘sensors_to_show’ is not set.

Note: Unauthorized sensors are filtered out, and a warning is logged. Only sensors the user has permission to access are included in the final result.

class flexmeasures.data.models.generic_assets.GenericAssetType(**kwargs)

An asset type defines what type an asset belongs to.

Examples of asset types: WeatherStation, Market, CP, EVSE, WindTurbine, SolarPanel, Building.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.