-
-
Notifications
You must be signed in to change notification settings - Fork 110
Integration Test fixes #314
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
yuvraajnarula
wants to merge
12
commits into
openclimatefix:main
Choose a base branch
from
yuvraajnarula:feat/292-integration-test-fix
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 11 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
a569435
feat: Fix PV data loading: timezone-aware merge and generation column…
yuvraajnarula e172b6e
chore : removal of parquet files"
yuvraajnarula 7a73047
chore : file read checker
yuvraajnarula f1022f3
chore : ruff checks
yuvraajnarula 9d8cdbf
chore : ruff checks pt .2
yuvraajnarula 89c005e
chore : ruff checks pt. 3
yuvraajnarula 03dc932
feat : args introduced for test
yuvraajnarula df6bc80
chore : data removal
yuvraajnarula 25a5280
feat: parameterized command for accessing 5_minutely and 30_minutely …
yuvraajnarula 606beb8
chore : ruff checks
yuvraajnarula 5259ba5
chore : parameterization introduced
yuvraajnarula f294716
chore : conftest.py
yuvraajnarula File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,93 +1,130 @@ | ||
| import glob | ||
| import os | ||
|
|
||
| import numpy as np | ||
| import pandas as pd | ||
| import xarray as xr | ||
| import pyarrow as pa | ||
| import pyarrow.dataset as ds | ||
| from huggingface_hub import HfFileSystem | ||
|
|
||
| fs = HfFileSystem() | ||
|
|
||
|
|
||
| def get_pv_metadata(testset: pd.DataFrame): | ||
| # download from hugginface or load from cache | ||
| def get_pv_metadata(testset: pd.DataFrame) -> pd.DataFrame: | ||
| """Merge metadata (lat/lon/capacity) with testset of pv_id + timestamp.""" | ||
| cache_dir = "data/pv" | ||
| metadata_file = f"{cache_dir}/metadata.csv" | ||
| if not os.path.exists(metadata_file): | ||
|
|
||
| if not os.path.exists(metadata_file) or os.path.getsize(metadata_file) == 0: | ||
| os.makedirs(cache_dir, exist_ok=True) | ||
| fs.get("datasets/openclimatefix/uk_pv/metadata.csv", metadata_file) | ||
|
|
||
| # Load in the dataset | ||
| metadata_df = pd.read_csv(metadata_file) | ||
|
|
||
| # join metadata with testset | ||
| # align schema | ||
| metadata_df = metadata_df.rename(columns={"ss_id": "pv_id"}) | ||
|
|
||
| combined_data = testset.merge(metadata_df, on="pv_id", how="left") | ||
|
|
||
| # only keep the columns we need | ||
| # keep only useful columns | ||
| combined_data = combined_data[ | ||
| ["pv_id", "timestamp", "latitude_rounded", "longitude_rounded", "kwp"] | ||
| ] | ||
|
|
||
| # rename latitude_rounded to latitude and longitude_rounded to longitude | ||
| combined_data = combined_data.rename( | ||
| ["pv_id", "timestamp", "latitude_rounded", "longitude_rounded", "kWp"] | ||
| ].rename( | ||
| columns={ | ||
| "latitude_rounded": "latitude", | ||
| "longitude_rounded": "longitude", | ||
| "kwp": "capacity", | ||
| "kWp": "capacity", | ||
| } | ||
| ) | ||
|
|
||
| # format datetime | ||
| combined_data["timestamp"] = pd.to_datetime(combined_data["timestamp"]) | ||
|
|
||
| return combined_data | ||
|
|
||
|
|
||
| def get_pv_truth(testset: pd.DataFrame): | ||
| print("Loading PV data") | ||
| FOLDER_TO_TIME_RES = { | ||
| "5_minutely": "5min", | ||
| "30_minutely": "30min", | ||
| } | ||
|
|
||
|
|
||
| def get_pv_truth( | ||
| testset: pd.DataFrame, horizon_hours: int = 48, folder_name: str = "30_minutely" | ||
| ) -> pd.DataFrame: | ||
| """ | ||
| Fetch PV generation truth values for given testset. | ||
| Optimized for performance using Arrow predicate filtering. | ||
| """ | ||
|
|
||
| # download from hugginface or load from cache | ||
| cache_dir = "data/pv" | ||
| metadata_file = f"{cache_dir}/pv.netcdf" | ||
| if not os.path.exists(metadata_file): | ||
| print("Loading from HF)") | ||
| parquet_dir = f"{cache_dir}/{folder_name}" | ||
|
|
||
| if not os.path.exists(parquet_dir): | ||
| print("Downloading PV parquet data from HuggingFace...") | ||
| os.makedirs(cache_dir, exist_ok=True) | ||
| fs.get("datasets/openclimatefix/uk_pv/pv.netcdf", metadata_file) | ||
|
|
||
| # Load in the dataset | ||
| pv_ds = xr.open_dataset(metadata_file, engine="h5netcdf") | ||
|
|
||
| combined_data = [] | ||
| for index, row in testset.iterrows(): | ||
| print(f"Processing {index} of {len(testset)}") | ||
| pv_id = str(row["pv_id"]) | ||
| base_datetime = pd.to_datetime(row["timestamp"]) | ||
|
|
||
| # Calculate future timestamps up to the max horizon | ||
| for i in range(0, 49): # 48 hours in steps of 1 hour | ||
| future_datetime = base_datetime + pd.DateOffset(hours=i) | ||
| horizon = i # horizon in hours | ||
|
|
||
| try: | ||
| # Attempt to select data for the future datetime | ||
| selected_data = pv_ds[pv_id].sel(datetime=future_datetime) | ||
| value = selected_data.values.item() | ||
| value = value / 1000 # to convert from w to kw | ||
| except KeyError: | ||
| # If data is not found for the future datetime, set value as NaN | ||
| value = np.nan | ||
|
|
||
| # Add the data to the DataFrame | ||
| combined_data.append( | ||
| pd.DataFrame( | ||
| { | ||
| "pv_id": pv_id, | ||
| "timestamp": future_datetime, | ||
| "value": value, | ||
| "horizon_hour": horizon, | ||
| }, | ||
| index=[i], | ||
| ) | ||
| ) | ||
| combined_data = pd.concat(combined_data) | ||
| return combined_data | ||
| fs.get(f"datasets/openclimatefix/uk_pv/{folder_name}", cache_dir, recursive=True) | ||
|
|
||
| # Find all non-empty parquet files | ||
| files = glob.glob(f"{parquet_dir}/**/*.parquet", recursive=True) | ||
| non_empty_files = [f for f in files if os.path.getsize(f) > 0] | ||
|
|
||
| if not non_empty_files: | ||
| raise FileNotFoundError("No valid parquet files found (all are empty).") | ||
|
|
||
| # Prepare filtering parameters | ||
| unique_pv_ids = testset["pv_id"].unique().tolist() | ||
| min_time = pd.to_datetime(testset["timestamp"]).min() | ||
| max_time = min_time + pd.Timedelta(hours=horizon_hours) | ||
|
|
||
| # Ensure timestamps are timezone-aware | ||
| testset["timestamp"] = pd.to_datetime(testset["timestamp"], utc=True) | ||
|
|
||
| # Define dataset with filtering | ||
| dataset = ds.dataset(non_empty_files, format="parquet") | ||
|
|
||
| arrow_min_time = pa.scalar(min_time, type=pa.timestamp("ns", tz="UTC")) | ||
| arrow_max_time = pa.scalar(max_time, type=pa.timestamp("ns", tz="UTC")) | ||
|
|
||
| filter_expr = ( | ||
| (ds.field("ss_id").isin(unique_pv_ids)) | ||
| & (ds.field("datetime_GMT") >= arrow_min_time) | ||
| & (ds.field("datetime_GMT") <= arrow_max_time) | ||
| ) | ||
|
|
||
| # Load filtered data only | ||
| table = dataset.to_table(filter=filter_expr) | ||
| pv_data = table.to_pandas() | ||
|
|
||
| # Ensure datetime column is parsed and aligned | ||
| pv_data["datetime_GMT"] = pd.to_datetime(pv_data["datetime_GMT"], utc=True) | ||
| time_resolution = FOLDER_TO_TIME_RES.get(folder_name) | ||
| if time_resolution is None: | ||
| raise ValueError( | ||
| f"Unknown folder_name '{folder_name}'. Please add it to FOLDER_TO_TIME_RES mapping." | ||
| ) | ||
|
|
||
| pv_data["datetime_GMT"] = pv_data["datetime_GMT"].dt.floor(time_resolution) | ||
|
|
||
| # Expand testset for all horizons | ||
| horizons = np.arange(horizon_hours + 1) | ||
| expanded = testset.loc[testset.index.repeat(len(horizons))].copy() | ||
| expanded["horizon_hour"] = np.tile(horizons, len(testset)) | ||
|
|
||
| # Calculate actual timestamp for each horizon | ||
| expanded["timestamp"] = expanded["timestamp"] + pd.to_timedelta( | ||
| expanded["horizon_hour"], unit="h" | ||
| ) | ||
| expanded["timestamp"] = expanded["timestamp"].dt.floor(time_resolution) | ||
| # Merge | ||
| merged = expanded.merge( | ||
| pv_data, | ||
| left_on=["pv_id", "timestamp"], | ||
| right_on=["ss_id", "datetime_GMT"], | ||
| how="left", | ||
| ) | ||
|
|
||
| # Convert to kWh | ||
| merged["value"] = merged["generation_Wh"] / 1000.0 | ||
|
|
||
| result = merged[["pv_id", "timestamp", "value", "horizon_hour"]].copy() | ||
|
|
||
| return result |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| import pytest | ||
|
|
||
| @pytest.mark.parametrize("folder_name", ["30_minutely", "5_minutely"]) | ||
| def test_folder_processing(folder_name): | ||
| """ | ||
| Run tests for both folder types using parameterization. | ||
| """ | ||
| print(f"Running tests for folder: {folder_name}") | ||
| assert folder_name in ["30_minutely", "5_minutely"] | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
And can this test be removed?
Or what does this do?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It shouldnt be in conftest.py
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
so should this contain the pytest_addoption and pytest_generate_tests hooks that enable the --foldername command-line option, not an actual test function?
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I have commented down the previous implementation and worked around pytest_addoption and pytest_generate_tests. So sorry for my confusion. Let me know if this is more cleaner and suitable for the PR.