Repository navigation
Convert posted sensor data to the sensor unit before upsampling it - #2841
Conversation
PostSensorDataSchema upsampled posted values to the sensor's resolution first, and only then converted them to the sensor's unit, using the resolution after upsampling. For a stock unit posted to a flow sensor, such as one value of 4 kWh over PT1H to a kW sensor with a 15 minute resolution, each repeated 4 kWh was read as 4 kWh per 15 minutes, so 16 kW was recorded instead of 4 kW. Convert the values over the resolution they were posted in, then upsample them. Adds cases to test_post_sensor_data for m³ values posted to the gas sensor (m³/h, 10 minutes) at a 20 minute and a 1 hour resolution, and a changelog entry. Signed-off-by: Sajal Kumar Jana <[email protected]>
Signed-off-by: Sajal Kumar Jana <[email protected]>
e06ae31 to
3aa5e3a
Compare
|
Rebased onto the latest main and resolved the conflict in documentation/changelog.rst by moving my entry under the v1.2.0 bugfixes. The sensor data API tests pass locally. |
Flix6x
left a comment
There was a problem hiding this comment.
Thanks for the clear issue and write-up! Converting over the posted resolution is right for a stock unit posted to a flow sensor, and the two new cases show it. But the swap breaks the opposite direction, which main gets right today. And with a little more, we can fix the kWh to kWh case as well.
A flow posted to a stock sensor is now recorded several times too high. Take one value of 4 kW over PT1H, posted to a kWh sensor with a 15-minute resolution. On main it is repeated first (four times 4 kW) and each value is converted over 15 minutes: 1 kWh each, which is right. With this PR it is converted over the hour first (4 kWh) and that amount is then repeated: four times 4 kWh. Running the schema's two steps in each order, for one value of 4 posted over an hour to a 15-minute sensor:
| posted → sensor | right | main | this PR |
|---|---|---|---|
| kWh → kW (#2840) | 4 | 16 | 4 |
| kW → kWh | 1 | 1 | 4 |
| kW → kW | 4 | 4 | 4 |
| kWh → kWh | 1 | 4 | 4 |
The tests don't catch it because the gas sensor in the API test fixtures has a flow unit.
The fix is to pick the order by direction: upsample first when the conversion turns a flow into a stock change, and convert first otherwise. If you don't mind, we'll take it from here and push it to your branch, together with the kWh to kWh fix below and an entry in the API changelog (documentation/api/change_log.rst). The order part is roughly this, in unit_utils.py:
def converts_flow_to_stock(from_unit: str, to_unit: str) -> bool:
"""Tell whether converting from one unit to the other turns a flow into a stock change, which needs a duration.
>>> converts_flow_to_stock("kW", "kWh")
True
>>> converts_flow_to_stock("kWh", "kW")
False
>>> converts_flow_to_stock("kW", "MW")
False
>>> converts_flow_to_stock("°F", "°C")
False
"""
if not is_valid_unit(from_unit) or not is_valid_unit(to_unit):
return False
scalar = (
ur.Quantity(from_unit).to_base_units() / ur.Quantity(to_unit).to_base_units()
)
return scalar.dimensionality == ur.Quantity("1/h").dimensionality(base units, because dividing °C by °C raises an OffsetUnitCalculusError), and in PostSensorDataSchema:
@staticmethod
def possibly_convert_and_upsample_values(data):
"""
Convert to the sensor's unit and upsample to the sensor's resolution, in the order that keeps the amounts right.
A flow (say kW posted to a kWh sensor) is repeated first, and each value is then converted over the sensor's resolution.
Anything else (say kWh posted to a kW sensor) is converted over the posted resolution first, and then repeated.
"""
if converts_flow_to_stock(data["unit"], data["sensor"].unit):
data = PostSensorDataSchema.possibly_upsample_values(data)
return PostSensorDataSchema.possibly_convert_units(data)
data = PostSensorDataSchema.possibly_convert_units(data)
return PostSensorDataSchema.possibly_upsample_values(data)called from post_load_sequence instead of the two steps. A test that needs no database covers both directions, for example in api/common/schemas/tests/test_sensor_data_schema.py (with from types import SimpleNamespace):
@pytest.mark.parametrize(
"posted_unit, sensor_unit, expected_value",
[
("kWh", "kW", 4), # a stock change to a flow: 4 kWh in 1 hour is 4 kW
("kW", "kWh", 1), # a flow to a stock change: 4 kW for 15 minutes is 1 kWh
("kW", "kW", 4), # a flow to a flow: repeated as it is
],
)
def test_convert_and_upsample_one_hourly_value(
posted_unit, sensor_unit, expected_value
):
"""One value of 4, posted for 1 hour to a sensor with a 15-minute resolution."""
data = dict(
values=[4.0],
unit=posted_unit,
duration=timedelta(hours=1),
sensor=SimpleNamespace(
unit=sensor_unit, event_resolution=timedelta(minutes=15)
),
)
data = PostSensorDataSchema.possibly_convert_and_upsample_values(data)
assert list(data["values"]) == pytest.approx([expected_value] * 4)With these changes, the new test, the sensor data API and schema tests, the data ingestion tests and the unit utils tests and doctests all pass.
kWh to kWh (and stock changes in general). Upsampling repeats each value, so 4 kWh over an hour posted to a 15-minute kWh sensor is stored as 4 kWh per 15 minutes. What a sensor measures isn't fully told by its unit: a kWh sensor could record a stock change per event, or a stock such as a state of charge. Repeating is right for a stock and wrong for a stock change. API v3 never upsamples to an instantaneous sensor, so we'd take this default: an energy unit on an instantaneous sensor is a stock, and an energy unit on a non-instantaneous sensor is a stock change. Concretely, upsampling to a non-instantaneous sensor with an energy unit splits each value over the new events instead of repeating it. Our push will include that, a test, and an explanation in the docstrings.
The API changelog entry will name both fixes as such: kWh posted to a kW sensor, and kWh posted to a kWh sensor, both at a coarser resolution than the sensor's. It will also note the exception: a non-instantaneous energy sensor that holds levels (say 15-minute state-of-charge targets) gets split values when data is posted to it at a coarser resolution. Telling stocks, stock changes and flows apart per sensor, with this as the default when nothing is set, goes into a new issue, which we'll open and link here.
Also:
- The branch conflicts with main again in
documentation/changelog.rst(v1.1.2 and v1.0.3 landed); we'll rebase it, keeping the entry under v1.2.0 Bugfixes. - Nit: the docstring of
post_load_sequencestill says "upsample and convert units" (our push updates that too).
If you'd rather make these changes yourself, just say so and we'll leave the branch to you.
The changelog conflicted by entries added in the same place; this PR's entry stays last under v1.2.0's Bugfixes. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01DWv6v3SfN2GwxVNn1ws2ep Signed-off-by: F.N. Claessen <[email protected]>
…split stock changes rather than repeat them Posted at a coarser resolution than the sensor's: - kW to a kWh sensor is repeated first, and each value then converted over the sensor's resolution (as before); - kWh to a kW sensor is converted over the posted resolution first, and then repeated (the original fix of this PR); - kWh to a kWh sensor is now split over the sensor's resolution, rather than repeated, as an energy value on a sensor with a non-zero resolution is a change in stock (an instantaneous sensor is never upsampled). Prices and other units are repeated as they were. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01DWv6v3SfN2GwxVNn1ws2ep Signed-off-by: F.N. Claessen <[email protected]>
|
As said in my review, I took over the follow-ups and pushed them to this branch:
For sensors that don't fit that default, I opened #2924: a sensor attribute saying whether its values are a flow, a stock change or a stock, which would set how they are resampled and converted. |
Flix6x
left a comment
There was a problem hiding this comment.
Thanks @SajalDevX, the follow-ups are in, and upsampling now keeps the amounts right. One more change before this can go in: the mirror case, downsampling.
What changed since my review, as I said I'd take it over:
- Values are converted and upsampled in the order that keeps the amounts right: kW posted to a kWh sensor is repeated and then converted per quarter-hour (right again, as on main), and kWh posted to a kW sensor is converted over the posted resolution and then repeated (your fix for #2840).
- kWh posted coarser to a kWh sensor is now split over the sensor's resolution, rather than repeated (4 kWh in an hour is 1 kWh per quarter-hour). Prices, ratios, percentages and other units are still repeated.
- Tests without a database for all of these cases, and the changelog entries, including one known limitation (documented, not handled): a non-instantaneous sensor that records a level in kWh (such as 15-minute state-of-charge targets) now gets split values when data is posted to it at a coarser resolution.
Requested change: downsampling still averages energy values. possibly_downsample_bdf calls bdf.resample_events(required_resolution) with its default method, the mean. So kWh posted every 15 minutes to an hourly kWh sensor is stored as the mean of the four values, not their sum: four times 1 kWh becomes 1 kWh for the hour instead of 4 kWh. The same goes for kW posted every 15 minutes to an hourly kWh sensor, as the values are converted to kWh per quarter-hour before they are downsampled. Since the values are in the sensor's unit by the time they are downsampled, the fix mirrors the split: sum when the sensor's unit is an energy unit, and keep the mean for anything else (kW, prices, ratios). We'll push that to this branch as well, with tests for both cases and an update to the changelog entries. The limitation for levels applies here too, and more strongly: summing levels (say 15-minute state-of-charge targets posted to an hourly kWh sensor) adds them up, and no single method is right for every level (a state of charge wants the last value, a minimum the highest, a maximum the lowest). So the API changelog will extend that note to downsampling: post levels at the sensor's own resolution.
For sensors that don't fit the default, #2924 proposes a sensor attribute saying whether its values are a flow, a stock change or a stock, and which resampling method fits them.
…ta posted coarser Values posted at a finer resolution than the sensor's were averaged into each slot, whatever their unit, so kWh posted every 15 minutes to an hourly kWh sensor was recorded as a quarter of what it was. Values in an energy unit (after conversion to the sensor's unit) are now summed, mirroring the split when upsampling; anything else, such as a flow or a price, is still averaged. The split added in the previous commit also ran for data posted finer than the sensor's resolution, where nothing is upsampled, and divided by zero; values are now only upsampled (and split) when posted coarser. As for upsampling, an energy level at a non-zero resolution (such as state-of-charge targets) is taken to be a stock change, which the API changelog notes as a known wrong interpretation until FlexMeasures#2924. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01DWv6v3SfN2GwxVNn1ws2ep Signed-off-by: F.N. Claessen <[email protected]>
|
As said in my review, I pushed the downsampling change myself (
|
Flix6x
left a comment
There was a problem hiding this comment.
Thanks @SajalDevX. With the downsampling change in (a4e652531), both directions now record energy in the right amounts:
- posted coarser than the sensor, values in an energy unit are split (and kWh to a kW sensor is converted before it is repeated);
- posted finer, they are summed: 1 kWh in each quarter-hour is 4 kWh in the hour, where it used to be averaged to 1 kWh. Flows and prices are still averaged.
That commit also fixes a division by zero my previous commit introduced for data posted finer than the sensor's resolution. The DB-free tests cover both directions, and the sensor data API, schema and ingestion tests pass.
One known limit is documented in the API changelog rather than handled, and it worries me: a level in kWh on a sensor with a non-zero resolution (such as the state-of-charge targets soc-minima and soc-maxima) is now split or summed as if it were a stock change, where main repeated and averaged it. That break should not ship on its own: I put #2924 (a sensor attribute saying what its values are) on the v1.2.0 milestone, so it lands in the same release and reverts the break for such levels.
The changelog conflicted by entries added in the same place; both are kept. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01DWv6v3SfN2GwxVNn1ws2ep Signed-off-by: F.N. Claessen <[email protected]>
…are stock changes (#2928) * Take energy values on a sensor to be levels unless it says they are stock changes Since #2841, POST sensors/data split energy values when posted at a coarser resolution than the sensor's, and summed them when posted at a finer one, taking every energy value on a non-instantaneous sensor to be a change in stock. For levels, such as state-of-charge targets used as soc-minima, that is wrong: hourly kWh minima posted to a 15-minute sensor were stored 4 times too low, so schedules planned too little charging. Now energy values are split and summed only on sensors with the attribute `quantity-type: stock-change` (see #2924), and repeated and averaged on any other sensor, as before #2841. The conversion order from #2841 stays: kWh posted to a kW sensor is still converted before it is repeated. Summing values posted with a horizon raised NotImplementedError (each value has its own belief time); it now converts to belief times and keeps the most recent belief per event. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01DWv6v3SfN2GwxVNn1ws2ep Signed-off-by: F.N. Claessen <[email protected]> * Document how posted values are resampled, and the quantity-type sensor attribute Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01DWv6v3SfN2GwxVNn1ws2ep Signed-off-by: F.N. Claessen <[email protected]> * Add the PR number to the changelog entry Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01DWv6v3SfN2GwxVNn1ws2ep Signed-off-by: F.N. Claessen <[email protected]> * Say how values relate to their interval with the CF-style sensor attribute cell-method Replace `quantity-type: stock-change` by `cell-method: sum` (values `sum`, `mean`, `maximum`, `minimum`, `point`, after the cell methods of the CF conventions); only `sum` is acted on here, for values in an energy unit. - kW posted to a kWh sensor is a change over each interval: converted per interval, then split or summed; it is refused (422) for a sensor whose cell-method is not `sum`, such as a level (`mean`). - An unknown cell-method is refused (422), naming the attribute and its allowed values, checked when the request comes in. - Values posted with a horizon at a finer resolution are aggregated when averaged too, not only when summed. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01DWv6v3SfN2GwxVNn1ws2ep Signed-off-by: F.N. Claessen <[email protected]> * Document cell-method with an example unit for each value, and update the changelogs Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01DWv6v3SfN2GwxVNn1ws2ep Signed-off-by: F.N. Claessen <[email protected]> * Cite the CF Conventions' section 7.3 (Cell Methods) and Appendix E for cell-method Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01DWv6v3SfN2GwxVNn1ws2ep Signed-off-by: F.N. Claessen <[email protected]> --------- Signed-off-by: F.N. Claessen <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
…n any unit (#2929) * Take energy values on a sensor to be levels unless it says they are stock changes Since #2841, POST sensors/data split energy values when posted at a coarser resolution than the sensor's, and summed them when posted at a finer one, taking every energy value on a non-instantaneous sensor to be a change in stock. For levels, such as state-of-charge targets used as soc-minima, that is wrong: hourly kWh minima posted to a 15-minute sensor were stored 4 times too low, so schedules planned too little charging. Now energy values are split and summed only on sensors with the attribute `quantity-type: stock-change` (see #2924), and repeated and averaged on any other sensor, as before #2841. The conversion order from #2841 stays: kWh posted to a kW sensor is still converted before it is repeated. Summing values posted with a horizon raised NotImplementedError (each value has its own belief time); it now converts to belief times and keeps the most recent belief per event. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01DWv6v3SfN2GwxVNn1ws2ep Signed-off-by: F.N. Claessen <[email protected]> * Document how posted values are resampled, and the quantity-type sensor attribute Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01DWv6v3SfN2GwxVNn1ws2ep Signed-off-by: F.N. Claessen <[email protected]> * Add the PR number to the changelog entry Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01DWv6v3SfN2GwxVNn1ws2ep Signed-off-by: F.N. Claessen <[email protected]> * Let a sensor say what its values are: quantity-type and resampling-method The sensor attribute `quantity-type` (`flow`, `stock-change` or `stock`) decides how data posted at another resolution than the sensor's is resampled: stock changes are split when upsampled and summed when downsampled, flows and stocks (levels) are repeated and averaged. A stock refuses values in a power unit, which can't be converted to a level. Without the attribute, values are repeated and averaged, as with the previous commit. The sensor attribute `resampling-method` (`mean`, `sum`, `min`, `max`, `first` or `last`) overrides how values are aggregated when downsampled; timely-beliefs only sums and averages, so min, max, first and last are aggregated here. Both attributes are validated by the sensor schema (API) and by `flexmeasures edit attribute` (CLI). Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01DWv6v3SfN2GwxVNn1ws2ep Signed-off-by: F.N. Claessen <[email protected]> * Add the PR number to the changelog entry Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01DWv6v3SfN2GwxVNn1ws2ep Signed-off-by: F.N. Claessen <[email protected]> * Say how values relate to their interval with the CF-style sensor attribute cell-method Replace `quantity-type: stock-change` by `cell-method: sum` (values `sum`, `mean`, `maximum`, `minimum`, `point`, after the cell methods of the CF conventions); only `sum` is acted on here, for values in an energy unit. - kW posted to a kWh sensor is a change over each interval: converted per interval, then split or summed; it is refused (422) for a sensor whose cell-method is not `sum`, such as a level (`mean`). - An unknown cell-method is refused (422), naming the attribute and its allowed values, checked when the request comes in. - Values posted with a horizon at a finer resolution are aggregated when averaged too, not only when summed. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01DWv6v3SfN2GwxVNn1ws2ep Signed-off-by: F.N. Claessen <[email protected]> * Document cell-method with an example unit for each value, and update the changelogs Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01DWv6v3SfN2GwxVNn1ws2ep Signed-off-by: F.N. Claessen <[email protected]> * Resample by the CF-style cell-method in any unit, instead of quantity-type and resampling-method One sensor attribute, `cell-method` (`sum`, `mean`, `maximum`, `minimum`, `point`), says how each value relates to its interval: `sum` (a change over the interval, in any unit: kWh, m³, a ramp in kW, a price change, °C) is split and summed; `mean` (a level, flow or price) is repeated and averaged; `maximum`/`minimum` are repeated as bounds and aggregated by maximum/minimum; `point` (an instant) is repeated, and the last value per interval is kept. kW posted to a kWh sensor is converted per interval and split or summed, unless the sensor's cell-method is not `sum`. The attribute is validated on sensors (API and CLI), refusing misspellings of its name such as `cell_method`. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01DWv6v3SfN2GwxVNn1ws2ep Signed-off-by: F.N. Claessen <[email protected]> * Cite the CF Conventions' section 7.3 (Cell Methods) and Appendix E for cell-method Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01DWv6v3SfN2GwxVNn1ws2ep Signed-off-by: F.N. Claessen <[email protected]> * Document how point and maximum/minimum resample, and point posting-data readers to cell-method - point keeps the value of the last event in each interval (labelled by its start, such as :45 for an hour of quarter-hours), not a reading at the end of the interval; the code comment said otherwise. - maximum and minimum are repeated when upsampled as bounds for each shorter interval, not as their own extremes. - The posting-data tutorial says a meter in kWh or m³ needs cell-method: sum to be split and summed, linking to the section. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01DWv6v3SfN2GwxVNn1ws2ep Signed-off-by: F.N. Claessen <[email protected]> * Separate the cell_method label from the paragraph before it, so Sphinx registers it Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01DWv6v3SfN2GwxVNn1ws2ep Signed-off-by: F.N. Claessen <[email protected]> --------- Signed-off-by: F.N. Claessen <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
Description
documentation/changelog.rstPostSensorDataSchemaupsampled posted values first and converted units afterwards, with the resolution after upsampling. For a stock unit posted to a flow sensor at a coarser resolution, each repeated value was then read as the amount for the shorter interval. For example, one value of 4 kWh overPT1Hposted to a kW sensor with a 15 minute resolution was stored as 16 kW instead of 4 kW. Swapping the two steps converts over the resolution the data was posted in.Look & Feel
Gas sensor in the API test fixtures (
m³/h, 10 minute resolution), posting one hour:Before: six beliefs of -67.68 m³/h. After: six beliefs of -11.28 m³/h.
How to test
pytest flexmeasures/api/v3_0/tests/test_sensor_data_fresh_db.pyI added two cases to
test_post_sensor_data: three 20 minute values in m³ (expecting 3 * -11.28 m³/h) and one 1 hour value in m³ (expecting -11.28 m³/h). Both fail on main (stored as -67.68) and pass with the fix. I also ran the rest offlexmeasures/apiandflexmeasures/data/tests/test_data_ingestion.py.Further Improvements
Upsampling still repeats values as they are, so a stock-unit sensor (say kWh at 15 minutes) that gets one kWh value for a whole hour stores that amount four times. That seems like a separate question (repeat or split), so I left it alone here.
Related Items
Closes #2840
Sign-off