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
17 changes: 14 additions & 3 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,20 @@ release between minors that only adds (0.19.1).
credited the salvage at the end, discounted as `expected_npv`
discounts it (`NPVDistribution.salvage`, `undiscounted_salvage` and
`retire_at`). A salvage by age of the unit in service, and one unit
of several retiring, are still refused, saying what to give;
`best_switch_time`, `plan_vs_actual` and `task_value` still refuse a
unit's own salvage or retirement. Results without them are unchanged.
of several retiring, are still refused, saying what to give.
Results without them are unchanged.
- Added: `best_switch_time`, `plan_vs_actual` and a service's
`task_value` take a unit's own `retire_at` and `salvage` too, which
they refused. `best_switch_time` scans switch times up to the
retirement and credits every candidate's runs the salvage
(`SimulatedSwitchTime.salvage`, `undiscounted_salvage`, `retire_at`);
`plan_vs_actual` values the plan and the rest from today to the
retirement, with the salvage there (by age, from the unit's state
today), lists the salvage among what a log does not record, and
refuses a `now` past the retirement; `task_value` runs each side to
its plan's retirement, credits the salvage in the period it falls
in, and does no service after it. Results without them are
unchanged.
- 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
Expand Down
17 changes: 11 additions & 6 deletions repyability/maintenance/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2518,9 +2518,14 @@ only where it is the diagram's only unit; in a diagram of several it is
refused, saying to give the valuation's `retire_at`. The valuations of
runs (`npv_distribution`, `compare_npv`) end at a plan's retirement and
credit every run its salvage at the end (a number; a salvage by age is
refused), as `expected_npv` does; those of switch times and logs
(`best_switch_time`, `plan_vs_actual`) take a plan's escalation and
refuse its salvage and retirement, naming them.
refused), as `expected_npv` does, and so do `best_switch_time` (every
candidate credited alike, the candidates up to the retirement) and a
service's `task_value` (each side's runs to the plan's retirement, its
salvage in the period it falls in, no service after it).
`plan_vs_actual` values the plan and the rest from today to the
retirement, the salvage credited there as `expected_npv` credits it
(by age, from the unit's state today); a log past the retirement is
refused.

**The hand-worked answer, today.** The diagram of the one pump,
`RepairableRBD([("s", "p"), ("p", "t")], {"p": spec})`, valued by
Expand Down Expand Up @@ -2550,9 +2555,9 @@ retirement, plus the salvage `expected_npv` credits
what a plan alone needed was a name for its one-node diagram and the
unit's money on the plan. The simulated runs then took a salvage given
as a number and a retirement; a salvage by age in the runs (each run's
unit in service), a salvage and retirement in `best_switch_time` and
`plan_vs_actual`, and one unit's retirement within a system, are left
for later.
unit in service) and one unit's retirement within a system are left
for later; the switch times, logs and services' values took the plan's
own end next (`test_npv_runs_own_end.py`).

### UC-59: "A stop every month renews the bearing; a long overhaul every year renews the pump and the bearing. What is the plan worth over two years, and how available is the line?"

Expand Down
21 changes: 2 additions & 19 deletions repyability/rbd/_npv.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,24 +72,6 @@ def own_escalation(rbd, escalation):
return own_terms(rbd, math.inf, None, escalation, None)[1]


def refuse_own_end(rbd, method: str = "") -> None:
"""Refuse a valuation that credits no salvage and runs to its horizon
(``best_switch_time``, ``plan_vs_actual``, a service's value) for a
diagram whose components carry their own salvage or retirement,
which it would leave out."""
for node, own in getattr(rbd, "_valuation", {}).items():
for key in ("salvage", "retire_at"):
if key in own:
raise NotImplementedError(
f"Component {node!r} has its own {key!r}, which the "
"valuations of switch times and of logs "
"(best_switch_time, plan_vs_actual, task_value) do "
"not take yet: expected_npv and npv_distribution "
f"credit it. Value a plan without its {key!r} here "
"(and its worth at the end with expected_npv)."
)


