|
|
@@ -0,0 +1,110 @@
|
|
|
+from pathlib import Path
|
|
|
+from pv_io import ROOT, station_info, parse_issue_time, validate_arrays, read_json
|
|
|
+
|
|
|
+def utc_series(values, label):
|
|
|
+ import pandas as pd
|
|
|
+ parsed = []
|
|
|
+ for value in values:
|
|
|
+ ts = pd.Timestamp(value)
|
|
|
+ if pd.isna(ts) or ts.tzinfo is None:
|
|
|
+ raise ValueError(f'{label} requires timezone-aware timestamps')
|
|
|
+ parsed.append(ts.tz_convert('UTC'))
|
|
|
+ return pd.DatetimeIndex(parsed, tz='UTC')
|
|
|
+
|
|
|
+def prepare_from_csv(station, issue_time, power_csv, ec_dir, receipts=None, replay=False):
|
|
|
+ import numpy as np
|
|
|
+ import pandas as pd
|
|
|
+ import yaml
|
|
|
+ from pv_forecast.deep.build import regular_power_history
|
|
|
+ from pv_forecast.features import solar_features
|
|
|
+ from pv_forecast.ec_latest import latest_available_run, build_latest_ec_future, RAW
|
|
|
+ info = station_info(station)
|
|
|
+ site = yaml.safe_load((ROOT / 'configs/sites.yaml').read_text(encoding='utf-8'))['sites'][info['site']]
|
|
|
+ issue = parse_issue_time(issue_time)
|
|
|
+ run = latest_available_run([issue], 8)[0]
|
|
|
+ ec_path = Path(ec_dir).resolve() / f'{run:%Y%m%d%H}.csv'
|
|
|
+ if not ec_path.is_file():
|
|
|
+ raise ValueError(f'missing selected EC file: {ec_path.name}; no automatic older-run fallback')
|
|
|
+ received = None
|
|
|
+ if receipts is not None:
|
|
|
+ if ec_path.name not in receipts:
|
|
|
+ raise ValueError(f'missing EC receipt for {ec_path.name}')
|
|
|
+ received = utc_series([receipts[ec_path.name]], 'EC receipt')[0]
|
|
|
+ if received > issue or received < run:
|
|
|
+ raise ValueError('EC receipt is after issue_time or before run time')
|
|
|
+ elif not replay:
|
|
|
+ raise ValueError('production requires EC receipts; use --replay only for historical replay')
|
|
|
+
|
|
|
+ power = pd.read_csv(power_csv)
|
|
|
+ if not {'timestamp', 'power_kw'}.issubset(power.columns):
|
|
|
+ raise ValueError('power CSV requires timestamp,power_kw')
|
|
|
+ if power.empty:
|
|
|
+ raise ValueError('history is empty')
|
|
|
+ power['timestamp'] = utc_series(power.timestamp, 'power.timestamp')
|
|
|
+ power = power[(power.timestamp <= issue) & (power.timestamp >= issue - pd.Timedelta(minutes=240))].copy()
|
|
|
+ if 'received_time' in power:
|
|
|
+ power['received_time'] = utc_series(power.received_time, 'power.received_time')
|
|
|
+ power = power[power.received_time <= issue].copy()
|
|
|
+ if power.empty:
|
|
|
+ raise ValueError('history has no available measurements')
|
|
|
+ power['power_kw'] = pd.to_numeric(power.power_kw, errors='coerce')
|
|
|
+ if power.timestamp.duplicated().any() or not np.isfinite(power.power_kw).all() or (power.power_kw < 0).any():
|
|
|
+ raise ValueError('history contains duplicate times, invalid values or negative kW; clean upstream')
|
|
|
+ histories = regular_power_history(power, pd.DatetimeIndex([issue]), info['capacity_kw'], .05)
|
|
|
+ if issue not in histories:
|
|
|
+ raise ValueError('history missing ratio exceeds 5%; skip issue')
|
|
|
+ original = histories[issue][None, :, :]
|
|
|
+ times = pd.date_range(issue - pd.Timedelta(minutes=235), issue, freq='5min')
|
|
|
+ solar = solar_features(times, site)
|
|
|
+ clear = solar.clear_sky_ghi.to_numpy() / 1000
|
|
|
+ ratio = np.clip(original[0, :, 0] / np.maximum(clear, .05), 0, 2)
|
|
|
+ extra = np.column_stack([ratio, clear, solar.solar_elevation.to_numpy() / 90,
|
|
|
+ solar.hour_sin.to_numpy(), solar.hour_cos.to_numpy()])
|
|
|
+ history = np.concatenate([original, extra[None]], axis=2).astype('float32')
|
|
|
+
|
|
|
+ ec = pd.read_csv(ec_path)
|
|
|
+ if not {'init_time', 'time', *RAW}.issubset(ec.columns):
|
|
|
+ raise ValueError('EC CSV missing required processed columns')
|
|
|
+ init = utc_series(ec.init_time, 'EC.init_time')
|
|
|
+ valid = utc_series(ec.time, 'EC.time')
|
|
|
+ if not len(ec) or not (init == run).all() or valid.duplicated().any() or not valid.is_monotonic_increasing:
|
|
|
+ raise ValueError('EC run/time order mismatch')
|
|
|
+ for column in RAW:
|
|
|
+ ec[column] = pd.to_numeric(ec[column], errors='coerce')
|
|
|
+ if not np.isfinite(ec[column]).all():
|
|
|
+ raise ValueError(f'EC {column} contains NaN/Inf')
|
|
|
+ for column in ('tcc', 'lcc', 'mcc', 'hcc'):
|
|
|
+ if not ec[column].between(0, 100).all():
|
|
|
+ raise ValueError(f'EC {column} must be a percentage in [0,100]')
|
|
|
+ if not ec['2t'].between(-100, 70).all() or not ec['2d'].between(-100, 70).all():
|
|
|
+ raise ValueError('EC 2t/2d must be Celsius, not Kelvin')
|
|
|
+ if (ec.ssrd < 0).any():
|
|
|
+ raise ValueError('EC ssrd must be nonnegative processed W/m2')
|
|
|
+ targets = issue + pd.to_timedelta(np.arange(15, 241, 15), unit='min')
|
|
|
+ if valid.min() > targets.min() or valid.max() < targets.max():
|
|
|
+ raise ValueError('EC does not cover all 16 forecast times; no extrapolation')
|
|
|
+ template = np.zeros((1, 16, 20), dtype='float32')
|
|
|
+ solar_future = solar_features(targets, site)
|
|
|
+ for j, name in enumerate(info['future_features']):
|
|
|
+ if name in solar_future:
|
|
|
+ template[0, :, j] = solar_future[name].to_numpy()
|
|
|
+ # The original helper caches EC files. Clear it when preparing a new external snapshot.
|
|
|
+ from pv_forecast.ec_latest import _load
|
|
|
+ _load.cache_clear()
|
|
|
+ raw, ec_audit = build_latest_ec_future([issue], Path(ec_dir), template, info['future_features'], 8, site=site)
|
|
|
+ if ec_audit.missing_run.any():
|
|
|
+ raise ValueError('selected EC run became unavailable')
|
|
|
+ schema = read_json(ROOT / 'input_schema.json')
|
|
|
+ data = dict(power_history=history, future_raw=raw, elevation=raw[:, :, 13].copy(),
|
|
|
+ issue_time_ns=np.array([issue.value], dtype='int64'), station_code=np.array(info['station_code']),
|
|
|
+ future_feature_names=np.array(info['future_features']), history_feature_names=np.array(schema['history_features']))
|
|
|
+ validate_arrays(data)
|
|
|
+ audit = dict(station_code=info['station_code'], issue_time=issue.isoformat(), selected_ec_run=run.isoformat(),
|
|
|
+ assumed_available_time=(run + pd.Timedelta(hours=8)).isoformat(),
|
|
|
+ ec_received_time=received.isoformat() if received is not None else None,
|
|
|
+ mode='replay' if replay else 'production', power_rows_used=len(power),
|
|
|
+ maximum_power_timestamp=power.timestamp.max().isoformat(),
|
|
|
+ power_receipt_filter_applied='received_time' in power,
|
|
|
+ capacity_kw=info['capacity_kw'])
|
|
|
+ return data, audit
|
|
|
+
|