Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
# and y-axis probabilistic fx
ts_fig = timeseries(
value_df, meta_df, report.report_parameters.start,
report.report_parameters.end, units, (None, 'y'),
report.raw_report.timezone)
ts_fig.update_layout(
plot_bgcolor=PLOT_BGCOLOR,
font=dict(size=14),
margin=PLOT_MARGINS,
)
# probability vs time plot for the x-axis probabilistic fx
if any(
(
isinstance(pfxob.original.forecast, (
datamodel.ProbabilisticForecast,
datamodel.ProbabilisticForecastConstantValue)) and
pfxob.original.forecast.axis == 'x')
for pfxob in pfxobs
):
ts_prob_fig = timeseries(
value_df, meta_df, report.report_parameters.start,
report.report_parameters.end, units, ('x',),
report.raw_report.timezone)
ts_prob_fig.update_layout(
plot_bgcolor=PLOT_BGCOLOR,
font=dict(size=14),
margin=PLOT_MARGINS,
)
ts_prob_fig_json = ts_prob_fig.to_json()
else:
ts_prob_fig_json = None
def _post_forecast_values(session, fx, fx_vals, model_str):
if isinstance(fx, datamodel.ProbabilisticForecast):
if not model_str.startswith('gefs'):
raise ValueError(
'Can only process probabilisic forecast from GEFS')
if not isinstance(fx_vals, pd.DataFrame) or len(fx_vals.columns) != 21:
raise TypeError(
'Could not post probabilistic forecast values: '
'forecast values in unknown format')
# adjust columns to be constant values
cv_df = fx_vals.rename(columns={i: i * 5.0 for i in range(22)})
for cv_fx in fx.constant_values:
# will raise a KeyError if no match
cv_vals = cv_df[cv_fx.constant_value]
logger.debug('Posting %s values to %s', len(cv_vals),
cv_fx.forecast_id)
session.post_probabilistic_forecast_constant_value_values(
else:
fx_dict['site'] = self.get_site(fx_dict['site_id'])
elif fx_dict['aggregate_id'] is not None:
fx_dict['aggregate'] = self.get_aggregate(fx_dict['aggregate_id'])
cvs = []
for constant_value_dict in fx_dict['constant_values']:
# the API just gets the groups attributes for the
# single constant value forecasts, so avoid
# those excess calls
cv_dict = fx_dict.copy()
cv_dict.update(constant_value_dict)
cvs.append(
datamodel.ProbabilisticForecastConstantValue.from_dict(
cv_dict))
fx_dict['constant_values'] = cvs
return datamodel.ProbabilisticForecast.from_dict(fx_dict)
interval_label='ending',
interval_value_type='interval_mean',
variable='ghi',
site=_DUMMY_SITE,
axis='y',
constant_values=range(0, 101, 5),
extra_parameters=json.dumps(
{'is_reference_forecast': True,
'model': 'gefs_half_deg_to_hourly_mean'
})
)
]
TEMPLATE_PROBABILISTIC_PERSISTENCE_FORECASTS = [
ProbabilisticForecast(
name='Hour Ahead Prob Persistence',
issue_time_of_day=dt.time(0),
lead_time_to_start=pd.Timedelta('1h'),
interval_length=pd.Timedelta('1h'),
run_length=pd.Timedelta('1h'),
interval_label='ending',
interval_value_type='interval_mean',
variable='ghi',
site=_DUMMY_SITE,
axis='y',
constant_values=range(0, 101, 5),
extra_parameters=json.dumps(
{'is_reference_persistence_forecast': True})
)
]
'None')
elif ref_fx is None and ref_data is not None:
raise ValueError(
'ref_data was supplied but fx_obs.reference_forecast is None')
if ref_fx is not None:
if fx.interval_length != ref_fx.interval_length:
raise ValueError(
f'forecast.interval_length "{fx.interval_length}" must match '
'reference_forecast.interval_length '
f'"{ref_fx.interval_length}"')
if fx.interval_label != ref_fx.interval_label:
raise ValueError(
f'forecast.interval_label "{fx.interval_label}" must match '
f'reference_forecast.interval_label "{ref_fx.interval_label}"')
if isinstance(fx, datamodel.ProbabilisticForecast):
if fx.axis != ref_fx.axis:
raise ValueError(
f'forecast.axis "{fx.axis}" must match '
f'reference_forecast.axis "{ref_fx.axis}"')
issue_datetime -= template_forecast.run_length
issue_time_of_day = issue_datetime.time()
forecast = template_forecast.replace(
name=fx_name, extra_parameters=json.dumps(extra_parameters),
site=site, variable=variable, issue_time_of_day=issue_time_of_day,
)
existing = existing_forecasts(api)
if (
forecast.name in existing and
existing[forecast.name].site == forecast.site
):
logger.info('Forecast, %s, already exists', forecast.name)
return existing[forecast.name]
if isinstance(forecast, ProbabilisticForecast):
create_func = api.create_probabilistic_forecast
else:
create_func = api.create_forecast
try:
creation_validation(forecast)
except ValueError as exc:
logger.error('Validation failed on creation of %s forecast '
'at Site %s with message %s', variable, site.name, exc)
return
try:
created = create_func(forecast)
except HTTPError as e:
logger.error(f'Failed to create {variable} forecast at Site '
f'{site.name}.')
logger.debug(f'HTTP Error: {e.response.text}')
Should be used to version reports to ensure even older
reports can be properly rendered
"""
report_parameters: ReportParameters
raw_report: Union[None, RawReport] = None
status: str = 'pending'
report_id: str = ''
provider: str = ''
__version__: int = 0 # should add version to api
FORECAST_TYPE_MAPPING = {
'forecast': Forecast,
'event_forecast': EventForecast,
'probabilistic_forecast': ProbabilisticForecast,
'probabilistic_forecast_constant_value': ProbabilisticForecastConstantValue
}
def from_dict(model, input_dict, raise_on_extra=False):
dict_ = input_dict.copy()
if model != Forecast:
return super().from_dict(dict_, raise_on_extra)
if dict_.get('constant_value', None) is not None:
return ProbabilisticForecastConstantValue.from_dict(
dict_, raise_on_extra)
elif dict_.get('constant_values', None) is not None:
return ProbabilisticForecast.from_dict(dict_, raise_on_extra)
elif dict_.get('variable') == 'event':
return EventForecast.from_dict(dict_, raise_on_extra)
else:
return super().from_dict(dict_, raise_on_extra)