def own_end(rbd, horizon: float, money):
"""Where a valuation of runs ends, and what it credits there, from
the components' own ``"retire_at"`` and ``"salvage"`` (see
Expand All @@ -107,7 +89,8 @@ def own_end(rbd, horizon: float, money):
raise NotImplementedError(
f"Component {node!r} has a salvage by age, which the "
"valuations of simulated runs (npv_distribution, "
"compare_npv) do not take yet: give it as a number, or "
"compare_npv, best_switch_time, a service's task_value) "
"do not take yet: give it as a number, or "
"value its worth at the end with expected_npv."
)
credits = _salvage(rbd, salvage, stop, None, set())
Expand Down
17 changes: 8 additions & 9 deletions repyability/rbd/_npv_runs.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,8 @@ def refusal(rbd) -> Optional[Tuple[str, Tuple[Hashable, ...]]]:
(),
)
for category, node, why in _pricing.unrecorded(rbd):
if category == "acquisition":
if category in ("acquisition", "salvage"):
# (Paid at the start, and credited at the end, by the runs.)
continue
whose = (
"A maintenance group's set-up cost"
Expand Down Expand Up @@ -108,12 +109,10 @@ def refusal(rbd) -> Optional[Tuple[str, Tuple[Hashable, ...]]]:
return None


def _require_priceable(rbd, own_end: bool = False) -> None:
"""Refuse a diagram whose runs cannot be priced; ``own_end``: the
valuation credits the components' own salvage and retirement
(``_npv.own_end``), else it refuses them."""
if not own_end:
_npv.refuse_own_end(rbd)
def _require_priceable(rbd) -> None:
"""Refuse a diagram whose runs cannot be priced (each valuation of
runs credits the components' own salvage and retirement, through
``_npv.own_end``)."""
found = refusal(rbd)
if found is not None:
raise NotImplementedError(found[0])
Expand Down Expand Up @@ -316,7 +315,7 @@ def npv_distribution(
tail = _share(tail, "tail")
checks.one_of("engine", engine, ("auto", "python", "numba"))
seed = _seed(seed)
_require_priceable(rbd, own_end=True)
_require_priceable(rbd)
return _priced_runs(
rbd,
horizon,
Expand Down Expand Up @@ -587,7 +586,7 @@ def compare_npv(
for diagram, which, s in zip(
(rbd, other), ("this plan", "the other plan"), settings
):
_require_priceable(diagram, own_end=True)
_require_priceable(diagram)
_require_matched(diagram, which, s[0], state)
this, that = (
_priced_runs(
Expand Down
18 changes: 14 additions & 4 deletions repyability/rbd/_plan_actual.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,9 +171,6 @@ def route(rbd, npv_route):

if npv_route.route == r.REFUSED:
return npv_route
own = r.refusal(lambda: _npv.refuse_own_end(rbd))
if own is not None:
return r.refused(own, tuple(rbd._valuation))
planned = r.refusal(lambda: _require_no_plans(rbd))
if planned:
return r.refused(planned)
Expand Down Expand Up @@ -446,7 +443,6 @@ def plan_vs_actual(
inflation=None,
) -> PlanVsActual:
"""See ``RepairableRBD.plan_vs_actual``."""
_npv.refuse_own_end(rbd, "plan_vs_actual")
escalation = _npv.own_escalation(rbd, escalation)
money = _npv.Money(
rbd, discount_rate, value_rate, escalation, rates, inflation
Expand All @@ -466,6 +462,20 @@ def plan_vs_actual(
f"now ({now:g}) is past the horizon ({horizon:g}): the plan "
"ends before today."
)
# A plan's own retirement ends it (and the rest from now) there, with
# its salvage credited at that end, as expected_npv credits it.
retire_at = _npv.own_terms(rbd, horizon, None, None, None)[2]
if retire_at is not None:
if now > retire_at and not math.isclose(
now, retire_at, rel_tol=1e-12
):
raise ValueError(
f"now ({now:g}) is past the retirement on the plan "
f"({retire_at:g}): the plan ends before today. Compare the "
"log with a plan to a later retire_at, or without one."
)
horizon = float(retire_at)
now = min(now, horizon)
for name, given in (("state", state), ("start_state", start_state)):
if given is not None and not isinstance(given, Mapping):
raise TypeError(
Expand Down
7 changes: 7 additions & 0 deletions repyability/rbd/_pricing.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@
"includes renewals the log does not mark."
)
_BOUGHT = "Paid at the start: the log does not record purchases."
_SALVAGE = (
"Credited at the plan's end (its retirement or the horizon): the log "
"does not record a sale."
)


def unrecorded(rbd) -> List[Tuple[str, Optional[Hashable], str]]:
Expand Down Expand Up @@ -91,6 +95,9 @@ def unrecorded(rbd) -> List[Tuple[str, Optional[Hashable], str]]:
for node, price in rbd.acquisition_costs.items():
if price:
out.append(("acquisition", node, _BOUGHT))
for node, own in getattr(rbd, "_valuation", {}).items():
if "salvage" in own:
out.append(("salvage", node, _SALVAGE))
return out


Expand Down
12 changes: 8 additions & 4 deletions repyability/rbd/_switch_runs.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,6 @@ def route(rbd, npv_route):
return r.refused(_NONE)
if npv_route.route == r.REFUSED:
return npv_route
own = r.refusal(lambda: _npv.refuse_own_end(rbd))
if own is not None:
return r.refused(own, tuple(rbd._valuation))
return r.AnalysisRoute(
r.SIMULATED,
"The diagram simulated with each candidate switch time on its "
Expand Down Expand Up @@ -207,6 +204,10 @@ def best_switch_time(
inflation,
)
H = _npv._number(horizon, "horizon", strict=True)
# The runs end at a plan's own retirement, and every run of every
# candidate credits its own salvage, as npv_distribution's do.
stop, salvage, nominal_salvage, retired = _npv.own_end(rbd, H, money)
H = stop
n = checks.whole_number(
1_000 if mc_samples is None else mc_samples, "mc_samples"
)
Expand All @@ -225,7 +226,7 @@ def at(s: float) -> np.ndarray:
samples, _, _, used = _runs(
twin, H, s, earned, money, n, seed, engine, state
)
valued[s] = (samples, used)
valued[s] = (samples + salvage, used)
return valued[s][0]

grid = np.linspace(0.0, H, count)
Expand Down Expand Up @@ -267,4 +268,7 @@ def at(s: float) -> np.ndarray:
rate_basis=money.basis,
inflation=money.inflation,
escalation=dict(money.escalation),
salvage=salvage,
undiscounted_salvage=nominal_salvage,
retire_at=stop if retired else None,
)
13 changes: 13 additions & 0 deletions repyability/rbd/results.py
Original file line number Diff line number Diff line change
Expand Up @@ -5291,6 +5291,16 @@ class SimulatedSwitchTime(_ResultMapping):
escalation : dict
Each stream's growth per unit time, as given (see
``ExpectedNPV``); empty with none.
salvage : float
The present value of the salvage the components' plans credit at
the end (their own ``"salvage"``, as a number), the same for
every candidate and in every run's NPV; 0 with none.
undiscounted_salvage : float
That salvage, not discounted.
retire_at : float or None
When a plan's own ``"retire_at"`` ended the runs before the
horizon (``horizon`` is then that time, and switching at it is
never switching); None otherwise.
"""

