pv_io.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. from pathlib import Path
  2. import json
  3. ROOT = Path(__file__).resolve().parent
  4. def read_json(path):
  5. return json.loads(Path(path).read_text(encoding='utf-8-sig'))
  6. def station_info(station, root=ROOT):
  7. mapping = read_json(Path(root) / 'input_schema.json')['station_mapping']
  8. for code, info in mapping.items():
  9. if station in (code, info['site']):
  10. return dict(info, station_code=code)
  11. raise ValueError(f'unknown station: {station}; use YUWEI, JMJD01 or ZHONGXIN')
  12. def parse_issue_time(value):
  13. import pandas as pd
  14. ts = pd.Timestamp(value)
  15. if pd.isna(ts) or ts.tzinfo is None:
  16. raise ValueError('issue_time requires an explicit timezone, e.g. +08:00')
  17. if ts != ts.floor('15min'):
  18. raise ValueError('issue_time must be on a 15-minute boundary')
  19. return ts.tz_convert('UTC')
  20. def validate_arrays(data):
  21. import numpy as np
  22. import pandas as pd
  23. for key in ('power_history', 'future_raw', 'elevation', 'issue_time_ns'):
  24. if key not in data:
  25. raise ValueError(f'missing input field: {key}')
  26. h, f, e, t = (np.asarray(data[k]) for k in ('power_history', 'future_raw', 'elevation', 'issue_time_ns'))
  27. n = len(h)
  28. if not n or h.shape != (n, 48, 7) or f.shape != (n, 16, 20) or e.shape != (n, 16) or t.shape != (n,):
  29. raise ValueError('input shapes must be [N,48,7], [N,16,20], [N,16], [N]; N > 0')
  30. if any(not np.isfinite(a).all() for a in (h, f, e)):
  31. raise ValueError('NaN/Inf in required input; skip this issue instead of filling future values')
  32. if not np.issubdtype(t.dtype, np.integer):
  33. raise ValueError('issue_time_ns must be integer UTC epoch nanoseconds')
  34. times = pd.to_datetime(t, unit='ns', utc=True)
  35. if times.isna().any() or times.duplicated().any() or not times.is_monotonic_increasing:
  36. raise ValueError('issue times must be valid, unique and increasing')
  37. if (times != times.floor('15min')).any():
  38. raise ValueError('issue times must be on 15-minute boundaries')
  39. if not np.allclose(e, f[:, :, 13], rtol=0, atol=1e-4):
  40. raise ValueError('elevation differs from future_raw column 13')
  41. return data
  42. def write_json(value, path):
  43. path = Path(path)
  44. path.parent.mkdir(parents=True, exist_ok=True)
  45. path.write_text(json.dumps(value, ensure_ascii=False, indent=2), encoding='utf-8')