From e5ca604bc390e4de53c464740a55edc46a829fa2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 07:04:50 +0000 Subject: [PATCH] Value a service on dates: no effect by default, or a stated effect task_value takes Services(plan, effect=). With no effect the service is an accepted cost, valued exactly at minus its cost's present value. A maintenance.Restoration or a fitted schedule.Condition credits a benefit: the plan's one-node diagram is simulated with the service on its dates and without it on common random numbers, each run priced with the plan's prices by period, and the value comes with its interval. Use case UC-67 in the schedule README. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L6RpnXB87vwhYETeh7ihtA --- CHANGELOG.md | 14 + docs/api/schedule.md | 4 + docs/guide/schedule.md | 50 +++ repyability/schedule/README.md | 114 +++++- repyability/schedule/__init__.py | 10 +- repyability/schedule/_service.py | 388 ++++++++++++++++++++ repyability/schedule/_value.py | 351 +++++++++++++++--- repyability/tests/test_schedule_services.py | 195 ++++++++++ 8 files changed, 1060 insertions(+), 66 deletions(-) create mode 100644 repyability/schedule/_service.py create mode 100644 repyability/tests/test_schedule_services.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d9622f..a82ba35 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,20 @@ release between minors that only adds (0.19.1). ### Added +- Added: `schedule.task_value` values a service (UC-67 of the schedule + README) with `Services(plan, effect=)`. By default a service has no + effect on the life: it is an accepted cost, and its value is minus its + cost's present value, exactly, with the notes saying so. A benefit + comes only from a stated effect: a `maintenance.Restoration` (a Kijima + factor from 0, as new at 0 under Kijima II and no effect at 1; a + virtual age; a fitted process) or a `schedule.Condition` (a regression + life fitted with a serviced-or-overdue covariate, as a covariate + schedule from the service's dates). With an effect, the plan's one-node + diagram is simulated with the service on its dates and without it on + the same random numbers, each run priced with the plan's prices by + period; `TaskValue` gains `method`, `value_lower`, `value_upper`, + `confidence`, `n_simulations` and `seed`. `task_value` takes + `mc_samples=`, `seed=` and `confidence=`. No existing result changes. - Added: a `RepairableRBD` takes `Shocks(rate, p, lethal_rate)` as a common-cause group's model, for members of any lives, which need not be alike. Shocks come at a rate of their own and each fails each diff --git a/docs/api/schedule.md b/docs/api/schedule.md index 107c7bc..8720161 100644 --- a/docs/api/schedule.md +++ b/docs/api/schedule.md @@ -65,4 +65,8 @@ tasks on dates and failures, events and work by calendar period (see the ::: repyability.schedule.Finds +::: repyability.schedule.Services + +::: repyability.schedule.Condition + ::: repyability.schedule.TaskValue diff --git a/docs/guide/schedule.md b/docs/guide/schedule.md index 18fb852..111adab 100644 --- a/docs/guide/schedule.md +++ b/docs/guide/schedule.md @@ -619,6 +619,56 @@ the device is taken to be working when the forecast starts. The task's solution. In model time, with the tests at any list of times, `failure_finding_window` gives the same numbers. +### Is a service worth it? + +A service (lubricate, adjust, clean, overhaul) neither replaces the unit +nor tests it, and what it does to the failure rate is not known from the +task. By default `task_value` takes it as having **no effect**: the +service is an accepted cost, and its value is minus its cost's present +value, worked out exactly. Say a gearbox, 4,000 h old and running around +the clock, is serviced every 3 months for $800: + +```python +from repyability.maintenance import Prices, Restoration, UnitPlan +from repyability.schedule import Services + +gearbox = UnitPlan(surv.Weibull.from_params([8760.0, 3.0]), "instant", + prices=Prices(repair=12000.0)) +service = Task("gearbox service", + every=Recurrence.every(3, "months", "2027-04-01"), cost=800.0) +year = UsageForecast.calendar("2027-01-01", "2028-01-01") +cost_only = task_value(service, Services(gearbox), year, age=4000.0, + discount=0.07) +round(cost_only.total["value"], 2) # -> -2320.95 +``` + +A benefit is credited only when you state what a service does. If the +fit of the gearbox's history (surpyval's `GeneralizedRenewal`) says each +service leaves 60% of its virtual age, give that restoration: + +```python +fitted = task_value(service, Services(gearbox, Restoration(q=0.6)), year, + age=4000.0, discount=0.07, mc_samples=1000, seed=4) +fitted.method # -> 'simulated' +round(fitted.total["value"], -1) # -> 3660.0 +round(fitted.total["value_lower"], -1) # -> 3240.0 +round(fitted.total["value_upper"], -1) # -> 4080.0 +``` + +The effect is the plan's own task effect, a `Restoration` (Kijima I or +II: 0 as new under Kijima II, 1 no effect, which is then valued exactly +as the default, above 1 a service that does harm; or a virtual age to +restore to, or a fitted process). A `Condition(life, fresh=, stale=, +lasts=)` instead takes a regression life fitted with a "serviced or +overdue" covariate, at `fresh` for `lasts` after each service. With an +effect, the plan's one-node diagram is simulated with the service on its +dates and without it, from one seed, so both see the same failures until +a service changes them; each run is priced with the plan's prices, by +period. `value_lower` and `value_upper` are the value's 90% interval +(`confidence=`), by period and in `total`. The plan must hold no +preventive task of its own. A virtual age on a duty plan that changes +over time is not followed yet: give the unit's duty as one share. + ### A system, by month A `RepairableRBD` runs on calendar time: its blocks' `"duty"` puts diff --git a/repyability/schedule/README.md b/repyability/schedule/README.md index a60ac4c..3903065 100644 --- a/repyability/schedule/README.md +++ b/repyability/schedule/README.md @@ -88,6 +88,7 @@ another site's calendar with other plans. | UC-49 | A system's expected costs by month, as present values | **Built**: `events_by_period(cost=True, discount=)` (exact) | | UC-50 | Is replacing the wear ring at every 6-monthly service worth it, at 7% a year? | **Built**: `task_value(task, Replaces(part), usage, discount=)` | | UC-54 | Is the 6-monthly trip test worth it, at 7% a year? | **Built**: `task_value` with `Finds(device, demand_rate=, consequence_cost=, repair_cost=)` | +| UC-67 | The gearbox is serviced every 3 months: what is the service worth at 7%, with no effect on its life (the default), as new, or with the fit's restoration factor? | **Built**: `task_value` with `Services(plan, effect=)`: no effect exact; a `Restoration`, or a fitted `Condition`, simulated on common random numbers with a 90% interval | | UC-57 | The same present values with costs escalating at a yearly rate | **Built**: `escalation=` beside `discount=` (the maintenance README's UC-57; the costs by period stay at today's prices) | | UC-32 | A pump on weekday shifts: its hours by month, and its 2,000-hour service on dates | **Built**: `DutyPlan`, `UsageForecast` | | UC-33 | A concrete run: when is the 500-hour check due? | **Built**: `Runs`, a crossing's stops | @@ -734,8 +735,7 @@ in `test_schedule_forecast.py`. - A planned replacement takes no time on the part's clock (its `time_to_replace` is a failure's, which `failures` counts). - Only a replacement is valued here (`Replaces`); a test of a hidden - failure is UC-54's (`Finds`), and what a service does is a later - use case, refused saying so. + failure is UC-54's (`Finds`), and a service UC-67's (`Services`). - The `calendar=` of `cost_by_window` is an optimised policy's thresholds, so it does not say "replace at every date, whatever the age"; `every=` says it only for even gaps in model time, which @@ -834,6 +834,106 @@ in `test_schedule_forecast.py`. falling with the test's cost, zero at the break-even price), `test_periods_add_up`, `test_refusals`. +### UC-67: "The gearbox is serviced every 3 months, and the fit says a service takes off 40% of its age. What is the service worth at 7%?" + +- **Status:** built: `task_value(task, Services(plan, effect=), usage, + age=, discount=, period=, mc_samples=, seed=, confidence=)` returning + a `TaskValue` whose `method` says `"exact"` or `"simulated"`. +- **Who asks:** UC-50's planner, about a task that neither replaces + nor tests: a service (lubricate, adjust, clean, overhaul). Most of a + plan's recurring tasks are services, and what a service does to the + failure rate is not known from the task. +- **What they know:** the gearbox's plan (`UnitPlan`): its life + (Weibull, scale 8,760 h, shape 3), each failure repaired as new in no + time at 12,000; it runs around the clock (`UsageForecast.calendar`), + 4,000 h old on 1 January 2027; the service every 3 months from 1 April + (`Recurrence.every(3, "months", "2027-04-01")`), 800 each; a year, to + 1 January 2028; 7% a year. What a service does, if they say: the fit + of the gearbox's history (surpyval's `GeneralizedRenewal`) gives a + Kijima II factor of 0.6 (a service leaves 60% of its virtual age). +- **What they want back:** the service's value against not doing it, + by quarter and in all, and how sure that is. +- **Decisions (the owner's, 21 Nov 2026):** + - **By default a service has no effect on the life**: it is an + accepted cost. RePyability never invents a benefit. Its value is + then minus the present value of its own cost, exactly, and the + answer says the effect was taken as none. + - A benefit is credited only through an effect the caller states: + a **restoration factor** (`maintenance.Restoration`, Kijima I or + II, the factor from 0 up: 0 is as new under Kijima II, 1 no effect, + above 1 a service that does harm, UC-62), a virtual age to restore + to, a fitted surpyval process, or a **fitted condition** + (`Condition(life, fresh=, stale=, lasts=)`: a regression life fitted + with a "serviced or overdue" covariate, at `fresh` for `lasts` after + each service and at `stale` otherwise, as a covariate schedule on + the diagram's clock, UC-41's `ScheduledLife`). +- **The answer, by hand:** the services are on 1 April, 1 July and 1 + October, 2,160, 4,344 and 6,552 h from the start (the forecast is + 8,760 h). Their present value is 800 × (1.07^(-90/365.25) + + 1.07^(-181/365.25) + 1.07^(-273/365.25)) = 786.77 + 773.62 + 760.55 = + **2,320.95** (2,400 undiscounted). + - *No effect (the default):* the value is **-2,320.95** (-786.77, + -773.62 and -760.55 in the second, third and fourth quarters, 0 in + the first), exactly. A factor of 1 (Kijima I or II) leaves the + gearbox as old as it was, which is the same statement: -2,320.95, + exactly. + - *As new (Kijima II, factor 0):* each service renews the gearbox, + and a failure in between is renewed too, so the plan is UC-50's + block replacement on the dates: from `NonRepairable.failures`, 0.271 + failures with the service against 1.149 without (renewal from 4,000 + h), 0.878 avoided, a value of **8,135.54** undiscounted (with + 5,652.28 against without 13,787.83) and **7,794.48** at 7% (within + 15.81, UC-50's bracket). + - *Factor 0.6:* no closed form: the simulation's value lies between + the two (checked: the value falls as the factor rises). +- **How it is solved:** the service's dates come from `Task.due` and + are laid on the diagram's clock (real time from the forecast's start, + in the plan's unit), as UC-50's are. With no effect, the value is the + task's cost at each instant, discounted through `repyability.value`, + and nothing else is worked out: the unit's own costs are the same with + and without the service and are left out of both sides. With an + effect, the plan's one-node diagram (`UnitPlan.diagram`, on a + `CalendarContext` giving the node its duty) runs twice from one seed: + with the service as a task of no duration at the dated times + (`BlockPolicy(times=, restoration=)`, or the covariate schedule its + dates give) and without it. The node is named alike in both, so it + draws the same random numbers in both (`compare_npv`'s common random + numbers) and each run's difference comes from the service. Each run's + history is priced with the plan's own prices by + `_npv_runs.priced_chunk` (the money module's `Ledger`), by calendar + period, discounted at the yearly rate per unit of the diagram's + clock; the service's own cost is the exact one of the default, added + to the with side. The value by period and in all is the mean + difference, with a two-sided interval (90% by default) from the runs' + spread. +- **Decisions (defaults):** + - A service takes no time, as UC-50's replacement and UC-54's test. + - A service due at the forecast's start is done then: its effect is + the start's (the gearbox's age taken as having had no action since + new, so a Kijima factor `q` leaves `q × age`). + - The plan holds no preventive task of its own (it holds one at most, + which the service would be); a plan that does is refused, saying to + value the service on the plan without it. + - 4,000 runs by default; a seed is drawn and kept when none is given. + - What the engine does not follow is refused with its own reason: a + virtual age on a duty plan that changes over time, a covariate + schedule with a duty, a state with imperfect repair. +- **Checks** (`test_schedule_services.py`): the default against the hand + numbers to the cent; factor 1 equal to the default exactly; as new + (factor 0) against UC-50's `Replaces` values within four standard + errors (bound fixed before the run); as new with minimal repairs + from new against the overhaul's closed form, the failures with + services every `T` being `H(T)` a stretch; seeded runs repeat; the + interval narrows with more runs; the value falls as the factor rises + (0, 0.6, 1.2); an exponential life gains nothing at any factor (the + interval holds minus the task's cost); a fitted condition's value + follows its covariate's effect; refusals. +- **Learned:** valuing a service needed no new engine: a dated task + with a restoration was already a plan's task, and the runs' pricing + already the money module's. The default of no effect is the honest + one: it states that the service is a cost until someone says what it + does. + ### UC-40: "Replacing the part is cheap at the annual overhaul, the first Tuesday of November. Can the calendar policy use the real dates?" - **Status:** built: `Opportunity.from_recurrence(name, cost, rule, @@ -952,10 +1052,12 @@ in `test_schedule_forecast.py`. for the policies on dates, with `discounted_run_to_failure` and `age_replacement_value` where the usage keeps a steady pace) is not joined to it yet; a task's long run is (`Task.long_run_value`). -- **The value of a service.** `task_value` takes `Replaces` and - `Finds`: a service that changes the failure rate (whose model of the - effect is still to be chosen) is a later use case, refused saying so. - A test that can miss a failure or that takes the device off line, and +- **A service on what the engine does not follow yet.** UC-67's + simulated effects keep the engine's limits: a virtual age is not + followed on a duty plan that changes, nor from a state with imperfect + repairs; a covariate of the time since the service (a ramp, not a + step) is not a schedule the engine takes. +- A test that can miss a failure or that takes the device off line, and an inspection that finds a warning before the failure (on condition), are not valued on dates yet either. - **A task's value for ever.** `task_value` values the forecast's window; diff --git a/repyability/schedule/__init__.py b/repyability/schedule/__init__.py index 0bbe259..3f3245e 100644 --- a/repyability/schedule/__init__.py +++ b/repyability/schedule/__init__.py @@ -26,8 +26,10 @@ - ``task_value``: what a task is worth against not doing it (with ``Replaces(part)``: block replacement on its dates against running to failure; with ``Finds(device, ...)``: tests of a hidden failure on its - dates against never testing), by calendar period, as present values - with a ``discount``. + dates against never testing; with ``Services(plan, effect=)``: a + service, by default an accepted cost with no effect on the life, or + with a stated ``Restoration`` or fitted ``Condition``, simulated), by + calendar period, as present values with a ``discount``. ``README.md`` in this package records the use cases, the question each answers and how it is solved. @@ -72,8 +74,10 @@ UsageForecast, ) from repyability.schedule._value import ( + Condition, Finds, Replaces, + Services, TaskValue, task_value, ) @@ -102,8 +106,10 @@ "Task", "TaskDue", "LongRunValue", + "Condition", "Finds", "Replaces", + "Services", "TaskValue", "WorkByPeriod", "work_by_period", diff --git a/repyability/schedule/_service.py b/repyability/schedule/_service.py new file mode 100644 index 0000000..fc97810 --- /dev/null +++ b/repyability/schedule/_service.py @@ -0,0 +1,388 @@ +"""What a service is worth (UC-67 of this package's ``README.md``). + +A service (lubricate, adjust, clean, overhaul) neither replaces the unit +nor tests it, and what it does to the failure rate is not known from the +task. ``Services(plan, effect=)`` says it: by default nothing, the +service an accepted cost, whose value is minus the present value of its +own cost, exactly. A benefit comes only from an effect the caller states, +a task effect on the plan: + +- a ``maintenance.Restoration`` (a Kijima factor, as new at factor 0 + under Kijima II, a virtual age to restore to, or a fitted process), + which the service's dated task carries (``BlockPolicy(times=, + restoration=)``); +- a ``Condition``: the plan's life a regression model fitted with a + "serviced or overdue" covariate, which the dates turn into a covariate + schedule on the diagram's clock. + +With an effect, the plan's one-node diagram (``UnitPlan.diagram``) runs +twice from one seed, with the service and without it; the node draws the +same random numbers in both (as ``compare_npv`` has it), each run's +history is priced by ``_npv_runs.priced_chunk`` with the plan's own +prices (the money module's ``Ledger``) by calendar period, and the value +is the mean difference with its interval. The service's own cost is the +exact one, at its instants, in both cases. +""" + +from __future__ import annotations + +import math +from dataclasses import dataclass, field, replace +from typing import Any, Dict, Optional, Tuple + +import numpy as np + +from repyability.utils.checks import is_number, real_array + +#: The runs a service's value takes by default. +MC_SAMPLES = 4000 + + +@dataclass(frozen=True) +class Condition: + """What a service does, as a fitted condition: the unit's ``life`` is + a surpyval regression model fitted with a covariate that says whether + the unit is serviced, ``fresh`` for ``lasts`` (in the plan's unit of + time) after each service and ``stale`` otherwise (and throughout + without the service). Plain data for + [`Services`][repyability.schedule.Services]. + + Parameters + ---------- + life : surpyval regression model + Proportional or additive hazards, or accelerated failure time, + fitted with the covariate (as a block's ``"covariates"`` takes). + fresh, stale : sequence of float + The covariates in force while serviced, and while overdue. + lasts : float + How long a service keeps the unit ``fresh``, more than 0. + """ + + life: Any + fresh: Tuple[float, ...] = field(kw_only=True) + stale: Tuple[float, ...] = field(kw_only=True) + lasts: float = field(kw_only=True) + + def __post_init__(self) -> None: + for name in ("fresh", "stale"): + row = real_array(getattr(self, name), name).ravel() + if not np.all(np.isfinite(row)): + raise ValueError(f"{name} must be finite covariates.") + object.__setattr__(self, name, tuple(float(z) for z in row)) + if len(self.fresh) != len(self.stale): + raise ValueError( + f"fresh has {len(self.fresh)} covariates and stale " + f"{len(self.stale)}: give the same covariates for both." + ) + if not (is_number(self.lasts) and 0.0 < float(self.lasts) < np.inf): + raise ValueError( + "lasts must be how long a service keeps the unit fresh, a " + f"number more than 0; got {self.lasts!r}." + ) + + def schedule(self, times: np.ndarray): + """The covariate schedule the services at ``times`` give.""" + from surpyval.univariate.regression import StepSchedule + + # Each service keeps the unit fresh for ``lasts``; a service before + # the last ran out keeps it fresh from then. + stretches: list = [] + for t in np.unique(np.asarray(times, float)): + end = float(t) + float(self.lasts) + if stretches and t <= stretches[-1][1]: + stretches[-1][1] = end + else: + stretches.append([float(t), end]) + points, values = [0.0], [self.stale] + for start, end in stretches: + if start <= points[-1]: + values[-1] = self.fresh + else: + points.append(start) + values.append(self.fresh) + points.append(end) + values.append(self.stale) + return StepSchedule.from_changepoints(points, values) + + def describe(self) -> str: + return ( + f"a fitted condition: covariates {list(self.fresh)} for " + f"{float(self.lasts):g} after each service, " + f"{list(self.stale)} otherwise" + ) + + +@dataclass(frozen=True) +class Services: + """What a task does: it services the unit of ``plan`` (a + ``maintenance.UnitPlan``) without replacing it, with the stated + ``effect`` on its life. Plain data for + [`task_value`][repyability.schedule.task_value]. + + By default (``effect=None``) a service has **no effect** on the life: + it is an accepted cost, valued at minus its own cost's present value, + exactly, and the plan is not needed. Otherwise: + + - a ``maintenance.Restoration``: each service restores the unit as + the restoration says (Kijima I or II factor ``q`` from 0, 0 as new + under Kijima II, 1 no effect, above 1 a service that does harm; a + virtual age to restore to; a fitted process); + - a [`Condition`][repyability.schedule.Condition]: the life a + regression model fitted with a serviced-or-overdue covariate. + + Parameters + ---------- + plan : UnitPlan, optional + The unit's plan: its life, repairs and prices, with no preventive + task of its own. Needed with an effect. + effect : Restoration or Condition, optional + What a service does to the life; by default nothing. + """ + + plan: Any = None + effect: Any = None + + def __post_init__(self) -> None: + from repyability.maintenance import Restoration, UnitPlan + + if self.effect is not None and not isinstance( + self.effect, (Restoration, Condition) + ): + raise TypeError( + "effect must say what a service does to the life: a " + "maintenance.Restoration (a Kijima factor, as new at q=0, " + "a virtual age, or a fitted process) or a " + "schedule.Condition (a fitted serviced-or-overdue " + "covariate); leave it out for no effect (the service an " + f"accepted cost). Got {self.effect!r}." + ) + if self.plan is not None and not isinstance(self.plan, UnitPlan): + raise TypeError( + "plan must be the unit's maintenance.UnitPlan (its life, " + f"repairs and prices); got {self.plan!r}." + ) + if self.no_effect: + return + if self.plan is None: + raise ValueError( + "A service with an effect needs the unit's plan: give " + "Services(plan, effect=...), plan a UnitPlan with its " + "life, repairs and prices." + ) + held = self.plan.task("preventive") + if held is not None: + raise ValueError( + f"The plan already holds a preventive task ({held!r}), and " + "holds one at most, which the service would be: value the " + "service on the plan without it." + ) + + @property + def no_effect(self) -> bool: + """Whether the service leaves the life as it is: no effect given, + or a Kijima factor of exactly 1 (the unit as old as it was).""" + effect = self.effect + if effect is None: + return True + return ( + not isinstance(effect, Condition) + and effect.q is not None + and effect.model in ("kijima1", "kijima2") + and float(effect.q) == 1.0 + and effect.replace_every is None + ) + + def describe(self) -> str: + """What the task does, in words.""" + effect = self.effect + if self.no_effect: + return "services the unit, with no effect on its life" + if isinstance(effect, Condition): + return f"services the unit, with {effect.describe()}" + if effect.to_age is not None: + what = f"restoring it to a virtual age of {effect.to_age:g}" + elif effect.process is not None: + what = "restoring it by its fitted process" + else: + what = f"restoring it by a {effect.model} factor of {effect.q:g}" + return f"services the unit, {what}" + + +@dataclass(frozen=True) +class Sides: + """A service's simulated value: by period, the two sides' mean + present values and undiscounted costs (the unit's own, the service's + cost apart), failures, and the value's interval, and the run's + settings.""" + + with_money: np.ndarray + without_money: np.ndarray + with_cost: np.ndarray + without_cost: np.ndarray + failures_with: np.ndarray + failures_without: np.ndarray + lower: np.ndarray + upper: np.ndarray + total_lower: float + total_upper: float + n: int + seed: int + engine: str + + +def _diagrams(does: Services, usage, unit: str, times: np.ndarray, age): + """The plan's one-node diagrams with the service (at ``times`` on the + diagram's clock) and without it, on the usage's calendar, and the + start state.""" + from repyability.maintenance import BlockPolicy, UnitPlan + from repyability.rbd.node_state import NodeState + + from ._calendar import CalendarContext + + plan: UnitPlan = does.plan + effect = does.effect + later = times[times > 0.0] + at_start = bool(np.any(times <= 0.0)) + if isinstance(effect, Condition): + with_plan = replace( + plan, life=effect.life, covariates=effect.schedule(times) + ) + without_plan = replace( + plan, + life=effect.life, + covariates=effect.schedule(np.array([])), + ) + else: + task = BlockPolicy( + times=tuple(float(t) for t in later), restoration=effect + ) + with_plan = replace(plan, tasks=plan.tasks + (task,)) + without_plan = plan + context = CalendarContext(usage, unit=unit) + duty = CalendarContext(usage, {plan.NODE: usage}, unit=unit).duty_plan( + plan.NODE + ) + if duty != 1.0: + context = CalendarContext(usage, {plan.NODE: usage}, unit=unit) + state_with = state_without = None + if age: + state_without = {plan.NODE: NodeState(age=float(age))} + start_age = float(age) + if at_start and not isinstance(effect, Condition): + # A service at the start: the unit taken to have had no action + # since new, so a factor leaves q times its age. + if effect.to_age is not None: + start_age = float(effect.to_age) + elif effect.process is not None: + raise NotImplementedError( + "A service due at the forecast's start restores the " + "unit by its fitted process, whose state at the start " + "is not given: start the forecast after it, or state " + "the effect as a Kijima factor." + ) + else: + start_age = float(effect.q) * float(age) + state_with = {plan.NODE: NodeState(age=start_age)} + return ( + with_plan.diagram(context), + without_plan.diagram(context), + state_with, + state_without, + ) + + +def simulated( + does: Services, + usage, + unit: str, + age: float, + times: np.ndarray, + ends: np.ndarray, + rate: float, + mc_samples: Optional[int], + seed, + confidence: float, + engine: str = "auto", +) -> Sides: + """The service's value by simulation: the plan's diagram with and + without it from one seed (``times`` and the periods' ``ends`` on the + diagram's clock, ``rate`` per unit of it), each run priced by period; + the service's own cost is not in either side.""" + from repyability.rbd import _montecarlo as montecarlo + from repyability.rbd import _npv, _npv_runs, _pricing + from repyability.utils import checks + + n = checks.whole_number( + MC_SAMPLES if mc_samples is None else mc_samples, "mc_samples" + ) + montecarlo.check_confidence(confidence) + seed = _npv_runs._seed(seed) + with_d, without_d, state_with, state_without = _diagrams( + does, usage, unit, times, age + ) + horizon = float(ends[-1]) + node = does.plan.NODE + periods = ends.size + money: Dict[str, np.ndarray] = {} + plain: Dict[str, np.ndarray] = {} + fails: Dict[str, np.ndarray] = {} + used = engine + for name, diagram, state in ( + ("with", with_d, state_with), + ("without", without_d, state_without), + ): + _npv_runs._require_priceable(diagram) + _npv_runs._require_matched( + diagram, f"the plan {name} the service", horizon, state + ) + priced = _npv.Money(diagram, rate, 0.0) + pv = np.zeros((n, periods)) + nominal = np.zeros((n, periods)) + count = np.zeros((n, periods)) + 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, + priced, + size, + seed, + engine, + first, + state, + ) + used = runs.engine + for (k, _category, _node), (a, b) in ledger.cells.items(): + pv[first : first + size, k] += a + nominal[first : first + size, k] += b + history, at, down, planned = _pricing.changes( + runs.components[node]._data + ) + failed = down & ~planned & (at <= horizon) + k = np.minimum( + np.searchsorted(ends, at[failed], side="right"), periods - 1 + ) + np.add.at(count, (first + history[failed], k), 1.0) + money[name], plain[name], fails[name] = pv, nominal, count + differences = money["without"] - money["with"] + z = montecarlo.z_value(confidence) + mean = differences.mean(axis=0) + spread = differences.std(axis=0, ddof=1) / math.sqrt(n) + whole = differences.sum(axis=1) + whole_se = float(whole.std(ddof=1) / math.sqrt(n)) + return Sides( + with_money=money["with"].mean(axis=0), + without_money=money["without"].mean(axis=0), + with_cost=plain["with"].mean(axis=0), + without_cost=plain["without"].mean(axis=0), + failures_with=fails["with"].mean(axis=0), + failures_without=fails["without"].mean(axis=0), + lower=mean - z * spread, + upper=mean + z * spread, + total_lower=float(whole.mean()) - z * whole_se, + total_upper=float(whole.mean()) + z * whole_se, + n=n, + seed=seed, + engine=used, + ) diff --git a/repyability/schedule/_value.py b/repyability/schedule/_value.py index 91f526d..78bf1b6 100644 --- a/repyability/schedule/_value.py +++ b/repyability/schedule/_value.py @@ -49,6 +49,7 @@ _tolerance, _usage, ) +from ._service import Condition, Services, simulated # noqa: F401 from ._task import Task from ._usage import _Plain @@ -215,6 +216,22 @@ class TaskValue(_Plain): operating time it is failed (in a period it does not run, its chance of being failed then); ``total`` has each over the whole forecast. None otherwise. + method : str + ``"exact"``, or ``"simulated"`` for a service with an effect. + value_lower, value_upper : numpy.ndarray or None + Simulated: each period's value's two-sided interval at + ``confidence`` (``total`` has ``value_lower`` and ``value_upper`` + over the whole forecast). None when exact. + confidence, n_simulations, seed : float, int, int or None + Simulated: the interval's level, the runs and their seed (to + repeat them). None when exact. + + With ``Services`` and no effect, the unit's own costs are the same + with and without the service and are left out of both sides: + ``with_task`` is the service's cost, ``without_task`` 0, and the + failures are NaN (not worked out), none avoided. With an effect, + each side is the unit's own costs (its plan's prices) in the + simulated runs, ``with_task`` adding the service's cost. With ``Finds``, "the part" is the device and a "failure" above is a demand that meets it failed: ``failures_with``, ``failures_without`` @@ -250,6 +267,12 @@ class TaskValue(_Plain): found: Optional[np.ndarray] = None unavailability_with: Optional[np.ndarray] = None unavailability_without: Optional[np.ndarray] = None + method: str = "exact" + value_lower: Optional[np.ndarray] = None + value_upper: Optional[np.ndarray] = None + confidence: Optional[float] = None + n_simulations: Optional[int] = None + seed: Optional[int] = None def __repr__(self) -> str: money = "present value" if self.discount is not None else "cost" @@ -476,6 +499,116 @@ def _in_periods(ends: np.ndarray, hidden) -> np.ndarray: return np.where(ran > 0.0, failed / np.where(ran > 0.0, ran, 1.0), at) +def _servicing( + does: Services, + price: float, + usage, + unit: str, + age: float, + times: np.ndarray, + done_s: np.ndarray, + seconds: np.ndarray, + discount: Optional[float], + mc_samples: Optional[int], + seed, + confidence: float, + count: int, +) -> Tuple[_Plan, Any]: + """``Services``: the words and notes of a service's two sides, and, + with an effect, its simulated runs (``_service.simulated``); None + for a service with no effect, which is valued exactly.""" + from repyability.value._rates import per_unit + + from ._usage import UNITS + + words = ( + f"With the task: the unit serviced each time the task is done " + f"({count} times in the forecast), at {price:g} a time" + ) + common = ( + "A calendar task is done at midnight of its date (or its visit's), " + "a task by use when the meter reaches its reading; a service " + "takes no time." + ) + if does.no_effect: + why = ( + "a factor of 1 leaves the unit as old as it was" + if does.effect is not None + else "no effect was given" + ) + return ( + _Plan( + with_events=np.zeros_like, + without_events=np.zeros_like, + event_cost=0.0, + extra_seconds=np.array([]), + extra_amounts=np.array([]), + error=0.0, + with_words=( + f"{words}, with no effect on its life ({why}): the " + "service is an accepted cost. The unit's own costs are " + "the same with and without it, and are left out of " + "both sides." + ), + without_words=( + "Without the task: the unit as it is; its own costs, " + "the same as with the task, left out." + ), + notes=( + common, + "The service's effect on the life was taken as none: " + "its value is minus its own cost. State an effect " + "(a maintenance.Restoration, or a schedule.Condition) " + "to credit it with a benefit.", + ), + ), + None, + ) + hours = UNITS[unit] + clock = done_s / 3600.0 / hours + ends = seconds / 3600.0 / hours + rate = 0.0 if not discount else per_unit(discount, hours) + sim = simulated( + does, + usage, + unit, + age, + clock, + ends, + rate, + mc_samples, + seed, + confidence, + ) + return ( + _Plan( + with_events=np.zeros_like, + without_events=np.zeros_like, + event_cost=0.0, + extra_seconds=np.array([]), + extra_amounts=np.array([]), + error=0.0, + with_words=( + f"{words}, {does.describe()[len('services the unit, '):]}; " + "the unit's failures, repairs and downtime at its plan's " + "prices." + ), + without_words=( + "Without the task: the same plan from the same age " + f"({age:g} {unit}) over the same dates, never serviced." + ), + notes=( + common, + f"Simulated: {sim.n} runs of each side from seed " + f"{sim.seed}, on the same random numbers (the unit draws " + "the same failures until a service changes them); the " + f"value's interval is two-sided at {confidence:g}.", + ), + ), + sim, + ) + + def task_value( task, does, @@ -487,6 +620,9 @@ def task_value( escalation: Optional[float] = None, period: str = "month", npv_tolerance: float = NPV_TOLERANCE, + mc_samples: Optional[int] = None, + seed: Optional[int] = None, + confidence: float = 0.9, ) -> TaskValue: """What a scheduled task is worth against not doing it, by calendar period and in all: the part's cost with the task, without it, and the @@ -523,19 +659,30 @@ def task_value( demands that meet the device failed, and it has the failures ``found`` and the device's unavailability with and without the task. + ``Services(plan, effect=)``: the task services the unit without + replacing it. With no effect (the default) the service is an accepted + cost: its value is minus its cost's present value, exactly. With an + effect (a ``maintenance.Restoration``, or a fitted + [`Condition`][repyability.schedule.Condition]) the plan's one-node + diagram is simulated with the service at its dated times and without + it, from one seed (common random numbers), each run priced with the + plan's prices by period; the value is the mean difference, with its + interval (``value_lower``, ``value_upper``). + Parameters ---------- task : Task The task, by the calendar or by use (``every=Usage(...)``). A calendar task is done at midnight of its date (or of its visit); a task by use when the meter reaches its reading. - does : Replaces or Finds + does : Replaces, Finds or Services What the task does. ``Replaces(part)``: the part a ``NonRepairable`` with an ``unplanned_cost``; its ``planned_cost`` is the task's price where the task has no ``cost``, and given both, they must agree. ``Finds(device, demand_rate=, consequence_cost=)``: the device a ``NonRepairable``, the task's ``cost`` a test's. + ``Services(plan, effect=)``: the task's ``cost`` a service's. usage : UsageForecast The map between dates and the part's operating time ([`DutyPlan.forecast`][repyability.schedule.DutyPlan.forecast], or @@ -563,6 +710,15 @@ def task_value( npv_tolerance : float, optional How close each side's failure cost is discounted, as for ``failures_by_period``; by default 1e-3. + mc_samples : int, optional + For a service with an effect: the runs of each side, by default + 4,000. + seed : int, optional + For a service with an effect: seeds the runs; by default one is + drawn, and kept in the result. + confidence : float, optional + For a service with an effect: the level of the value's two-sided + interval, by default 0.9. Returns ------- @@ -614,28 +770,39 @@ def task_value( """ if not isinstance(task, Task): raise TypeError(f"task must be a Task; got {task!r}.") - if not isinstance(does, (Replaces, Finds)): + if not isinstance(does, (Replaces, Finds, Services)): raise TypeError( "does must say what the task does: Replaces(part) for a task " - "that puts a new part in, or Finds(device, demand_rate=, " - "consequence_cost=) for a test of a hidden failure. The value " - "of a service that changes the failure rate is not built " - "yet. Got " + repr(does) + "." + "that puts a new part in, Finds(device, demand_rate=, " + "consequence_cost=) for a test of a hidden failure, or " + "Services(plan, effect=) for a service. Got " + repr(does) + "." ) usage = _usage(usage) - part = does.part if isinstance(does, Replaces) else does.device notes: List[str] = [] - unit = _resolve_unit( - unit, _model_label(getattr(part, "reliability", None)), "life", notes - ) + if isinstance(does, Services): + life = None if does.plan is None else does.plan.life + if isinstance(does.effect, Condition): + life = does.effect.life + label = _model_label(life) + else: + part = does.part if isinstance(does, Replaces) else does.device + label = _model_label(getattr(part, "reliability", None)) + unit = _resolve_unit(unit, label, "life", notes) if not (is_number(age) and 0.0 <= float(age) < np.inf): raise ValueError(f"age must be a number, at least 0; got {age!r}.") age = float(age) discount = _discount.yearly(discount) given, discount = discount, _discount.net(discount, escalation) npv_tolerance = _tolerance(npv_tolerance) - failure_cost = getattr(part, "cu", None) - if isinstance(does, Replaces): + if isinstance(does, Services): + if task.cost is None: + raise ValueError( + f"Task {task.name!r} has no cost: give the task's cost=, " + "what one service costs (0.0 if it is free)." + ) + price = float(task.cost) + elif isinstance(does, Replaces): + failure_cost = getattr(part, "cu", None) if failure_cost is None: raise ValueError( "The part has no unplanned_cost: without a failure's cost " @@ -663,62 +830,106 @@ def task_value( times = (usage._at_s("hours", clock_s) - base) / scale times = np.maximum(np.asarray(times, float).reshape(done_s.shape), 0.0) - if isinstance(does, Replaces): - plan = _replacing( - part, price, failure_cost, age, unit, times, len(dates) - ) - else: - plan = _testing( - does, price, age, unit, times, done_s, float(ends[-1]), len(dates) - ) - each = plan.event_cost - fails_with = np.diff(plan.with_events(ends), prepend=0.0) - fails_without = np.diff(plan.without_events(ends), prepend=0.0) - def by_period(at_seconds, amounts=None) -> np.ndarray: index = np.minimum( np.searchsorted(seconds, at_seconds, side="right"), n - 1 ) return np.bincount(index, weights=amounts, minlength=n).astype(float) + eac: Optional[Dict[str, float]] = None + sim: Optional[Any] = None task_cost: np.ndarray = price * by_period(done_s) - cost_with = each * fails_with + task_cost - if plan.extra_seconds.size: - cost_with = cost_with + by_period( - plan.extra_seconds, plan.extra_amounts + if isinstance(does, Services): + plan, sim = _servicing( + does, + price, + usage, + unit, + age, + times, + done_s, + seconds, + discount, + mc_samples, + seed, + confidence, + len(dates), ) - cost_without = each * fails_without - - precision = plan.error - eac: Optional[Dict[str, float]] = None - if discount is None or discount == 0.0 or ends[-1] <= 0.0: - money_with, money_without = cost_with, cost_without - money_task = task_cost + precision = 0.0 + if discount is None or discount == 0.0: + money_task = task_cost + else: + factors = _discount.factor(discount, done_s / _YEAR_SECONDS) + money_task = by_period(done_s, np.atleast_1d(price * factors)) + if sim is None: + fails_with = np.full(n, np.nan) + fails_without = np.full(n, np.nan) + cost_with, cost_without = task_cost, np.zeros(n) + money_with, money_without = money_task, np.zeros(n) + else: + fails_with, fails_without = sim.failures_with, sim.failures_without + cost_with = sim.with_cost + task_cost + cost_without = sim.without_cost + money_with = sim.with_money + money_task + money_without = sim.without_money else: - - def side(expected): - def costs(model_ends: np.ndarray) -> np.ndarray: - return each * np.diff(expected(model_ends), prepend=0.0) - - accrued, _, half = _accrued_npv( - usage, seconds, unit, discount, npv_tolerance, costs, notes + if isinstance(does, Replaces): + plan = _replacing( + part, price, failure_cost, age, unit, times, len(dates) ) - return accrued, half - - def at_instants(at_seconds, amounts) -> np.ndarray: - factors = _discount.factor(discount, at_seconds / _YEAR_SECONDS) - return by_period(at_seconds, np.atleast_1d(amounts * factors)) + else: + plan = _testing( + does, + price, + age, + unit, + times, + done_s, + float(ends[-1]), + len(dates), + ) + each = plan.event_cost + fails_with = np.diff(plan.with_events(ends), prepend=0.0) + fails_without = np.diff(plan.without_events(ends), prepend=0.0) - failures_with_pv, half_with = side(plan.with_events) - failures_without_pv, half_without = side(plan.without_events) - money_task = at_instants(done_s, price) - money_with = failures_with_pv + money_task + cost_with = each * fails_with + task_cost if plan.extra_seconds.size: - money_with = money_with + at_instants( + cost_with = cost_with + by_period( plan.extra_seconds, plan.extra_amounts ) - money_without = failures_without_pv - precision = half_with + half_without + plan.error + cost_without = each * fails_without + + precision = plan.error + if discount is None or discount == 0.0 or ends[-1] <= 0.0: + money_with, money_without = cost_with, cost_without + money_task = task_cost + else: + + def side(expected): + def costs(model_ends: np.ndarray) -> np.ndarray: + return each * np.diff(expected(model_ends), prepend=0.0) + + accrued, _, half = _accrued_npv( + usage, seconds, unit, discount, npv_tolerance, costs, notes + ) + return accrued, half + + def at_instants(at_seconds, amounts) -> np.ndarray: + factors = _discount.factor( + discount, at_seconds / _YEAR_SECONDS + ) + return by_period(at_seconds, np.atleast_1d(amounts * factors)) + + failures_with_pv, half_with = side(plan.with_events) + failures_without_pv, half_without = side(plan.without_events) + money_task = at_instants(done_s, price) + money_with = failures_with_pv + money_task + if plan.extra_seconds.size: + money_with = money_with + at_instants( + plan.extra_seconds, plan.extra_amounts + ) + money_without = failures_without_pv + precision = half_with + half_without + plan.error value = money_without - money_with if discount is not None: years = float(seconds[-1]) / _YEAR_SECONDS @@ -742,7 +953,17 @@ def at_instants(at_seconds, amounts) -> np.ndarray: "The device's failed time is worked out on a grid, to within " f"{plan.error:.3g} of the costs in all (in the precision)." ) - if discount is not None: + if discount is not None and isinstance(does, Services): + notes.append( + f"{_discount.words(given, usage.start, escalation)} The " + "service's cost is discounted from when it is done" + + ( + "; each run's costs from when they fell." + if sim is not None + else "." + ) + ) + elif discount is not None: notes.append( f"{_discount.words(given, usage.start, escalation)} A failure's " "expected " @@ -750,6 +971,9 @@ def at_instants(at_seconds, amounts) -> np.ndarray: f"side to within its bracket ({precision:.3g} on the value in " "all); the task's cost from when it is done." ) + avoided = fails_without - fails_with + if sim is None and isinstance(does, Services): + avoided = np.zeros(n) # no effect: none avoided total = { "with_task": float(np.sum(money_with)), "without_task": float(np.sum(money_without)), @@ -759,10 +983,21 @@ def at_instants(at_seconds, amounts) -> np.ndarray: "cost_without": float(np.sum(cost_without)), "failures_with": float(np.sum(fails_with)), "failures_without": float(np.sum(fails_without)), - "failures_avoided": float(np.sum(fails_without - fails_with)), + "failures_avoided": float(np.sum(avoided)), "count": len(dates), } - hidden: Dict[str, Optional[np.ndarray]] = {} + hidden: Dict[str, Any] = {} + if sim is not None: + total["value_lower"] = sim.total_lower - total["task_cost"] + total["value_upper"] = sim.total_upper - total["task_cost"] + hidden = { + "method": "simulated", + "value_lower": sim.lower - money_task, + "value_upper": sim.upper - money_task, + "confidence": float(confidence), + "n_simulations": sim.n, + "seed": sim.seed, + } if plan.found is not None: whole = np.array([ends[-1]]) hidden = { @@ -798,7 +1033,7 @@ def at_instants(at_seconds, amounts) -> np.ndarray: cost_without=cost_without, failures_with=fails_with, failures_without=fails_without, - failures_avoided=fails_without - fails_with, + failures_avoided=avoided, total=total, precision=float(precision), eac=eac, diff --git a/repyability/tests/test_schedule_services.py b/repyability/tests/test_schedule_services.py new file mode 100644 index 0000000..c18d920 --- /dev/null +++ b/repyability/tests/test_schedule_services.py @@ -0,0 +1,195 @@ +"""The value of a service on dates (UC-67 of the schedule README): +``task_value(task, Services(plan, effect=), usage)``.""" + +import numpy as np +import pytest +import surpyval as surv + +from repyability import NonRepairable +from repyability.maintenance import ( + AgePolicy, + ImperfectRepair, + Prices, + Restoration, + UnitPlan, +) +from repyability.schedule import ( + Condition, + DutyPlan, + Recurrence, + Replaces, + Services, + Shifts, + Task, + UsageForecast, + task_value, +) + +LIFE = surv.Weibull.from_params([8760.0, 3.0]) +PLAN = UnitPlan(LIFE, "instant", prices=Prices(repair=12000.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") +#: The z of the default 90% two-sided interval. +Z90 = 1.6448536269514722 + + +def value(effect=None, plan=PLAN, **kwargs): + kwargs.setdefault("age", 4000.0) + kwargs.setdefault("discount", 0.07) + kwargs.setdefault("period", "quarter") + return task_value(SERVICE, Services(plan, effect), USAGE, **kwargs) + + +def standard_error(worth) -> float: + total = worth.total + return (total["value_upper"] - total["value_lower"]) / (2.0 * Z90) + + +def test_uc67_no_effect_is_the_service_cost(): + worth = value() + assert worth.method == "exact" + np.testing.assert_allclose( + worth.value, [0.0, -786.77, -773.62, -760.55], atol=0.005 + ) + assert worth.total["value"] == pytest.approx(-2320.95, abs=0.005) + assert worth.total["without_task"] == 0.0 + assert worth.total["failures_avoided"] == 0.0 + assert np.isnan(worth.total["failures_with"]) + assert worth.value_lower is None and worth.n_simulations is None + assert any("taken as none" in note for note in worth.notes) + plain = value(discount=None) + assert plain.total["value"] == -2400.0 + # The plan is not needed for no effect. + assert task_value( + SERVICE, Services(), USAGE, discount=0.07, period="quarter" + ).total["value"] == pytest.approx(-2320.95, abs=0.005) + + +@pytest.mark.parametrize("model", ["kijima1", "kijima2"]) +def test_a_factor_of_one_is_no_effect_exactly(model): + worth = value(Restoration(q=1.0, model=model)) + assert worth.method == "exact" + np.testing.assert_array_equal(worth.value, value().value) + + +def test_as_new_matches_block_replacement_on_the_dates(): + part = NonRepairable(LIFE, unplanned_cost=12000.0) + exact = task_value( + SERVICE, + Replaces(part), + USAGE, + age=4000.0, + discount=0.07, + period="quarter", + ) + # Replaces counts the task as the planned replacement at 800 too. + worth = value(Restoration(q=0.0), seed=67) + assert worth.method == "simulated" + se = standard_error(worth) + assert abs(worth.total["value"] - exact.total["value"]) < 4 * se + assert ( + abs(worth.total["failures_with"] - exact.total["failures_with"]) < 0.05 + ) + # Common random numbers: before the first service both sides match. + assert worth.value[0] == 0.0 + + +def test_as_new_with_minimal_repairs_against_the_overhaul_closed_form(): + minimal = UnitPlan( + LIFE, + "instant", + prices=Prices(repair=12000.0), + imperfect_repair=ImperfectRepair(model="kijima1", q=1.0), + ) + worth = value(Restoration(q=0.0), plan=minimal, age=0.0, discount=None) + hours = np.array([0.0, 2160.0, 4344.0, 6552.0, 8760.0]) + + def H(t): + return (np.asarray(t) / 8760.0) ** 3 + + with_service = float(np.sum(H(np.diff(hours)))) + expected = 12000.0 * (H(8760.0) - with_service) - 2400.0 + assert abs(worth.total["value"] - expected) < 4 * standard_error(worth) + + +def test_seeded_runs_repeat_and_narrow_with_more_runs(): + effect = Restoration(q=0.6) + one = value(effect, seed=5, mc_samples=1000) + again = value(effect, seed=5, mc_samples=1000) + np.testing.assert_array_equal(one.value, again.value) + assert one.seed == 5 and one.n_simulations == 1000 + more = value(effect, seed=5, mc_samples=4000) + assert standard_error(more) < standard_error(one) + + +def test_the_value_falls_as_the_factor_rises(): + worths = [value(Restoration(q=q), seed=11) for q in (0.0, 0.6, 1.2)] + for better, worse in zip(worths, worths[1:]): + assert better.total["value_lower"] > worse.total["value_upper"] + assert worths[-1].total["value"] < -2320.95 # a service that does harm + + +def test_a_constant_rate_gains_nothing_at_any_factor(): + plan = UnitPlan( + surv.Exponential.from_params([1 / 8760.0]), + "instant", + prices=Prices(repair=12000.0), + ) + for q in (0.0, 0.5): + worth = value(Restoration(q=q), plan=plan, seed=3) + assert abs(worth.total["value"] + 2320.95) < 4 * standard_error(worth) + + +@pytest.fixture(scope="module") +def serviced_life(): + """A proportional hazards Weibull fitted with a load covariate: + lives about 6,000 h at 1 and a quarter of that at 2.""" + rng = np.random.default_rng(7) + load = np.repeat([1.0, 2.0], 40) + x = 6000.0 * rng.weibull(1.5, load.size) / load**2 + return surv.WeibullPH.fit(x, Z=load[:, None]) + + +def test_a_fitted_condition_follows_its_covariate(serviced_life): + helps = Condition(serviced_life, fresh=[1.0], stale=[2.0], lasts=2000.0) + harms = Condition(serviced_life, fresh=[2.0], stale=[1.0], lasts=2000.0) + good = value(helps, age=0.0, seed=2) + bad = value(harms, age=0.0, seed=2) + assert good.method == bad.method == "simulated" + assert good.total["value_lower"] > 0.0 + assert bad.total["value_upper"] < -2320.95 + + +def test_a_condition_schedule_merges_overlapping_services(serviced_life): + effect = Condition(serviced_life, fresh=[1.0], stale=[2.0], lasts=10.0) + schedule = effect.schedule(np.array([0.0, 5.0, 30.0])) + np.testing.assert_array_equal(schedule.edges[:-1], [0.0, 15.0, 30.0, 40.0]) + np.testing.assert_array_equal(schedule.Z.ravel(), [1.0, 2.0, 1.0, 2.0]) + + +def test_refusals(serviced_life): + with pytest.raises(TypeError, match="effect must say what a service"): + Services(PLAN, effect=0.5) + with pytest.raises(ValueError, match="needs the unit's plan"): + Services(effect=Restoration(q=0.5)) + with pytest.raises(TypeError, match="UnitPlan"): + Services({"reliability": LIFE}, Restoration(q=0.5)) + held = UnitPlan(LIFE, "instant", tasks=(AgePolicy(interval=4000.0),)) + with pytest.raises(ValueError, match="without it"): + Services(held, Restoration(q=0.5)) + free = Task("service", every=Recurrence.every(3, "months", "2027-04-01")) + with pytest.raises(ValueError, match="what one service costs"): + task_value(free, Services(), USAGE) + with pytest.raises(ValueError, match="same covariates"): + Condition(serviced_life, fresh=[1.0], stale=[2.0, 0.0], lasts=1.0) + with pytest.raises(ValueError, match="lasts"): + Condition(serviced_life, fresh=[1.0], stale=[2.0], lasts=0.0) + shifts = DutyPlan(Shifts("Mon-Fri", "06:00", "22:00")).forecast( + "2027-01-01", "2028-01-01" + ) + with pytest.raises(NotImplementedError, match="virtual age"): + task_value(SERVICE, Services(PLAN, Restoration(q=0.5)), shifts, seed=1)