Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,19 @@ release between minors that only adds (0.19.1).

### Added

- Added: `RepairableRBD(shutdowns=)` takes the site's `Opportunities`
in model time, so a site's shuts are one record for its parts'
policies and its diagram: each `Opportunity` is a shutdown of its name
(its period and offset or its dates, its duration, None taking no
time, `takes_down` as the scope), with the new
`Opportunity(idle_ageing=, opportunistic=)` and
`Opportunities(shut_costs=)` (the site's own cost of each shut, not a
part's price) for what only a diagram uses. The dict form stays as its
shorthand: the record gives the diagram its dicts make, with the same
values and seeded runs, and saves as them. Shuts on real dates go
through `Opportunities.on_diagram`, and a `ShutdownPolicy` is refused,
naming the record to give. Saved opportunities without the new options
are read as before.
- Added: `RepairableRBD.least_spend_for_downtime(horizon, limit, ...)`
and `UnitPlan.least_spend_for_downtime` (UC-68 of the maintenance
README): the least spend that keeps a bad run's downtime (hours, or
Expand Down
23 changes: 23 additions & 0 deletions docs/guide/system-maintenance.md
Original file line number Diff line number Diff line change
Expand Up @@ -1282,6 +1282,29 @@ and carries on from where it was.
| `idle_ageing` | True (the default): idle blocks keep ageing; False: they stand still. |
| `opportunistic` | `{node: age}`, or one age for every block in scope under age replacement: at each shut, a block under its own age replacement that is working and at least that old is renewed then, at its replacement's cost and in its time (its next replacement counts from then). Simulated: the exact methods refuse it, and `availability()` gives the count renewed at each shut (`outage_jobs`). |

**The site's record.** The shuts are the same stops a part's policy
uses, so they can be given as the site's
[`Opportunities`](maintenance.md) in model time: each `Opportunity` is
a shutdown of its name (`period` and `offset`, or `dates` as numbers;
its `duration`, None taking no time; `takes_down` the nodes it holds
off line; `idle_ageing` and `opportunistic` as above), and the record's
`shut_costs` gives each kind's cost. An opportunity's times run both
ways from its offset, so on the diagram's clock the first is the first
after 0 (a shut at 0 itself is not taken, as a task due at 0 is not).
The diagram is then the one the dicts make, value for value and run for
run, and saves as them. Shuts on real dates are put on the diagram's
clock with `Opportunities.on_diagram(start, end)`.

```python
from repyability import Opportunities, Opportunity, RepairableRBD

site = Opportunities(
[Opportunity("overhaul", period=8760.0, duration=72.0)],
shut_costs={"overhaul": 5000.0},
)
line = RepairableRBD(edges, components, shutdowns=site)
```

**Outages at given times.** A plan of outages is rarely on a period:
give a shutdown its `times`. Several shutdowns, each with its own times,
duration, scope and cost, make a list of different outages (their
Expand Down
3 changes: 1 addition & 2 deletions repyability/maintenance/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ Architecture):
| How bad a bad run is (a quantile or tail mean of a priced outcome, with its bound) | `repyability.value._risk` | UC-68 |

Not yet single:
- a site's shutdowns are both the diagram's `shutdowns=` dicts and `Opportunities`/`ShutdownPolicy`;
- the calendar's present values (`failures_by_period`) still bracket their discounting where the diagram's are exact;
- a nested `RepairableRBD`'s costs are not counted in its parent.

Expand Down Expand Up @@ -69,7 +68,7 @@ Not yet single:
| UC-21 | A plan against its outage log: expected and actual cash flows so far, the variance, and the plan re-valued from the states now | **Built**: `RepairableRBD.plan_vs_actual` |
| UC-46 | The spread of a plan's net present value: each simulated run's NPV, its percentiles, the chance of missing a hurdle and the average of the worst runs | **Built**: `RepairableRBD.npv_distribution` (with `contract=`), `compare_npv` |
| UC-22 | Overhauls that restore a unit only partly (a Kijima restoration factor), every Nth replacing it: availability, failures and cost per year against overhauls that renew it, and the cheapest interval | **Built**: a `"preventive"` spec's `"restoration"`, `"replace_every"` and `"replacement_cost"`, simulated (#398) |
| UC-23 | The line is shut 3 days every 12 months, every block gets its PM then and the bearing is replaced if older than X: availability, the shut's share of the downtime and cost, failures between shuts, and whether a 9- or 18-month shut is cheaper | **Built**: `RepairableRBD(shutdowns=...)`, tasks bound with `"shutdown"` and `"older_than"`; exact and numerical |
| UC-23 | The line is shut 3 days every 12 months, every block gets its PM then and the bearing is replaced if older than X: availability, the shut's share of the downtime and cost, failures between shuts, and whether a 9- or 18-month shut is cheaper | **Built**: `RepairableRBD(shutdowns=...)`, tasks bound with `"shutdown"` and `"older_than"`; exact and numerical; the shuts given as the site's `Opportunities` in model time (each opportunity a shutdown, `shut_costs` their costs) or as dicts, its shorthand |
| UC-24 | Outages on a timeline: shuts at given times with a duration and a scope (renew some blocks, restore others), the plan's cost by window and its NPV | **Built**: the same `shutdowns` at `"times"`; over a horizon, exact or numerical where every job renews its block (`expected_npv`, `expected_cost`, `expected_events_by_window`), simulated where a job restores part-way; no long run |
| UC-51 | A part replaced at a list of times in model time (8,000, 14,000 and 26,000 hours) rather than on one interval: its plan's availability, failures, cost and NPV over a horizon | **Built**: a `"preventive"` spec's `"replace_at"`; numerical over a horizon (`expected_npv`, `expected_cost`, `expected_events`, `mission_availability`, `point_availability`), simulated too; the long run refused |
| UC-52 | Is a mid-life upgrade worth its capital cost, should the system be retired before the horizon, and what is it worth with a salvage value at the end? | **Built**: a component spec's `"upgrade"` (numerical over a horizon, and simulated: `npv_distribution`, `compare_npv`), and `expected_npv(retire_at=, salvage=)` |
Expand Down
76 changes: 75 additions & 1 deletion repyability/maintenance/_calendar.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,18 @@ class Opportunity:
takes_down : list of str, optional
The labels (lines, units, areas) it takes down; by default None,
the whole site. A policy given ``where=`` uses only the
opportunities that take that label down.
opportunities that take that label down. On a diagram
(``RepairableRBD(shutdowns=Opportunities(...))``) the labels are
the nodes it holds off line.
idle_ageing : bool, optional
On a diagram: whether the blocks it holds off line and does not
work on keep ageing through it (True, the default) or stand still
until it ends. A part's policy does not use it.
opportunistic : float or dict, optional
On a diagram: the components it renews if they are at least so
old, as a diagram's shutdown's ``"opportunistic"`` (an age for
every component in its scope under age replacement, or a dict of
an age by component). A part's policy does not use it.
cost : float, optional
**Deprecated** (also as the second argument, the 0.14 form
``Opportunity(name, cost, period=...)``): a price on the
Expand Down Expand Up @@ -174,6 +185,8 @@ class Opportunity:
duration: Optional[float] = None
at: Any = None
takes_down: Optional[Tuple[str, ...]] = None
idle_ageing: bool = True
opportunistic: Any = None

def __init__(
self,
Expand All @@ -190,6 +203,8 @@ def __init__(
at=None,
takes_down=None,
cost=None,
idle_ageing=True,
opportunistic=None,
):
if checks.is_number(rule):
# The 0.14 form, Opportunity(name, cost, period, offset, dates).
Expand Down Expand Up @@ -235,6 +250,8 @@ def __init__(
("duration", duration),
("at", at),
("takes_down", takes_down),
("idle_ageing", idle_ageing),
("opportunistic", opportunistic),
):
object.__setattr__(self, key, value)
self._check()
Expand All @@ -247,6 +264,8 @@ def __repr__(self) -> str:
continue
if f.name == "offset" and value == 0.0:
continue
if f.name == "idle_ageing" and value is True:
continue
shown.append(f"{f.name}={value!r}")
return f"Opportunity({', '.join(shown)})"

Expand Down Expand Up @@ -303,6 +322,44 @@ def _check(self) -> None:
f"site; got {self.takes_down!r}."
)
object.__setattr__(self, "takes_down", takes_down)
self._check_diagram_options()

def _check_diagram_options(self) -> None:
"""``idle_ageing`` and ``opportunistic``, which only a diagram
uses: checked here for their kind, and by the diagram against its
nodes."""
if not isinstance(self.idle_ageing, (bool, np.bool_)):
raise ValueError(
f"Opportunity {self.name!r}: idle_ageing must be True (the "
"blocks not worked on keep ageing) or False (they stand "
f"still), got {self.idle_ageing!r}."
)
object.__setattr__(self, "idle_ageing", bool(self.idle_ageing))
given = self.opportunistic
if given is None:
return
if isinstance(given, tuple) and all(
isinstance(pair, tuple) and len(pair) == 2 for pair in given
):
given = dict(given)
ages = list(given.values()) if isinstance(given, dict) else [given]
if not ages or not all(
checks.is_number(a) and float(a) >= 0.0 for a in ages
):
raise ValueError(
f"Opportunity {self.name!r}: opportunistic must be an age, "
"0 or more (inf for never), or a dict of an age by "
f"component, at least one; got {given!r}."
)
object.__setattr__(
self,
"opportunistic",
(
tuple((node, float(a)) for node, a in given.items())
if isinstance(given, dict)
else float(given)
),
)

def _check_model_time(self) -> None:
for key in ("then_every", "also_every", "at"):
Expand Down Expand Up @@ -691,6 +748,14 @@ def to_dict(self) -> dict:
)
if self.cost is not None:
out["cost"] = self.cost
if not self.idle_ageing:
out["idle_ageing"] = False
if self.opportunistic is not None:
out["opportunistic"] = (
[[node, age] for node, age in self.opportunistic]
if isinstance(self.opportunistic, tuple)
else self.opportunistic
)
return out

