import hashlib
import math
from typing import List, Union
import numpy as np
from citylearn import random_streams
from citylearn.base import Environment
[docs]
class PowerOutage:
"""Base stochastic power outage model class.
Randomly assigns power outage signal to time steps.
Parameters
----------
random_seed: int, optional
Pseudorandom number generator seed for repeatable results.
random_stream_version: str, optional
Derivation of the outage stream, ``'v2'`` (default) or ``'v1'`` (CityLearn 3.6.0 and earlier); see
:py:mod:`citylearn.random_streams`. A building that owns the model sets it to its own version at reset.
"""
def __init__(self, random_seed: int = None, random_stream_version: Union[str, int] = None):
self.random_seed = random_seed
self.random_stream_version = random_stream_version
self._episode_stream_key = None
@property
def random_stream_version(self) -> str:
return getattr(self, '_PowerOutage__random_stream_version', random_streams.DEFAULT_RANDOM_STREAM_VERSION)
@random_stream_version.setter
def random_stream_version(self, value: Union[str, int]):
self.__random_stream_version = random_streams.parse_random_stream_version(value)
@property
def random_seed(self) -> int:
if self.__random_seed is not None:
return self.__random_seed
episode_seed = getattr(self, '_episode_seed', None)
return np.random.randint(*Environment.DEFAULT_RANDOM_SEED_RANGE) if episode_seed is None else episode_seed
@random_seed.setter
def random_seed(self, value: int):
self.__random_seed = value
def _set_episode_seed(
self, seed: int, building_name: str, start: int, end: int,
random_stream_version: Union[str, int] = None, random_stream_episode: int = None,
) -> None:
"""Give the model a stable stream for this building and episode, shared by the controller and BAU.
With ``'v1'`` only an unseeded model uses it: a seeded model draws ``RandomState(random_seed)``
in every building and episode. With ``'v2'`` the stream is derived from the model's seed, or
the environment seed when the model has none, the building, the episode key and the window.
"""
if random_stream_version is not None:
self.random_stream_version = random_stream_version
payload = f'power-outage:{seed}:{start}:{end}:{building_name}'.encode('utf-8')
self._episode_seed = int.from_bytes(hashlib.sha256(payload).digest()[:4], 'big')
self._episode_root_seed = seed
self._episode_stream_key = (building_name, random_stream_episode, int(start), int(end))
def _signal_random_state(self) -> Union[np.random.RandomState, np.random.Generator]:
"""Random stream for one call of :py:meth:`get_signals`."""
if self.random_stream_version == random_streams.LEGACY_RANDOM_STREAM_VERSION:
return np.random.RandomState(self.random_seed)
explicit_seed = self.__random_seed
key = getattr(self, '_episode_stream_key', None)
if key is None:
return random_streams.generator(self.random_seed, random_streams.POWER_OUTAGE)
seed = self._episode_root_seed if explicit_seed is None else explicit_seed
return random_streams.generator(seed, random_streams.POWER_OUTAGE, *key)
[docs]
def get_signals(self, time_steps: int, **kwargs) -> np.ndarray:
"""Returns power outage signal time series.
Returns time series with randomly selected time steps set as candidates for power outage.
Parameters
----------
time_steps: int
Number of time steps in returned signal time series.
Other Parameters
----------------
kwargs: Any
Any other parameters specific to :py:meth:`get_signals` method for other subclasses of
:py:class:`citylearn.grid_resilience.PowerOutage`.
Returns
-------
signals: np.ndarray
Power outage time series signal where value of 0 indicates no power outage at time step index
whereas value of 1 indicates a power outage at said time step.
"""
nprs = self._signal_random_state()
signals = nprs.choice([0, 1], size=time_steps)
return signals
[docs]
class ReliabilityMetricsPowerOutage(PowerOutage):
"""Power outage signal stochastic model based on Distribution System Reliability Metrics.
Generates time series of power outage signals based on System Average Interruption Frequency Index (SAIFI)
and Customer Average Interruption Duration Index (CAIDI). The signal is generated by sampling `n` instances
from a binomial distribution to select days that experience power outage where the probability, `p`, is the
ratio of `saifi` to number of days in a year (365). The start time step index for the outage on each day is
then randomly selected from a uniform distribution of `start_time_steps` or all valid daily time step indexes.
Finally the duration of each power outage event is set by sampling from an exponential distribution with a
scale set to `caidi`.
Parameters
----------
saifi: float, default: 1.436
Number of non-momentary electric interruptions, per year, the average customer experienced
and is used as the average number of days per year that experience power outage.
caidi: float, default: 331.2
Average number of minutes it takes to restore non-momentary electric interruptions
and is used as the average length of a power outage.
start_time_steps: List[int], optional
List of candidate daily time step indexes to randomly select from when deciding start time step of an outage.
For example, for an hourly simulation that wants to consider power outages that start during the evening peak
between 4 PM to 7 PM will set `start_time_steps` as [15, 16, 17, 18]. By default all daily time step indexes
are considered.
Other Parameters
----------------
**kwargs : dict
Other keyword arguments used to initialize :py:class:`citylearn.grid_resilience.PowerOutage` super class.
Notes
-----
The reliability metrics are sourced from https://www.eia.gov/electricity/annual/html/epa_11_01.html.
"""
def __init__(self, saifi: float = None, caidi: float = None, start_time_steps: List[int] = None, **kwargs):
super().__init__(**kwargs)
self.saifi = saifi
self.caidi = caidi
self.start_time_steps = start_time_steps
@property
def saifi(self) -> float:
return self.__saifi
@property
def caidi(self) -> float:
return self.__caidi
@property
def start_time_steps(self) -> List[int]:
return self.__start_time_steps
@saifi.setter
def saifi(self, value: float):
self.__saifi = 1.436 if value is None else value
@caidi.setter
def caidi(self, value: float):
self.__caidi = 331.2 if value is None else value
@start_time_steps.setter
def start_time_steps(self, value: List[float]):
self.__start_time_steps = value
[docs]
def get_signals(self, time_steps: int, seconds_per_time_step: float, **kwargs) -> np.ndarray:
"""Returns power outage signal time series.
Returns time series with randomly selected time steps set as candidates for power outage.
Parameters
----------
time_steps: int
Number of time steps in returned signal time series.
seconds_per_time_step: float
Number of seconds in one `time_step`.
Other Parameters
----------------
kwargs: Any
Any other parameters specific to :py:meth:`get_signals` method for other subclasses of
:py:class:`citylearn.grid_resilience.PowerOutage`.
Returns
-------
signals: np.ndarray
Power outage time series signal where value of 0 indicates no power outage at time step index
whereas value of 1 indicates a power outage at said time step.
"""
nprs = self._signal_random_state()
legacy = self.random_stream_version == random_streams.LEGACY_RANDOM_STREAM_VERSION
days_per_year = 365.0
seconds_per_day = 86400.0
seconds_per_minute = 60.0
time_steps_per_day = seconds_per_day/seconds_per_time_step
time_steps_per_minute = seconds_per_minute/seconds_per_time_step
day_count = time_steps/time_steps_per_day
daily_outage_probability = self.saifi/days_per_year
start_time_steps = list(range(int(time_steps_per_day))) if self.start_time_steps is None else self.start_time_steps
signals = np.zeros(time_steps, dtype=int)
if legacy:
# CityLearn 3.6.0: drops day 0 and the partial last day, and floors durations.
outage_days = nprs.binomial(n=1, p=daily_outage_probability, size=int(day_count))
outage_day_ixs = outage_days*np.arange(outage_days.shape[0])
outage_day_ixs = outage_day_ixs[outage_day_ixs != 0]
outage_day_count = outage_days[outage_days == 1].shape[0]
outage_start_time_steps = nprs.choice(start_time_steps, size=outage_day_count)
outage_durations = nprs.exponential(scale=self.caidi, size=outage_day_count) # [mins]
outage_duration_time_steps = outage_durations*time_steps_per_minute
for i, j , k in zip(outage_day_ixs, outage_start_time_steps, outage_duration_time_steps):
start_ix = i*time_steps_per_day + j
end_ix = start_ix + k
start_ix = int(start_ix)
end_ix = int(end_ix)
signals[start_ix:end_ix] = 1
return signals
# Every day can have an outage, the partial last day included; an outage that starts past
# the end of the series is dropped and one that runs past it is truncated.
outage_days = nprs.binomial(n=1, p=daily_outage_probability, size=int(math.ceil(day_count - 1e-9)))
outage_day_ixs = np.flatnonzero(outage_days)
outage_start_time_steps = nprs.choice(start_time_steps, size=outage_day_ixs.size)
outage_durations = nprs.exponential(scale=self.caidi, size=outage_day_ixs.size) # [mins]
# Round to the nearest step, so durations are not biased half a step short.
outage_duration_time_steps = np.floor(outage_durations*time_steps_per_minute + 0.5).astype(int)
for i, j, k in zip(outage_day_ixs, outage_start_time_steps, outage_duration_time_steps):
start_ix = int(math.floor(i*time_steps_per_day + j))
signals[start_ix:start_ix + int(k)] = 1
return signals