diff --git a/CHANGELOG.md b/CHANGELOG.md index e8c02f6..43ac5e9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/repyability/maintenance/README.md b/repyability/maintenance/README.md index 5969c8b..756d7d4 100644 --- a/repyability/maintenance/README.md +++ b/repyability/maintenance/README.md @@ -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 @@ -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?" diff --git a/repyability/rbd/_npv.py b/repyability/rbd/_npv.py index cef23a0..b77596d 100644 --- a/repyability/rbd/_npv.py +++ b/repyability/rbd/_npv.py @@ -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 @@ -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()) diff --git a/repyability/rbd/_npv_runs.py b/repyability/rbd/_npv_runs.py index 7a0f598..cb2a86a 100644 --- a/repyability/rbd/_npv_runs.py +++ b/repyability/rbd/_npv_runs.py @@ -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" @@ -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]) @@ -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, @@ -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( diff --git a/repyability/rbd/_plan_actual.py b/repyability/rbd/_plan_actual.py index 484c18e..3947cf1 100644 --- a/repyability/rbd/_plan_actual.py +++ b/repyability/rbd/_plan_actual.py @@ -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) @@ -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 @@ -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( diff --git a/repyability/rbd/_pricing.py b/repyability/rbd/_pricing.py index ecb987d..e0fb41a 100644 --- a/repyability/rbd/_pricing.py +++ b/repyability/rbd/_pricing.py @@ -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]]: @@ -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 diff --git a/repyability/rbd/_switch_runs.py b/repyability/rbd/_switch_runs.py index 53b99db..66e3ef1 100644 --- a/repyability/rbd/_switch_runs.py +++ b/repyability/rbd/_switch_runs.py @@ -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 " @@ -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" ) @@ -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) @@ -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, ) diff --git a/repyability/rbd/results.py b/repyability/rbd/results.py index 965a52c..d70b4ae 100644 --- a/repyability/rbd/results.py +++ b/repyability/rbd/results.py @@ -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 @@ -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 diff --git a/repyability/schedule/_service.py b/repyability/schedule/_service.py index f88c263..fd6db58 100644 --- a/repyability/schedule/_service.py +++ b/repyability/schedule/_service.py @@ -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, @@ -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 diff --git a/repyability/schedule/_value.py b/repyability/schedule/_value.py index 78bf1b6..bf69982 100644 --- a/repyability/schedule/_value.py +++ b/repyability/schedule/_value.py @@ -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) diff --git a/repyability/tests/test_npv_runs_own_end.py b/repyability/tests/test_npv_runs_own_end.py index 5e20970..7550a47 100644 --- a/repyability/tests/test_npv_runs_own_end.py +++ b/repyability/tests/test_npv_runs_own_end.py @@ -99,3 +99,133 @@ def test_what_runs_still_refuse_says_what_to_give(): assert several.analysis_routes()["npv_distribution"].route == ( routes.REFUSED ) + + +# ------------------------------------------- switch times, logs, services + + +def _switching(**money): + """A one-block diagram on a covariate schedule (as + test_switch_time_diagram's), with a unit's own money.""" + rng = np.random.default_rng(3) + load = np.repeat([1.0, 2.0], 40) + x = 100.0 * rng.weibull(3.0, load.size) / load**2 + model = surv.WeibullPH.fit(x, Z=load[:, None]) + spec = { + "reliability": model, + "repairability": surv.Exponential.from_params([1.0]), + "replace_cost": 80.0, + "covariates": surv.StepSchedule.from_changepoints([0.0], [[1.0]]), + **money, + } + return RepairableRBD([("s", "a"), ("a", "t")], {"a": spec}) + + +def _search(rbd, horizon): + return rbd.best_switch_time( + {"a": [[1.5], [1.0]]}, + [1.5, 1.0], + horizon, + discount_rate=RATE, + mc_samples=200, + seed=11, + scan=5, + ) + + +def test_best_switch_time_credits_every_candidate_its_own_end(): + own = _search(_switching(salvage=50.0, retire_at=150.0), 200.0) + plain = _search(_switching(), 150.0) + worth = 50.0 * math.exp(-RATE * 150.0) + assert own.retire_at == 150.0 and own.horizon == 150.0 + assert own.salvage == pytest.approx(worth, rel=1e-15) + assert own.undiscounted_salvage == 50.0 + # The same candidates, from the same seed: each run its own NPV plus + # the salvage, and the same choice. + assert own.times == plain.times + np.testing.assert_allclose( + own.npvs, np.array(plain.npvs) + worth, rtol=0, atol=1e-9 + ) + np.testing.assert_allclose( + own.samples, plain.samples + worth, rtol=0, atol=1e-9 + ) + assert own.switch_time == plain.switch_time + assert plain.salvage == 0.0 and plain.retire_at is None + route = _switching(salvage=50.0).analysis_routes()["best_switch_time"] + assert route.route == routes.SIMULATED + + +def test_plan_vs_actual_ends_at_its_own_retirement_with_its_salvage(): + from repyability import Timeline + + log = Timeline.from_outages([(50.0, 52.0)], 100.0) + plan = with_money(retire_at=240.0, salvage=70.0) + own = plan.plan_vs_actual(log, 100.0, HORIZON, discount_rate=RATE) + plain = PLAIN.plan_vs_actual(log, 100.0, 240.0, discount_rate=RATE) + worth = 70.0 * math.exp(-RATE * 240.0) + assert own.horizon == 240.0 + assert own.plan_npv == pytest.approx(plain.plan_npv + worth, rel=1e-12) + assert own.rest_npv == pytest.approx(plain.rest_npv + worth, rel=1e-12) + assert own.revalued_npv == pytest.approx( + plain.revalued_npv + worth, rel=1e-12 + ) + # What happened so far is the plan's without them. + assert own.actual_so_far == pytest.approx(plain.actual_so_far) + assert own.variance_so_far == pytest.approx(plain.variance_so_far) + assert {"category": "salvage", "component": UnitPlan.NODE} in [ + {k: r[k] for k in ("category", "component")} for r in own.not_compared + ] + assert plan.analysis_routes()["plan_vs_actual"].route != routes.REFUSED + with pytest.raises(ValueError, match="past the retirement on the plan"): + with_money(retire_at=80.0).plan_vs_actual(log, 100.0, HORIZON) + + +def test_a_service_value_takes_its_plan_own_end(): + from repyability.maintenance import Restoration + from repyability.schedule import ( + Recurrence, + Services, + Task, + UsageForecast, + task_value, + ) + + life = surv.Weibull.from_params([8760.0, 3.0]) + service = Task( + "gearbox service", + every=Recurrence.every(3, "months", "2027-04-01"), + cost=800.0, + ) + usage = UsageForecast.calendar("2027-01-01", "2028-01-01") + + def worth(plan): + return task_value( + service, + Services(plan, Restoration(q=0.5)), + usage, + age=4000.0, + discount=0.07, + period="quarter", + unit="hours", + seed=5, + mc_samples=500, + ) + + plain = UnitPlan(life, "instant", prices=Prices(repair=12000.0)) + # A salvage at the forecast's end: credited to both sides alike. + from dataclasses import replace + + salvaged = worth(replace(plain, salvage=1000.0)) + base = worth(plain) + credit = 1000.0 * 1.07 ** (-365 / 365.25) + for side in ("with_task", "without_task"): + assert salvaged.total[side] == pytest.approx( + base.total[side] - credit, rel=1e-12 + ) + np.testing.assert_allclose(salvaged.value, base.value, atol=1e-9) + # Retired half way: the October service is not done, and nothing + # falls in the last quarter. + retired = worth(replace(plain, retire_at=4380.0, salvage=1000.0)) + assert retired.total["count"] == 2 + assert retired.with_task[3] == 0.0 and retired.without_task[3] == 0.0 + assert any("are not done" in note for note in retired.notes) diff --git a/repyability/tests/test_plan_alone.py b/repyability/tests/test_plan_alone.py index ebc4c84..35176b9 100644 --- a/repyability/tests/test_plan_alone.py +++ b/repyability/tests/test_plan_alone.py @@ -316,17 +316,11 @@ def test_one_unit_retiring_in_a_diagram_of_several_is_refused(): rbd.expected_npv(HORIZON, retire_at=100.0) -def test_the_valuations_of_logs_refuse_what_they_leave_out(): +def test_the_valuations_of_logs_and_runs_take_its_own_end(): + # Each credits it (test_npv_runs_own_end.py). plan = with_money(salvage=7.0) - message = "has its own 'salvage'" - log = Timeline.from_outages([(50.0, 52.0)], 100.0) - with pytest.raises(NotImplementedError, match=message): - plan.plan_vs_actual(log, 100.0, HORIZON) - assert plan.analysis_routes()["plan_vs_actual"].route == routes.REFUSED - # The runs credit it (test_npv_runs_own_end.py). - assert plan.analysis_routes()["npv_distribution"].route == ( - routes.SIMULATED - ) + for method in ("plan_vs_actual", "npv_distribution"): + assert plan.analysis_routes()[method].route != routes.REFUSED # Its own escalation the runs take, as the argument. grown = with_money(escalation=2e-4) runs = dict(discount_rate=RATE, mc_samples=50, seed=4)