@classmethod
Expand Down Expand Up @@ -740,6 +805,15 @@ def from_dict(cls, data: dict) -> "Opportunity":
)
if data.get("cost") is not None:
made = made._replaced(cost=_price(data["cost"], "cost"))
opportunistic = data.get("opportunistic")
if isinstance(opportunistic, list):
opportunistic = {node: age for node, age in opportunistic}
if opportunistic is not None or "idle_ageing" in data:
made = made._replaced(
idle_ageing=data.get("idle_ageing", True),
opportunistic=opportunistic,
)
made._check_diagram_options()
return made


Expand Down
89 changes: 87 additions & 2 deletions repyability/maintenance/_opportunities.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,11 @@ class Opportunities:
time_zone : str, optional
On real dates: the site's IANA zone (``"Australia/Brisbane"``);
None: clock times as they are, with no daylight saving.
shut_costs : dict, optional
The site's own cost of each kind of shut, by name, charged at
every shut when the record is a diagram's shutdowns
(``RepairableRBD(shutdowns=...)``, as a shutdown's ``"cost"``):
not a part's price, which each part brings. By default none.

Examples
--------
Expand All @@ -273,7 +278,14 @@ class Opportunities:
True
"""

def __init__(self, opportunities=(), *, any_day=True, time_zone=None):
def __init__(
self,
opportunities=(),
*,
any_day=True,
time_zone=None,
shut_costs=None,
):
from repyability.schedule._meters import zone

if isinstance(opportunities, (Opportunity, _shutdowns.Shutdown)):
Expand Down Expand Up @@ -326,6 +338,7 @@ def __init__(self, opportunities=(), *, any_day=True, time_zone=None):
)
self.opportunities: Tuple[Opportunity, ...] = tuple(listed)
self.any_day: bool = any_day
self.shut_costs: Dict[str, float] = _shut_costs(shut_costs, names)
self.time_zone = time_zone
#: A failure's price from a deprecated Calendar(failure=).
self._failure_price: Optional[float] = None
Expand Down Expand Up @@ -511,6 +524,8 @@ def to_dict(self) -> dict:
out["failure_price"] = self._failure_price
if self._clock is not None:
out["time"] = self._clock
if self.shut_costs:
out["shut_costs"] = dict(self.shut_costs)
return out

@classmethod
Expand Down Expand Up @@ -540,14 +555,84 @@ def from_dict(cls, data: dict) -> "Opportunities":
"These Opportunities were saved by a newer RePyability "
f"(version {data['version']}): upgrade to read them."
)
return cls._legacy(
made = cls._legacy(
[Opportunity.from_dict(o) for o in data.get("opportunities", [])],
any_day=bool(data.get("any_day", True)),
any_day_price=data.get("any_day_price"),
failure=data.get("failure_price"),
clock=data.get("time"),
zone=data.get("time_zone"),
)
made.shut_costs = _shut_costs(data.get("shut_costs"), made.names)
return made

# -- on a diagram --------------------------------------------------

def _diagram_shutdowns(self) -> Dict[str, dict]:
"""The record as a diagram's shutdowns (model time only): one
shutdown per kind, by name, in the spec the dict form takes, so
that the record and the dicts it stands for are one diagram."""
if self.model_time is False:
raise ValueError(
"A diagram runs on model time, and these opportunities are "
"on real dates: put them on the diagram's clock with "
"Opportunities.on_diagram(start, end) and give the dict it "
"returns as shutdowns."
)
out: Dict[str, dict] = {}
for o in self.opportunities:
if o.cost is not None:
raise ValueError(
f"Opportunity {o.name!r} has a price of its own (a "
"part's, deprecated): a diagram's shut takes the site's "
"cost, Opportunities(shut_costs={name: cost})."
)
spec: Dict[str, Any] = {}
if o.period is not None:
period = float(o.period)
# Every period from the offset, both ways: on the diagram's
# clock, the first after 0 (a shut at 0 itself is not taken,
# as a task due at 0 is not).
spec["period"] = period
spec["offset"] = float(o.offset) % period
else:
spec["times"] = list(o.dates or ())
spec["duration"] = 0.0 if o.duration is None else o.duration
if o.takes_down is not None:
spec["scope"] = list(o.takes_down)
if o.name in self.shut_costs:
spec["cost"] = self.shut_costs[o.name]
if not o.idle_ageing:
spec["idle_ageing"] = False
if o.opportunistic is not None:
spec["opportunistic"] = (
dict(o.opportunistic)
if isinstance(o.opportunistic, tuple)
else o.opportunistic
)
out[o.name] = spec
return out


def _shut_costs(given, names) -> Dict[str, float]:
"""``Opportunities``' ``shut_costs`` checked: a cost, 0 or more, by the
name of one of its opportunities."""
if given is None:
return {}
if not isinstance(given, Mapping):
raise TypeError(
"shut_costs must map each kind of shut, by name, to the site's "
f"cost of it; got {given!r}."
)
out: Dict[str, float] = {}
for name, cost in given.items():
if name not in names:
raise ValueError(
f"shut_costs names {name!r}, which is not one of the "
f"opportunities {list(names)}."
)
out[name] = _price(cost, f"The shut cost of {name!r}")
return out


def _listed(names: List[str]) -> str:
Expand Down
23 changes: 21 additions & 2 deletions repyability/rbd/_shutdowns.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,25 @@
# -- validation ---------------------------------------------------------------


def as_specs(given):
"""A diagram's ``shutdowns`` in the dict form: an ``Opportunities``
record in model time read as one shutdown per kind (its shut costs,
durations, scopes and options), a dict or None as it is."""
from repyability.maintenance._opportunities import Opportunities
from repyability.maintenance._site_policy import ShutdownPolicy

if isinstance(given, Opportunities):
return given._diagram_shutdowns() or None
if isinstance(given, ShutdownPolicy):
raise ValueError(
"shutdowns takes the site's shuts, not a part's policy at them: "
"give the Opportunities the policy was worked out for, on the "
"diagram's clock (Opportunities.on_diagram(start, end) for "
"shuts on real dates)."
)
return given


def validate(given) -> Dict[Hashable, _Shutdown]:
"""A diagram's ``shutdowns`` (a dict of a name and a spec each),
checked: each spec's keys, its calendar, duration, cost and option,
Expand All @@ -79,8 +98,8 @@ def validate(given) -> Dict[Hashable, _Shutdown]:
return {}
if not isinstance(given, dict):
raise ValueError(
"shutdowns must be a dict of a name and a spec for each "
f"shutdown, got {given!r}."
"shutdowns must be Opportunities (in model time) or a dict of a "
f"name and a spec for each shutdown, got {given!r}."
)
out = {name: _validate_one(name, spec) for name, spec in given.items()}
_refuse_overlaps(list(out.values()))
Expand Down
Loading
Loading