switch_time: float
Expand All @@ -5313,6 +5323,9 @@ class SimulatedSwitchTime(_ResultMapping):
rate_basis: str = "nominal"
inflation: Optional[float] = None
escalation: Dict[Hashable, float] = field(default_factory=dict)
salvage: float = 0.0
undiscounted_salvage: float = 0.0
retire_at: Optional[float] = None

def difference_interval(
self, against: str = "never switch", confidence: float = 0.95
Expand Down
22 changes: 16 additions & 6 deletions repyability/schedule/_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -343,19 +343,29 @@ def simulated(
("without", without_d, state_without),
):
_npv_runs._require_priceable(diagram)
priced = _npv.Money(diagram, rate, 0.0)
# The plan's own retirement ends its runs there, and its own
# salvage is credited then (as npv_distribution's runs), in the
# period it falls in; the periods after hold nothing.
stop, salvage, nominal_salvage, _ = _npv.own_end(
diagram, horizon, priced
)
own_ends = np.append(ends[ends < stop], stop)
last = own_ends.size - 1
_npv_runs._require_matched(
diagram, f"the plan {name} the service", horizon, state
diagram, f"the plan {name} the service", stop, state
)
priced = _npv.Money(diagram, rate, 0.0)
pv = np.zeros((n, periods))
nominal = np.zeros((n, periods))
count = np.zeros((n, periods))
pv[:, last] -= salvage
nominal[:, last] -= nominal_salvage
for first in range(0, n, _npv_runs._CHUNK):
size = min(_npv_runs._CHUNK, n - first)
ledger, runs = _npv_runs.priced_chunk(
diagram,
horizon,
ends,
stop,
own_ends,
priced,
size,
seed,
Expand All @@ -370,9 +380,9 @@ def simulated(
history, at, down, planned = _pricing.changes(
runs.components[node]._data
)
failed = down & ~planned & (at <= horizon)
failed = down & ~planned & (at <= stop)
k = np.minimum(
np.searchsorted(ends, at[failed], side="right"), periods - 1
np.searchsorted(own_ends, at[failed], side="right"), last
)
np.add.at(count, (first + history[failed], k), 1.0)
money[name], plain[name], fails[name] = pv, nominal, count
Expand Down
15 changes: 15 additions & 0 deletions repyability/schedule/_value.py
Original file line number Diff line number Diff line change
Expand Up @@ -823,6 +823,21 @@ def task_value(
ends = np.atleast_1d(usage.model_time(list(found.ends), unit=unit))
ends = np.maximum.accumulate(np.maximum(ends, 0.0))
due, dates, done_s = _done_instants(task, usage, notes)
retire_at = getattr(getattr(does, "plan", None), "retire_at", None)
if isinstance(does, Services) and retire_at is not None:
# The unit is retired on its plan (on the diagram's clock, the
# forecast's calendar time in ``unit``): no service after it.
from ._usage import UNITS

kept = done_s / 3600.0 / UNITS[unit] <= retire_at
if not kept.all():
notes.append(
f"The plan retires the unit {retire_at:g} {unit} into the "
f"forecast: the {int((~kept).sum())} service(s) after it "
"are not done."
)
dates = [d for d, k in zip(dates, kept) if k]
done_s = done_s[kept]
starts_s = usage._start_s
clock_s = usage._start_s + done_s
scale = usage._unit(unit)
Expand Down
Loading
Loading