diff --git a/CHANGELOG.md b/CHANGELOG.md index a4c8c47f..45c69335 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,971 @@ release between minors that only adds (0.19.1). ## [Unreleased] +## [0.20] - 2026-11-22 + +Money over time and site shutdowns. Net present values are exact by +default, refused where they can't be and worked out to a `horizon=` on +request. They cover a unit's plan valued alone (`UnitPlan`), upgrades, +retirement and salvage, value schedules and escalation, and the spread +of a plan's value with contract payoffs. Schedule forecasts discount +each cost from when it is expected to fall. A site's `Opportunities` +are one record for its parts' policies and its diagram. The release +also adds repair crews that cost something, a call-out crew, shocks at +a rate of their own, and the best time to switch a whole diagram from +one way of running to another. + +The minimum surpyval is 0.29. Some numbers change on purpose; each is +marked "intentional" under Changed. 0.20 deprecates a price on an +opportunity, the `Calendar` names and `method="auto"` sampling a long +calendar, all refused from 0.21. It removes nothing. + +### Added + +- Added: `allocate_redundancy` and `redundancy_front` take + `start_probability` (a number, or a dict by node) for cold standby: a + spare that fails to start is skipped, and the next one is tried, as a + `StandbyModel`'s `start_probability` and a standby block's mean. Each + cold design is scored as the `StandbyModel` it fits, so with two or + more spares the reliability the search reports is the diagram's once + the design is applied (with `switching_probability`, a failed switch + ends the arrangement, which is lower). Giving both is refused. +- Added: `npv_distribution` and `compare_npv` take a unit's own + `retire_at` and `salvage` (a `UnitPlan`'s, or a component spec's), + which they refused: the runs end at the retirement, and each run is + 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. + 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 + (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 + cost with `measure="cost"`) under a limit at `level` (95% by default), + counting all system downtime or `downtime="unplanned"`. A design meets + the limit when an upper confidence bound on the downtime's quantile + (an order statistic, exact) or tail mean (`objective="cvar"`, + normal) is under it. Levers: `redundancy` (copies at a price each) and + `intervals` (a preventive interval's candidates), searched greedily on + common random numbers, with no bound on spend unless `budget=`. The + result has the frontier of spend against the bad run's downtime, each + design's planned and unplanned downtime (mean and bad run, hours and + cost), and, when the limit is not met, the floor that stopped the + levers. The risk measures are in `repyability.value._risk`. + `AvailabilityResult.unplanned_downtimes` gives each run's unplanned + downtime, which both engines already worked out. No existing result + changes. +- 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 + member with probability `p`; a strike fails the members it names that + are up, in the group's order, each then repaired on its own, and a + tested member's failure waits for its test. The simulations run it (in + Python; the compiled engine hands a diagram with groups over, as + before), and every exact and numerical method refuses, naming the + simulation, as do a member's own long-run availability + (`node_availability`) and its exact spares (`spares_demand`, + `spares_stock`), which its own life no longer gives; + `spares_demand(method="simulate")` counts them. For exponential + members a seeded run is the equivalent rate-split group's, strike for + strike, as the shocks' causes take the shared causes' streams; no + existing seeded result changes. Scheduled maintenance, imperfect + repair or a maintenance group on a member, and a tested member started + from a state, are refused by name. The group's `rate`, `p` and + `lethal_rate` are levers (`ccf_rate`, `ccf_p`, `ccf_lethal_rate`). + +- Added: a `NonRepairableRBD` as a unit's life (UC-66 of the + maintenance README): a subassembly replaced whole at its failure, + taken wherever a life is (`UnitPlan`, a spec's `"reliability"`, + `NonRepairable`) by its functions, exact where the routes are and + simulated from the streams as any model's draws. `NonRepairableRBD.qf` + inverts its `ff` to near machine precision in both tails. + +- Added: a unit's plan valued alone (UC-65 of the maintenance README). + `UnitPlan` has `expected_npv`, `cash_flows`, `npv_distribution`, + `plan_vs_actual`, `expected_cost`, `expected_cost_rate`, + `events_by_period`, `failures_by_period`, + `optimal_replacement_interval`, `optimal_inspection_interval` and + `analysis_routes`, each the method of its one-node diagram + (`UnitPlan.diagram()`, the node `"unit"`), on a + `schedule.CalendarContext` given as `calendar=`. A plan holds the + unit's own money: `salvage` (a number or a function of age), + `escalation` (a growth rate for its prices) and `retire_at`, which are + also component spec keys; `expected_npv` takes them as its arguments + of the same names for the node (the arguments still work, and win). + A unit's retirement in a diagram of several, and a unit's salvage or + retirement in `npv_distribution`, `compare_npv`, `best_switch_time` + and `plan_vs_actual`, are refused, saying what to use. + +- Added: the long run of a diagram with an upgrade (UC-64 of the + maintenance README): `mean_availability`, `expected_cost_rate`, + `node_availability`, the importance measures (by default, in the long + run), `replacement_cycle` and the other long-run methods give the + values once upgraded, those of the diagram built with each upgraded + component's new life (its block replacement kept, the time before the + upgrade and its capital cost ignored), where they refused. Asked over + time, the measures follow the upgrade as before; `total_cost` still + refuses, its horizon starting before the upgrade. + +- Added: a block kept unless it is due (`"older_than"`, or on + condition with a threshold) at a shutdown's given times, valued + without simulation. Over a horizon, `point_availability`, + `mission_availability`, `expected_events`, `expected_cost`, + `expected_npv` and the windows follow the condition recursion stretch + by stretch, from new or from a state; the units kept at an outage are + moved onto the next stretch's grid of ages keeping their mass and mean + age. Equally spaced times give the shutdown on that period's values. + A block tested at given times stays simulated, and the exact methods + say so. + +- Added: each unit's own duty plan on the calendar (UC-64 of the + schedule README). A block's `"duty"` takes a `DutySchedule` (the + shares of the time it runs over the diagram's clock, from + `UsageForecast.schedule()`) as well as one share: its life is drawn in + operating hours and put on the calendar through the plan (a unit put + in at `t0` fails when the plan has run its life on from `t0`), and a + `"preventive"` task counted in operating time (`"basis": + "operating"`) falls when the plan reaches it. Such a block is + simulated (the Python engine; the exact methods refuse it, saying + why), and `cost_by_window` then takes each window's mean from the + simulations, as it does for a covariate schedule. + `schedule.CalendarContext(usage, duty={node: forecast or share}, + unit=)` is the calendar an analysis runs on: `events_by_period` takes + it, giving each unit its plan (counting the events in the + simulations' histories, and discounting each simulated cost from when + it falls, where a plan changes), and `rule_times` gives a recurrence + rule's dates on the diagram's clock for a task's `"replace_at"`. + +- Added: `UnitPlan`, one unit's maintenance plan (UC-63 of the + maintenance README): its life and repair models, its tasks (`AgePolicy`, + `BlockPolicy`, `ConditionPolicy`, `CalendarReplacement`, `AtShutdown`, + `Inspection`, `Upgrade`, with a `Restoration` for a task that restores + partly), its imperfect repairs (`ImperfectRepair`) and its `Prices`, + each task in its own clock, as frozen plain data that saves + (`to_dict`, `from_dict`). A `RepairableRBD` node takes a plan as it + takes the spec dict, which is the plan's shorthand + (`UnitPlan.from_spec`, `plan.spec()`); `RepairableRBD.plans` reads + each spec node back as a plan. A node given a plan is the node given + its spec: no result changes. (The name `MaintenancePlan` stays the + result of choosing intervals.) + +- Added: a value schedule and escalation in the simulated NPV and in + a plan against what happened (UC-57 of the maintenance README, part + 2). `npv_distribution`, `compare_npv` and `plan_vs_actual` take + `value_rate` as a `ValueSchedule` and `escalation=`, `rates=` and + `inflation=` as `expected_npv` does; `best_switch_time` takes + `escalation=`, `rates=` and `inflation=`. Each cost in a run or a log + is charged at its price grown to when it fell, each up span earns + each step's rate over its part of it, grown, and each is discounted + exactly. `plan_vs_actual` values the plan with `expected_npv` on the + same arguments, and the rest from now with the schedule's steps from + then, each stream grown to now. The results state the basis + (`rate_basis`, `inflation`, `escalation`, `value_schedule`). With a + number and no growth every value is unchanged. + +- Added: `Shocks(rate, p, lethal_rate)`, shocks at a rate of their own + as a common-cause group's model: `CCFGroup(members, Shocks(...))`. A + `NonRepairableRBD` writes the group's causes into its structure as + `shock_nodes` does (the same nodes and the same values, to the last + bit), so the members keep their own lives and ages and every analysis + takes the shocks; the diagram is saved with the group as given. A + fault tree refuses the model, saying what to draw instead. + +- Added: maintenance that does harm (UC-62 of the maintenance README). + A `"preventive"` spec's `"restoration"` takes a restoration factor `q` + above 1, a task that leaves the unit older than it was (Kijima II with + `q = 1.1` takes the virtual age to `1.1 (v + x)`), where it was held + to [0, 1]; the lever `preventive.restoration.q` ranges from 0 up. A + repair's `q` stays in [0, 1], and its refusal now says only a task's + may be above 1. `q = 1` gives the failures of no service; with + `compare_npv` against the plan without the task, a plan shows whether + a task is worth stopping. Simulated as any restoration (in Python). + +- Added: `shock_nodes(edges, nodes, members, rate, p, lethal_rate)`, + shocks that fail each member they reach with a probability (the + binomial failure rate model), for a `NonRepairableRBD` whose members + have any lives, each its own, at their own ages. Shocks at a constant + rate that fail each of `m` members independently with probability `p` + are an independent cause for each set of members, at rate `rate p^j + (1 - p)^(m - j)` for a set of `j`; the function writes each into the + diagram as an exponential node after every member it fails (one + component in several places), so every analysis takes them as it + takes any repeated node: the reliability, MTTF, B-lives and importance + exactly, given each member's age too, and the simulations. For + exponential members the values are the alpha-factor group's by rate + (to 1e-12). In the guide: "Common causes with wear-out lives and + ages". + +- Added: common causes for members that wear out and have aged. The + condition-based methods (`sf_given_state`, `remaining_life`, + `mean_residual_life`, `importances_given_state`) take a common-cause + group that splits the failure rate (`basis="rate"`) when its members + are given one state (alive, at one age): each cause takes its share of + the members' hazard from that age on, whatever their life. They + refused every group before. Members in different states, a failed + member and a group splitting a probability are refused, saying what to + do. A new guide page, "Common causes with wear-out lives and ages", + shows it beside the model for members of different ages: a shock at + its own rate that fails every member it reaches, drawn as an + exponential node in series with them (a repeated node where they sit + in different branches), with the Weibull and exponential closed forms + of the split as checks. + +- Added: the NPV spread of a diagram with shutdowns (UC-61 of the + maintenance README). `npv_distribution`, `compare_npv` and + `best_switch_time` price the runs of a diagram with shutdowns, where + they refused it: each shut's cost at each of its starts, discounted + exactly; a component held off line by a shut not charged for the + hold; and a failure in the shut, or a renewal made in it (an + opportunistic renewal, a task at the shut), charged as anywhere else. + The Python loop's histories mark each hold and record the changes a + hold hid (for pricing; `simulate_timelines`' timelines are unchanged). + +- Added: `value_plan(spec)`, an NPV question asked and answered as JSON + documents. The request names a diagram (`to_dict()`), the analysis + (`expected_npv`, `expected_npv_uncertainty`, `npv_distribution`, + `compare_npv`, `plan_vs_actual`) and its inputs by name in plain data + (states, timelines, a `ValueSchedule`, escalation, real rates, + salvage, retirement); the answer is strict JSON with the request, the + units, the route and the result, or the refusal and every NPV + analysis's route. Valuing the echoed request gives the same answer (a + seed is drawn and recorded for a seeded analysis given none). + `npv_schema()` gives the documents' JSON Schema + (`repyability/schemas/npv-1.json`). + +- Added: block replacement on an upgraded component (UC-60 of the + maintenance README). A component with an `"upgrade"` may have a + `"preventive"` of `"policy": "block"` on its own interval: it is + replaced every interval with the life in service, and at the + upgrade's time as at a block time (at its cost and in its time, + beside the capital cost). Numerical over a horizon and simulated; + other tasks with an upgrade are still refused, now saying block + replacement is taken. + +- Added: an upgraded component is simulated (UC-52 of the maintenance + README). `availability`, `cost`, `simulate_timelines`, + `npv_distribution` and `compare_npv` take a component's `"upgrade"`: + a life that starts at or after the upgrade's time is the upgrade's, + drawn from the same random number the old life would have taken, so + an upgrade to the same life at no cost is a replacement at its time, + run for run, and `compare_npv` against keeping the old life matches + the runs. The capital cost is charged at its time in every run that + reaches it. In Python (the compiled engine leaves an upgrade to it); + the long run, the spares counts and `plan_vs_actual` still refuse. + Seeded results of diagrams without an upgrade are unchanged. + +- Added: a part renewed at several shutdowns (UC-59 of the maintenance + README). A `"preventive"` spec's `"shutdown"` takes a list of the + diagram's shutdowns: the part is renewed at every start of each, each + renewal taking its own shut's length. Exact over a horizon + (`point_availability`, `mission_availability`, `expected_events`, + `expected_cost`, `expected_npv`, the windows), followed stretch by + stretch between the merged starts; simulated in Python. The long-run + methods and a long-run or in-maintenance state refuse it, and two of + its shutdowns may not start together. A list of one name is that + shutdown. Saved with the diagram. + +- Added: a task that leaves a part as if a given age (UC-58 of the + maintenance README): a `"preventive"` spec's `"restore_to"`, at a + shutdown or on the part's own calendar, sets its virtual age to that + age whatever it was, its next life drawn given it. Simulated, as a + Kijima `"restoration"` is (one or the other); `restore_to=0` is a + renewal, exact where renewals are. Saved with the diagram. + +- Added: value and prices over time in a net present value (UC-57 of + the maintenance README). `expected_npv` takes `value_rate` as a + `ValueSchedule(times, rates)` of steps in model time; `escalation=` + a growth rate per unit time for any cost category, component, + `"value"` or `"salvage"` (an amount at `t` is its price times + `exp(g t)`; a growth above the discount rate is valid over a + horizon); and `rates="real"` with `inflation=` to value in real terms + (every amount made nominal, which leaves the present values as they + are). `ExpectedNPV` states `rate_basis`, `inflation`, `escalation` + and `value_schedule`; with no schedule or growth every value is as + before. On dates, `Task.due`, `Task.long_run_value`, + `work_by_period`, `failures_by_period`, `events_by_period` and + `task_value` take `escalation=` (a yearly rate) beside `discount=`: + the present values take each cost grown to when it falls. + `npv_distribution` and `plan_vs_actual` refuse a `ValueSchedule`, + naming `expected_npv`. + +- Added: opportunistic work at a planned outage (UC-56 of the + maintenance README). A shutdown takes `"opportunistic": {node: age}` + (or one age for every block in its scope under age replacement): at + each shut, such a block that is working and at least that old is + renewed as its own age replacement renews it, and its next + replacement counts from then. Simulated, in Python: `availability()` + gives the expected count renewed at each shut with a 95% interval + (`AvailabilityResult.outage_jobs`) and each block's total + (`opportunistic_renewals`); the renewals are charged as preventive + work. The exact methods refuse it, naming `availability()` and + `cost()`; an age of `inf` is the plan without the rule. Saved with + the diagram. + +- Added: how sure an NPV and a choice of intervals are (UC-55 of the + maintenance README). `expected_npv(rate_sensitivity=True)` gives the + NPV's derivative in the discount rate, with an estimate of its error + (`ExpectedNPV.rate_sensitivity` and `rate_sensitivity_error`). + `RepairableRBD.expected_npv_uncertainty(horizon, uncertainty, ...)` + values the plan over draws of the fitted models, as the other + uncertainty methods draw them, in an `NPVUncertainty`: each draw's + NPV, its intervals, each input's share of the variance (the delta + method) and the models held fixed. `optimal_replacement_intervals` + takes `robust=True` (the choice against its neighbours under each + draw) or `robust="reoptimise"` (against each draw's own best), with + `uncertainty=`, `n_draws=` and `seed=`, and gives the plan a + `PlanRobustness`: the share of draws in which the choice stays the + best, and its expected regret. + +- Added: what a test of a hidden failure is worth (UC-53 of the + maintenance README and UC-54 of the schedule's). + `failure_finding_window(device, test_times, window, age=, test_cost=, + repair_cost=, demand_rate=, consequence_cost=, discount_rate=)` is + `failure_finding` over a window in model time: a protective device + tested at any list of times (none for "never tested"), from its age, + giving the chance each test finds it failed, the time it is failed, + the demands that meet it failed, the unavailability over time, and the + plan's cost and present value, in a `FailureFindingWindow`. A demand + that meets the device failed shows the failure, which is repaired + then (`demands_reveal=False` for `failure_finding`'s convention, whose + long-run numbers even tests over a long window then give). Exact at + the tests where only a test finds a failure, numerical where a demand + shows it, to the `precision` given. On dates, + `repyability.schedule.task_value` takes `Finds(device, demand_rate=, + consequence_cost=, repair_cost=)` for a task that tests the device: + the tests' cost, the repairs and the demands that meet the device + failed, against never testing it, by calendar period and as present + values with `discount=`. `TaskValue` gains `found`, + `unavailability_with` and `unavailability_without` (None for + `Replaces`, whose values are as before). + +- Added: mid-life upgrades, retirement and salvage in a net present + value (UC-52 of the maintenance README). A component spec takes + `"upgrade": {"at": time, "reliability": new_life, "cost": capital}`: + from that time its units have the new life (the unit in service is + replaced by one of it, in no time), and the capital cost is charged + then under a new cost category, `"capital"`. Its values over a horizon + are worked out (`point_availability`, `mission_availability`, + `expected_events`, `expected_cost`, `expected_npv`), from new or from + a state; an upgrade to the same life at no cost is a replacement at + that time. `expected_npv` takes `retire_at=` (nothing is earned or + spent after it; the equivalent annual cost is over the time to it) and + `salvage=` (a number for the system, or a dict by component, credited + at the retirement or the horizon and discounted from there; a + component's may be a function of the age of its unit in service, for a + plain component from new). `ExpectedNPV` gains `salvage`, + `undiscounted_salvage` and `retire_at`, and its cash flows the + categories `"capital"` and `"salvage"`. An upgraded diagram has no + long run and is not simulated yet: those methods refuse, saying what + to run. Every cost breakdown gains a `"capital"` entry of 0; without + an upgrade, a retirement or a salvage every value is as before. + +- Added: outages at given times, valued without simulation (UC-24 of the + maintenance README). A diagram's `shutdowns` at `"times"` (each with + its duration, scope and cost; several shutdowns for different + outages) were simulated only. Over a horizon they are now worked out + where every block worked on in them is renewed (`"preventive": + {"shutdown": name}`): `point_availability`, `mission_availability`, + `expected_events`, `expected_cost`, `expected_npv`, + `expected_events_by_window`, `compare`, `maintenance_effect` over a + window, and a run's default means. A renewed block is replaced at each + outage if it is up, taking the outage's time; the blocks in scope are + held off line in each window; each outage's cost and each job's is + charged and discounted at the outage's start. Outages at a period's + times give the shutdown on that period's values. A job that restores + part-way, a block kept unless due (`"older_than"`, on condition) and a + test at outages at given times stay simulated, and the exact methods + say so. + +- Added: a component replaced at a list of times (UC-51 of the + maintenance README). A `"preventive"` spec takes `"replace_at"`, the + times in the diagram's time from 0 (positive, increasing), in place of + an `"interval"`: block replacement at those times, the unit replaced at + each if it is up, with the task's `"cost"` and `"duration"`, and after + the last no more. Its values over a horizon are numerical, with no + simulation: `point_availability`, `mission_availability`, + `expected_events`, `expected_cost`, `expected_npv` (each replacement + counted and discounted at its exact time) and what is built on them + (`availability_rate`, `compare`, `maintenance_effect`, + `expected_events_by_window`, a run's default means), from new or from a + state (the times counted from now). Equally spaced times give block + replacement's values over the same horizon. The simulations replace at + the times (in Python; a compiled engine leaves a plan to it). Each + time is a lever, `preventive.replace_at.0`, ..., between its + neighbours. A plan ends, so the long-run methods refuse, saying to ask + for a horizon or give an interval; `spares_demand`, `spares_stock` and + `plan_vs_actual` refuse too, saying what to run instead. It is saved + by `to_dict`, and with `"basis": "operating"` its times go onto the + calendar through the block's duty. Without it every value is as + before. + +- Added: redundancy chosen by net present value. + `RepairableRBD.allocate_redundancy(horizon, objective="npv", + discount_rate=, value_rate=)` chooses the copies with the highest net + present value over the horizon: what the system earns while it works + (`value_rate` per unit time, at its long-run availability) less the + copies bought at the start and the running costs, each over the + horizon's present value as `total_cost` counts them. + `objective="eac"` chooses by the equivalent annual cost less the value + earned, which over one horizon is the same design. The + `TotalCostAllocation` gains `objective`, `value_rate`, `npv`, `eac`, + `value`, `running_cost` (`npv = value - acquisition_cost - + running_cost`) and `basis`, which says what is approximate (a system + new at the start is up more often at first; `expected_npv` values a + design from new). A value earned is a cost of downtime, so the search + and its bounds are the total cost's with an hour down costing + `downtime_cost_rate + value_rate`: `min_availability`, `max_units`, + `trains`, common-cause groups and both methods work as before, and + with no value the design and its total cost are exactly the total + cost's. `objective="cost"`, the default, is unchanged; a `value_rate` + with it is refused, naming the objectives. + +- Added: test intervals chosen at a discount rate. + `RepairableRBD.optimal_inspection_intervals` takes the objectives of + `optimal_replacement_intervals`: `objective="eac"` (with + `discount_rate=` and `value_rate=`) for the lowest equivalent annual + cost in the long run, and `objective="npv"` with a `horizon` for the + highest `expected_npv`, with `allowed`, `offset_shares`, + `min_availability` (a PFDavg limit) and `max_cost_rate` as before. A + component with hidden failures, tested and repaired in no time by + tests that find every failure, is discounted over its own cycle, the + tests up to the one that finds it failed: each test when it is made, + the failure when it is found, its own downtime from the failure to + that test (for an exponential life a closed form, which the tests + check; the first cycle from the tests' offset). So such a component is + no longer refused by `optimal_replacement_intervals(objective="eac")` + either. Tests or repairs that take time, and tests that can miss a + failure, refuse `"eac"` at a discount rate and name `"npv"`. At a rate + of 0 the plan is the cost rate's. + +- Added: what a scheduled replacement is worth against running to failure, + on real dates (UC-50 of `repyability/schedule/README.md`). + `task_value(task, Replaces(part), usage, *, age=0.0, unit=None, + discount=None, period="month", npv_tolerance=1e-3)` takes the task's + dates from `Task.due` (by the calendar, or by use when the meter reaches + its reading), fits a new part at each whatever its age (a failure in + between is replaced too and does not move the dates), and compares it + with the part run to failure from the same age over the same dates. It + returns `TaskValue`: by period and in total, the cost with the task, + without it, and `value` (without less with: positive when the task + pays), the task's own cost, the expected failures each way and those + avoided, with the undiscounted costs beside; with `discount=` the money + is a present value (each failure's cost discounted as + `failures_by_period` discounts it, to within `precision`; the task's + cost from when it is done) with each side's `eac`. The expected failures + are `NonRepairable.failures`' over the stretches between the task's + dates. The task's `cost` is the planned replacement's price, else the + part's `planned_cost`; two different prices are refused, naming both. A + new ring at every 6-monthly service on UC-38's pump saves $1,436.74 over + the year (0.549 failures avoided), $1,366 at 7% a year. `Replaces` is + the only kind of task valued so far: anything else is refused with what + to run. +- Added: replacement intervals chosen at a discount rate. + `RepairableRBD.optimal_replacement_intervals(objective="eac", + discount_rate=, value_rate=)` chooses the age-replacement intervals for + the lowest equivalent annual cost in the long run, less a value earned + per unit time while the system works: each component's own costs + discounted over its renewal cycle, exactly (Fox, 1966; one unit's plan + is `NonRepairable.optimal_replacement_policy(discount_rate=)`'s), the + cost of the system's downtime and the value at its long-run + availability, an approximation the plan states. `objective="npv"` with + a `horizon` chooses them for the highest `expected_npv` from new: every + combination of `allowed` valued, or a local search (without gradients) + from the long run's best plan; much slower, as each plan's curves are + followed over the horizon. `min_availability` and `max_cost_rate` are + kept with both. The `MaintenancePlan` says what was minimised + (`objective`, `discount_rate`, `value_rate`, `horizon`), what it came + to (`objective_value`) and what that is made of (`basis`). At a rate + of 0, `"eac"` is the cost rate: the same search and the same plan. A + priced component with no renewal cycle of its own worked out (a tested + unit, a standby group, block replacement, a common-cause group, ...) + refuses `"eac"` at a discount rate, naming `"npv"`. The default, + `objective="cost"`, is unchanged. + +- Added: present values on the calendar forecasts + (`repyability.schedule`; UC-47 to UC-49 of its README). `discount=` is + the effective yearly rate (0.07 for 7% a year, a year of 365.25 days), + as on the dated replacement policies, and money is discounted to the + forecast's first date. `Task.due(start, end, discount=)` adds `npv` + (each cost discounted from the date the task is done) and `eac`, the + equivalent annual cost; `work_by_period(..., discount=)` adds each + period's `npv`, `total_npv` and `eac`. `Task.long_run_value(start, + discount, precision=1e-9)` is what a task repeating for ever is worth, + returning a `LongRunValue`: a closed form for a plain interval of days + or weeks, otherwise the dates summed until a bound on what is left is + under `precision`; refused, saying what to run, at a discount of 0, + for given dates and for a limit by use. $250 every 30 days at 7% is 13 + tasks and $3,144.10 in the first year, and $45,112 for ever. + `failures_by_period(..., discount=, npv_tolerance=1e-3)` adds each + period's `expected_npv`, with `npv`, `npv_precision` and `eac`: the + expected cost of short windows discounted at each window's start and + end, which bracket the true value (the middle is given, half the + bracket is the precision); the ranges stay undiscounted. + `events_by_period(..., cost=True, discount=)` adds each period's + `expected_npv`, with `npv` and `eac`, exact + (`RepairableRBD.expected_cost` with its `discount_rate`). With no + `discount` every result is as before, with the new fields None. + +- Added: redundancy allocation with limited repair crews. + `allocate_redundancy` on a diagram whose components can wait for a + repair crew (exponential lives and repairs) no longer refuses: a copy + is one more job for the crews, so each design is worked out whole, from + the crews' Markov chain of its components and their copies (a call-out + crew and the crews' salaries counted), which counts how many of a + component's alike copies are up rather than telling them apart, so a + design with several copies stays small. The search keeps to the two + bounds that still hold with crews (no design is down less than with a + crew for every job; every copy is bought): `method="exact"` starts + from the greedy design and solves the designs that could still beat + it, the most promising first; `"greedy"` takes single steps. The + result's `basis` says the designs came from the crews' chain. A design + the search needs whose chain has more than 15,000 states is refused by + name, as are whole trains, common-cause groups, maintenance groups and + shutdowns with crews, each naming `compare()`; a node whose copies + cost nothing to buy needs a `max_units`. The number of crews is not + chosen by the search. `availability_allocation` and + `mttf_mttr_allocation` still refuse with crews, now naming + `allocate_redundancy`. With a crew for every component the results + are as before. + +- Added: common-cause groups in the repair crews' Markov chain. With + limited `repair_crews` and `ccf_groups` whose members have exponential + lives and repairs, the long-run values (`mean_availability`, + `node_availability`, `system_failure_frequency` and the times from it, + `expected_cost_rate`, `capacity_distribution`), the importance measures + and the values over time (`point_availability`, + `mission_availability`, `expected_events`, `expected_cost`, + `availability_rate`) are exact or numerical, where they refused: a + shared cause strikes at its rate and fails the members it names that + are up, which join the crews' queue one after another in the group's + order, as the simulation's do (the first named takes a free crew, + whatever the priorities, which order the jobs that wait). A member + fails on its own at its own cause's rate. The failures a shared cause + makes are reported under the tuple of the group's members, as without + crews (`barlow_proschan_importance`, `availability_rate`). A member + held working or broken is struck no more, and the causes it shares + still strike the others. The chain takes causes that strike two + members: a group of two, or a larger `AlphaFactor` or `MGL` group + whose causes of three or more have no share. A cause that strikes + three or more keeps refusing, naming the simulation, as the simulation + queues components struck at one instant in the order its event queue + releases them, which is the group's order only for two; so do members + repaired instantly or found by tests. No simulated result changes. + +- Added: a call-out crew. `RepairableRBD(..., repair_crews=n, + call_out={"when_waiting": k, "fee": f, "rate": c})` adds one crew that + comes only when jobs queue: when a job falls due, finds every crew busy + and is the `k`-th waiting, it comes at once and starts the waiting job + the next free crew would have taken; it leaves at the first end of a + job that leaves a crew with no waiting job to take (the crews are + alike, so the job it has then is finished by the crew that came free), + and jobs that wait while it is engaged call no other. Each call-out + costs `f` and its time engaged `c` per unit time, under the `"crews"` + category. With exponential lives and repairs the crews' Markov chain + has it exactly: the long-run values (`mean_availability`, + `expected_cost_rate`, the importance measures), those over time + (`point_availability`, `expected_events`, `expected_cost`), the + discounted ones (`expected_cost(discount_rate=)`, `expected_npv`) and + the first failure, so the difference from the same diagram without + `call_out` is what the contract is worth. `crew_states()` adds + `call_out_rate` and `call_out_engaged`, the rate of call-outs and + whether the crew is engaged in each state. The simulations follow the + same rule in the Python event loop (the compiled engine hands such a + diagram to it); `npv_distribution` and `compare_npv` refuse a priced + call-out crew, whose call-outs the histories do not record, naming + `expected_npv` and `cost()`. It needs `repair_crews`, does nothing + where no job can wait, and is saved when given. Without it every value + is as before. + +- Added: repair crews that cost something. `RepairableRBD(..., + repair_crews=n, crew_cost_rate=c)` pays each of the `n` crews `c` per + unit time, busy or not, so a crew more is a trade-off rather than free. + Every cost result has the crews' cost under the new category + `"crews"`: `expected_cost_rate` adds `n c`; `total_cost`, + `expected_cost` and `expected_npv` (and its cash-flow table, by + period) add `n c T` over a window `T`, or `n c (1 - exp(-r T)) / r` + discounted at `r`; the simulations (`availability`, `cost`, + `cost_by_window`, `compare`, `npv_distribution`, `plan_vs_actual`'s + actual side) add the same amount to every run, after it, on every + engine. The interval choices with `assume_unlimited_crews=True` and + `allocate_redundancy` keep the crews' cost in the cost rate they + report and in a `max_cost_rate`, and the crew count lever moves it. + `crew_cost_rate` without `repair_crews` is refused (as many crews as + are needed cannot be priced); it is saved by `to_dict` when given. + Without it every value is as before; the cost breakdowns gain a + `"crews"` entry of 0. + +- Added: the best time to switch a whole diagram from one way of running + to another (UC-20 of the maintenance README, which was built for one + unit). `RepairableRBD.best_switch_time(covariates, value_rates, + horizon, *, discount_rate=0, mc_samples=1000, seed=None, scan=11, + engine="auto", state=None)` takes, for each block on a covariate + schedule that switches, its covariates before and after the switch, + and what the system earns per unit of time up before and after. Each + candidate switch time is the diagram with those schedules, simulated + from one seed (common random numbers) and priced as `npv_distribution` + prices its runs; the horizon is scanned and the best refined. It + returns `SimulatedSwitchTime`: the switch time and choice, the NPVs of + never switching and of switching at once, each one's runs, the scan, + and `difference_interval(against, confidence)` on the gain. For one + block it agrees with the numerical one-unit `best_switch_time`. + `analysis_routes()` lists it (simulated; refused when no block runs on + a covariate schedule). + +- Added: contract payoffs and two plans compared in the simulated net + present value. `AvailabilityContract(periods, target, + penalty_per_point, bonus_per_point=0.0, cap=None)` states, as plain + data (`to_dict`/`from_dict`), a penalty for each percentage point of + availability below a target in each period and a bonus for each point + above it, at most `cap` a period either way. `npv_distribution(..., + contract=)` pays it run by run, from the share of each period the + system was up in that run, at the period's end; the result keeps it + apart (`contract_samples`, `contract_payoff`, + `undiscounted_contract_payoff`) with each run's availability by period + (`period_availability`, `period_ends`). `RepairableRBD.compare_npv(other, + horizon, ...)` prices both plans' runs from one seed, a component in the + same place in both drawing the same random numbers (as `compare` does), + and returns `NPVComparison`: each run's difference, their mean with a + confidence interval, the chance the other plan is better, the standard + error two independent runs would have had, and both plans' + `NPVDistribution`. Identical plans differ by exactly 0 in every run. + Components whose draws cannot be matched are refused by name. + `analysis_routes()` lists `compare_npv` (simulated). Results without a + contract are unchanged. + +- Added: the spread of a plan's net present value (UC-46 of the + maintenance README). `RepairableRBD.npv_distribution(horizon, *, + discount_rate=0, value_rate=0, mc_samples=10_000, seed=None, + hurdle=None, tail=0.1, engine="auto", state=None)` prices each history + of `simulate_timelines` (the same simulations, by seed, on either + engine) with the diagram's own costs, each discounted at the time it + fell, less the value earned while the system was up, the acquisition + costs paid at the start. It returns `NPVDistribution`: each run's NPV, + value and cost (`samples`, `value_samples`, `cost_samples`), the mean + with `mean_interval()`, the split of value and cost as in + `ExpectedNPV`, `p10`/`p50`/`p90` (`percentile(q)`, order statistics, + and `percentile_interval(q)`, binomial), `probability_below_hurdle` + (and `probability_below(x)`) and `cvar`, the mean of the worst `tail` + of the runs. Its mean agrees with `expected_npv` within its interval; + it also works for diagrams the exact methods refuse, such as crews + with other lives. A cost the histories do not record (a standby + group's units' failures, tests, planned replacements that take no + time, calendar prices, set-up costs, shutdowns, a partial + restoration's replacement) refuses the diagram, naming it; a cost + given as a distribution is charged at its mean (`priced_at_mean`). + `analysis_routes()` lists it (simulated). `plan_vs_actual` prices its + log with the same code, moved to a module of its own; its results are + unchanged. + +- Added: one record of opportunities for every part, the prices on the + part (UC-45 of the maintenance README). `Opportunity` says when a stop + or shut happens (a period or numeric dates in model time; a rule, + dates or `every=` on real dates), how long it lasts (`duration`) and + what it takes down (`takes_down`), with no price; `Opportunities([...], + any_day=True, time_zone=None)` collects them, in model time or on real + dates by what they are (a mix is refused), with `dates`, `on_diagram`, + `route`, `to_dict` and `from_dict` (which also reads a saved + `Shutdowns`). `NonRepairable` takes `opportunity_cost` (at an + opportunity; without one an opportunity is priced as any other day, at + `planned_cost`), `opportunity_costs` (per opportunity, keyed by name or + by the `Opportunity`; a key naming no opportunity of the collection is + refused when the policy runs, listing the names) and `job_duration` (an + opportunity shorter than the job is not used for the part), all saved + with it. `NonRepairable.optimal_opportunity_policy` and + `opportunity_policy_cost` take every keyword the calendar methods took, + and `where=` (only the opportunities that take that label down); the + policy's `prices` (`OpportunityPrices`, in `to_dict` too) give each + opportunity's price and where it came from, and each one not used and + why. `NonRepairable.opportunity_prices(opportunities, *, + replacement_cost, replacement_duration, failure_cost, failure_duration, + downtime_cost)` works the prices out (at a stop the job fits in the + replacement alone; on any day it plus the downtime; at a failure the + failure's cost plus its downtime), and its `apply(part)` gives the part + them. No numerical method changed. + +- Added: a discount rate for the long-run replacement policies (Fox, + 1966). `NonRepairable.find_optimal_replacement(discount_rate=)` and + `optimal_replacement_policy(discount_rate=)` (continuous, per unit of + the life's time) choose the age with the least equivalent annual cost + (EAC), the present value of every replacement forever spread as a + steady cost; `inf` where running to failure is cheaper, which a high + rate can make it. `MaintenancePolicy` gains `discount_rate`, `npv` and + `eac` (defaults 0, `inf` and `cost_rate`); `cost_rate` stays the + undiscounted rate of the age chosen. `optimal_calendar_policy` takes + `discount_rate=` for a `Calendar` (a periodic one of a short cycle, by + discounted value iteration on the grid or by quadrature), and, for a + `Shutdowns` site, `discount=` (yearly) without a horizon: the exact + routes and plain age replacement discounted, and the dated window + discounted to its end with the recurring shuts' discounted long run + after it, where it was valued undiscounted. `CalendarPolicy` and + `ShutdownPolicy` carry the rate, `npv` and the EAC (a site's `cost`, + measure `"equivalent annual cost"`). Sampling, averaged gaps, given + dates in model time, long cycles, duty plans and pricing a given rule + refuse a rate, saying what to give instead. At rate 0 every number is + unchanged. See the maintenance README's UC-44. + +- Added: exact by default, refused where it can't be, and `horizon=` + never refused (the maintainer's decision of 16 Nov 2026, UC-44). + Opportunities in model time take `horizon=` (a time in their own time) + with `discount_rate=` (0 for the plain total), in + `optimal_opportunity_policy` and `opportunity_policy_cost`: a backward + sweep from the horizon over every opportunity as it falls (given dates + as they are, nothing assumed after them), the policy's `npv` the net + present cost to it, `eac` the steady cost a unit of time worth it, and + `basis` `"horizon"`. `opportunity_policy_cost(..., discount_rate=)` in + model time, and `discount=` on a site's exact routes and dated window, + price a given rule's discounted long run exactly (discounted value + iteration with the decisions fixed, on the grid or by quadrature): the + rule the optimiser picks prices at its own EAC, and a site's + `ShutdownPolicy.compare()` prices each simpler rule so (age + replacement at the discounted best age). `ShutdownPolicy` and + `RuleCost` gain `eac` (and `RuleCost` `npv`): a horizon's net present + cost spread over its years, which its words now give too. + `NextReplacement` and `NextReplacementOnDates` gain `discount_rate`. + Every refusal of a discounted long run (a cycle too long to sweep, + given dates in model time, shuts that drift on real dates, a duty + plan, sampling, pricing a rule where nothing repeats) now names a ready + horizon worked out from the inputs: with a discount, where costs are + discounted to under one part in a billion (`horizon='2333-11-16'` at + 7% from 16 Nov 2026; `horizon=112000` days at 7% a year in model + time); with none, the full cycle and three life spans (at most two + million grid steps). + +### Deprecated + +- Deprecated, for removal in 0.21 (each warns with a `FutureWarning` + naming its replacement, and gives the same numbers as before): + `Calendar` and `Shutdowns` for `Opportunities`; `Shutdown` for + `Opportunity`; a price on an opportunity (`Opportunity(name, cost, + ...)`, `cost=`, `Opportunity.from_recurrence(name, cost, ...)`, + `Shutdown(replace_cost=)`, `Shutdowns(any_day=)`, + `Opportunities(any_day=)`), taken as the part's price there, + and `Calendar(failure=, anytime=)`, taken as the failure and any-day + prices; `NonRepairable.optimal_calendar_policy` and + `calendar_policy_cost` for `optimal_opportunity_policy` and + `opportunity_policy_cost`. +- Deprecated, refused from 0.21: `method="auto"` in model time sampling + a periodic calendar whose cycle is too long to sweep. It still samples, + with a `FutureWarning` (it was a `UserWarning`) naming a ready + `horizon=` and `method="sampling"`; from 0.21 it refuses with them + (exact by default, simulation on request). + +### Changed + +- Changed: the minimum surpyval is 0.29. The examples and guides build + the renewal processes with `from_params` (`GeneralizedRenewal`, + `GeneralizedOneRenewal`, `ARA`, `ARI`), the name surpyval 0.29 gives + `fit_from_parameters`, which warns there and goes in surpyval 0.30. + +- Changed: RePyability takes surpyval's `JointModel` and + `SemiParametricRegressionModel` from their subpackages + (`surpyval.univariate.joint`, `surpyval.univariate.regression`), not + its top level, where surpyval 0.29 warns of them. Nothing else + changes. +- Changed: a schedule forecast's present values (`failures_by_period` + and `task_value` with `discount=`) discount each expected cost from + when it is expected to fall, by the diagram's own integral (the + Gauss-Kronrod rule, its pieces halved to `npv_tolerance`), in place + of short windows each discounted at its middle; `npv_precision` (and + `TaskValue.precision`'s share from it) is the integral's error + estimate, plus, run to failure, how far the expected failures (worked + out on a grid, linear between its points) can be from the true ones, + not half a bracket. Values move by about the old + precision's size or less: the README's wear ring (UC-48) is + $2,882.74 to within $0.016, from $2,882.77 give or take $2.47 (each + month by up to $0.02, the EAC $2,869.51 from $2,869.53), and its + run-to-failure cost is worked out from `failures`, about twice as + fast. Diagram results are unchanged to the bit. The private + `bracket` helper is gone. +- Changed: every result made of several runs on one seed draws that seed + the same way when given none: from numpy's global RNG, so + `np.random.seed` makes the call repeatable, as it already did for + `cost_by_window` and a single run. This covers `npv_distribution`, + `compare_npv`, `least_spend_for_downtime`, `best_switch_time`, + `RepairOrReplace.unit_decision(s)` with uncertainty and `value_plan` + requests, which drew it from the operating system's entropy. Seeded + results are unchanged. +- Changed: one definition of the discounted equivalent annual cost of + age replacement, `maintenance._options.cycle_eac` (Fox, 1966, with + every category of a unit's own: its failures' and planned + replacements' prices, and its downtime over repairs and planned work + that take time). `NonRepairable`'s discounted optimum and run to + failure and a diagram component's EAC (`objective="eac"`) both take + it. Nothing changes in value: the old two computed the same + arithmetic, which the shared one keeps. + +- Changed: `value_plan` takes a unit's plan (`UnitPlan.to_dict()`) as + its `"diagram"`, valued as its one-node diagram (`npv-1.json` says + so). + +- Changed: a preventive or inspection task's `"duration"` may be a + plain number, a fixed time (surpyval's `ExactEventTime`), where it had + to be a model or `'instant'`; 0 is `'instant'`. A negative or + non-finite number is refused, naming the task. +- Changed: the `*_uncertainty` methods (and `uncertainty_importance` and + `optimal_replacement_intervals`) keep `n_draws`, the number of draws of + the uncertain models' parameters, each worked out without simulating + it; given `mc_samples=` (which counts simulations) or a name 0.12 + removed, they refuse it naming `n_draws`, where Python said only that + the keyword was unexpected. `FaultTree` refuses the removed names as + the diagrams do. +- Changed: a session's first diagram no longer imports surpyval's joint + and degradation models (with its regression code and pandas) to check + whether a node is one; the first build took about 2 s, later ones + about 1 ms, and now the first takes about 0.05 s. +- Changed: `BetaFactor`'s docstring says first which `basis` to use + (`"probability"`, the default, for a mission or proof-test interval; + `"rate"` for a whole life), and the warning past `Q = 0.1` names the + default basis it is about. +- Changed (docs): the costs guide has a table of which cost is charged + when, and the component spec says `replace_cost` is the replacement on + failure, a planned replacement being charged its `"preventive"` task's + `"cost"`. + +- Changed: a task counted in operating time on a block with no + `"duty"` is no longer refused: the diagram's clock is then the + block's operating time (as a share of 1), until an analysis's + calendar gives the block its plan. Nothing that ran before changes. + +- Changed: a block's `"duty"` (and a life at a usage rate) moves its + life onto the calendar by the model's own `rescale_time` where + surpyval has it (its release after 0.28), so any model that rescales + itself takes a duty, a mixture among them. Values move in the last + bits where surpyval's arithmetic differs from RePyability's own (a + scale times `1 / d` rather than over `d`): exact window counts by + some 6e-15 relative on the diagrams checked. With surpyval 0.28 + nothing changes. + +- Changed: money has one home, `repyability.value`: discounting (one + convention, continuous at a rate per unit time, with a yearly rate + converted to it in one place), escalation and real rates, + `ValueSchedule` (still `repyability.ValueSchedule`), the cost + categories and the cash-flow table. The diagrams, the maintenance + module and the schedule module use it in place of their own copies. + No result changes. + +- Changed (intentional, the numbers can differ): a shutdown that takes + no time and has a cost is charged at each of its starts by + `availability()` and `cost()` (and so `npv_distribution`), as + `expected_cost` and `expected_npv` charge it; the simulation charged + it nothing. Its other values and seeded draws are unchanged. + +- Changed: the long-run methods' refusal of shutdowns at given times now + says why and what to ask for (they end, so there is no long run: a + horizon, or a period), where it said that the exact methods take + shutdowns on a period. + +- Changed: a `Recurrence` counted from an anchor (every so many days, + weeks, months or years) finds its dates far from the anchor without + walking to them from it. The dates are the same; a `Task.due` over + centuries, which took a time growing with the square of the dates, + now takes one in proportion (400 years of a 30-day task: 25 s to + 0.1 s). +- Changed (intentional, the numbers can differ): + `Repairable.optimal_overhaul_replace_policy` searched only "overhaul + every `T`, replace after `K` periods", and its best was often beaten + by a plan it did not price. It now prices four plans and returns the + cheapest: overhaul and replace (`K` from 2 to `max_cycles`), overhaul + only (never replace; the age settles at `f T / (1 - f)`, `cycles` is + `inf`), replace only (`K = 1`) and a failure limit (replace at the + best `n`-th failure, at the replacement cost; new `max_failures`, + default 30). `OverhaulReplacePolicy` gains `plan`, `failure_count`, + `alternatives` (each plan's cost rate and settings), `saving` (against + the next best) and `cycles_limit_reached`; the old fields keep their + meaning. The documented example (overhaul every 177.7, replace every + second period, 0.1172 per unit time) now returns overhaul only, every + 73.8, at 0.1129. A unit that does not wear out returns plan `"run to + failure"`, as before with `interval` `inf` and `cycles` 1. + +- Changed: `optimal_next_replacement` with a policy chosen at a discount + (a `MaintenancePolicy` or `CalendarPolicy` with `discount_rate`, or a + site's discounted `ShutdownPolicy` or horizon) now discounts its own + choices at the policy's rate and values the time the part serves at + the policy's equivalent annual cost: each choice's present value and + the policy's after it, less the policy's from now (Fox, 1966). It took + the EAC (or, in model time, the undiscounted `cost_rate`) as its + baseline and chose undiscounted. A horizon policy's baseline is now + its continuous equivalent annual cost (`ln(1 + d)` where it used `d`). + Undiscounted policies give the same numbers as before. +- Changed: a site's `discount=` without `horizon=` was refused ("goes + with horizon="); it now asks for the discounted long run. +- Changed: a meshed diagram's decision diagram tries a third order of + its nodes, a greedy one that looks a node ahead, and keeps it where it + leaves the narrowest frontier (meshes a few nodes wide and random + meshed diagrams; grids keep the order they had). Where the order + changes the diagram is a little smaller or larger (1,700 small random + cores: 2% fewer steps in all), and its probabilities can differ in + their last bits. `scripts/bdd_benchmark.py` measures what the diagrams + cost: at the step limit the search holds some hundreds of megabytes at + most, so the steps, not the memory, are what stops a core. +- Changed: `events_by_period`'s and `failures_by_period`'s notes, their + docstrings and the schedule guide say that with `discount=` the + costs by period (`cost`'s mean and range, `expected_cost`) stay + undiscounted, the present values being `expected_npv` and `npv`; the + note read as if `cost` were discounted. The values are unchanged. +- Changed: `RepairableRBD`'s docstring and the costs guide say that a + component's `"downtime_cost"` and the system's `downtime_cost_rate` + add up (an hour a series component is down costs both), so lost + output is priced in one of them. No behaviour changes. + +### Fixed + +- Fixed: the API reference has a page for `UnitPlan` and its tasks + and prices (`Prices`, `AgePolicy`, `BlockPolicy`, `ConditionPolicy`, + `CalendarReplacement`, `AtShutdown`, `Inspection`, `Upgrade`, + `Restoration`, `ImperfectRepair`), and lists + `schedule.CalendarContext`; each of their parameters is documented, + with its unit, as are `schedule.Condition`'s. No behaviour changes. +- Fixed: `RepairableRBD.cost_by_window` (and `events_by_period` with + `cost=True`) without a seed gave windows that cost less than nothing + in some simulations (on one diagram some 3,700 of 26,000, down to + -309,000). A window's cost is a simulation's cost to its end less its + cost to its start, which needs every end's run to draw the same + histories; a seeded call did, but an unseeded one let each run draw + its own. An unseeded call now draws one seed (from numpy's global + random number generator) for all its runs, so it is the seeded call + of that seed: never below 0, and the windows add to one run. Seeded + results are unchanged. `events_by_period` likewise seeds its + histories, costs and simulated present values once. + ## [0.19.1] - 2026-11-16 One addition to 0.19: a life on two clocks, surpyval's life at a usage diff --git a/CLAUDE.md b/CLAUDE.md index 5f5078cc..b64741dd 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -8,7 +8,7 @@ first. This file adds the internals and conventions it does not cover. release; the latest published release is on PyPI (`https://pypi.org/pypi/repyability/json`) and the CHANGELOG's newest dated section. New work goes under the CHANGELOG's `[Unreleased]`. The -minimum surpyval is in `pyproject.toml` (0.28 as of 0.19). +minimum surpyval is in `pyproject.toml` (0.29 as of 0.20). ## Architecture & scope @@ -43,6 +43,33 @@ minimum surpyval is in `pyproject.toml` (0.28 as of 0.19). level, and the probabilities a forecast is made of (expected failures and costs over a window from a state, and their distribution). +- **Maintenance and money are layered.** Each question has one home, + and the layers above call the ones below rather than repeat them: + - `repyability.value`: money. Discounting (one convention, continuous + at a rate per unit of the clock the money falls on; a yearly rate + converted in one place), escalation and real rates, + `ValueSchedule`, the cost categories and the cash-flow table. + - `repyability.maintenance`: a unit's plan and the single part's + maths. `UnitPlan` (its life, repairs, tasks, `Prices`, and its own + `salvage`, `escalation` and `retire_at`; a spec dict is its + shorthand), the policies, and `NonRepairable`'s methods. The + age-replacement EAC has one definition (`_options.cycle_eac`), + which a diagram's component takes too. A plan is valued alone + through its one-node diagram (`UnitPlan.diagram()`): there is no + second single-unit route. + - `repyability.schedule`: the calendar. Rules, duty plans and + `CalendarContext`, which gives an analysis its calendar and each + unit its duty plan. The duty plan belongs to the analysis, not to + the plan or the diagram. + - `RepairableRBD`: only what belongs to the system. Its structure, + system downtime and value, crews, spares, the site's shutdowns and + common-cause groups. A node takes a `UnitPlan` (or its spec), and a + life can be any model with a life's functions, a `NonRepairableRBD` + included. + + What is still duplicated is listed in the maintenance README's + "Layers" section, so that it goes rather than spreads. + - **Model behaviour belongs in surpyval too.** When a surpyval model misbehaves (its draws, means, densities or save format), raise an issue in derrynknife/surpyval rather than only working around it here. Keep any @@ -126,6 +153,17 @@ minimum surpyval is in `pyproject.toml` (0.28 as of 0.19). a call binds costs reference counting that numba cannot prune in a function this size, and passing the run's tuples to a function per simulation cost several times the loop (measured in #206). +- **A life on the diagram's clock is the Python loop's alone** + (`_covariate_schedule.ClockLife`: a covariate schedule's + `ScheduledLife`, and a duty plan that changes over time, + `_duty.PlannedLife`): what is left of a unit's life depends on when it + is put into service (`life_left(t0, age, u)`, the loop's + `_ScheduledComponent`), so the exact methods refuse it and + `_compiled.unsupported` hands it to Python. A task counted in + operating time on such a plan carries it as its `_Preventive.clock` + (due in operating time, mapped back through the plan's inverse). The + engine always runs on calendar time; an analysis's + `schedule.CalendarContext` gives each unit its plan. - **Simulations take turns across threads (#216).** The event loop keeps a run's state on the diagram (`_run_state`, an `_events._Run`) and draws that cannot be streamed come from numpy's global RNG, so a run holds @@ -221,9 +259,26 @@ minimum surpyval is in `pyproject.toml` (0.28 as of 0.19). checks it changes nothing. - **The repair crews' Markov chain (`repyability/rbd/_crew_chain.py`) copies the simulation's queue (`_events._Crews`)**: which waiting job a free crew - takes, and how instant jobs pass through. A change to one goes into the - other; `test_crew_chain.py` checks the chain's exact values against the - simulation. Likewise a standby group's chain (`_standby_chain.py`) copies + takes, and how instant jobs pass through, and when a call-out crew + (`call_out`) comes and goes: it is engaged exactly while a job more than + the crews is under repair, so the chain's state needs nothing more. A + change to one goes into the other; `test_crew_chain.py` and + `test_call_out_crew.py` check the chain's exact values against the + simulation. It takes common-cause groups in too (#251, + `_crews._crew_causes`): a shared cause's strike is its members' failures + one after another in the cause's order, each as a failure of its own + (`_crew_chain._enumerate`'s `failed`), which is the order + `_event_loop._strike` queues them in only for two members (the event + queue releases ties at one time by its heap's shape, so the chain + refuses causes of more, `MAX_STRUCK`); `test_crews_ccf.py` checks it + against the simulation. The chain can count a component's alike copies + (`copies`: a state says how many are under repair and waiting, not + which), for the redundancy allocation with crews + (`_crew_allocation.py`, each design worked out whole from its chain, + the search bounded by the unavailability with a crew for every job and + the copies' prices); `test_crew_allocation.py` checks the counted chain + against the chain of every copy, and each design against the diagram + with its copies drawn out. Likewise a standby group's chain (`_standby_chain.py`) copies `_events._StandbyGroup`'s rules (switching, spares, repairs), checked by `test_repairable_standby.py`. - **A phased mission's Markov chain (`repyability/rbd/_mission_chain.py`) @@ -258,6 +313,18 @@ minimum surpyval is in `pyproject.toml` (0.28 as of 0.19). (`_Counted`) rather than tell them apart, which holds for a `BetaFactor`'s one shared cause: `test_ccf_allocations.py` checks them against the chain of every copy. +- **A `Shocks` group's causes are the simulation's shared causes at + rates of their own** (`_ccf_groups._shared_causes`, from + `Shocks.causes`): every set of members a shock can fail, a single + member's too, each a `_Cause` on the cause streams, while a member's + own life is its own model's (`_own_rate` is None). A cause names its + members in the group's order, which is the order `_event_loop._strike` + fails them in: that is the rule for members struck at one instant. No + chain copies them: `_ccf_rates` refuses the group for every exact + method. A `NonRepairableRBD` writes the same causes into its structure + (`shocks.written_shocks`) and is from then on the diagram written out; + it saves the diagram as given (`_given_args`). `test_shock_nodes.py` + and `test_repairable_shocks.py` check both. - **A common-cause group's chain with tests and repairs that take time (`_ccf_chain._Timed`, #220) copies the simulation's inspections** too (`_event_loop._inspected_follow_up`, `_event_loop._inspected_next`, `_event_loop._strike`): a working member @@ -449,7 +516,14 @@ minimum surpyval is in `pyproject.toml` (0.28 as of 0.19). public function of the classes that simulate (an `RBD` subclass gets it from `RBD.__init_subclass__`); a new class whose methods take `mc_samples` gets `@refuse_removed_names`. A seed goes through - `checks.seed` where it is taken. + `checks.seed` where it is taken. `n_draws` is kept, deliberately, for + the number of draws of uncertain models' parameters (the + `*_uncertainty` methods, `uncertainty_importance`, + `optimal_replacement_intervals`), each draw worked out without + simulating it: a method that takes `n_draws` but not `mc_samples` + refuses `mc_samples=` (and the removed names), naming `n_draws`, through + the same wrapper (a class with such methods gets `@refuse_removed_names` + too). - **Inputs are checked where they are given (#233)**: numbers through `checks.is_number`/`number_or_nan` (not `bool`, not text), times through `checks.real_array`, a choice of option through `checks.one_of`, and @@ -499,11 +573,22 @@ minimum surpyval is in `pyproject.toml` (0.28 as of 0.19). `surpyval.test_planning`'s, and 0.18 removed them with `DemonstrationPlan` (`test_removed_in_0_18.py`). 0.18 and 0.19 deprecate nothing, so 0.19 removes nothing (nor does 0.19.1, which - only adds the life at a usage rate as a block); `NEXT_REMOVAL` is 0.20, - which `test_what_0_19_deprecates_goes_in_0_20` reminds. A new + only adds the life at a usage rate as a block), and 0.20 removes + nothing. 0.20 deprecates, for 0.21 (`NEXT_REMOVAL`, which + `test_what_0_20_deprecates_goes_in_0_21` in `test_api_consistency.py` + reminds; a deprecation in 0.21's development goes in + `REMOVED_IN_0_22`), `Calendar`, + `Shutdown`, `Shutdowns`, prices on opportunities and + `optimal_calendar_policy`/`calendar_policy_cost` (UC-45; the prices + come with the part), which `test_what_0_20_deprecates_goes_in_0_21` + (`test_opportunities.py`) reminds, and `method="auto"` sampling a + calendar too long to sweep (UC-44, `refuses_from`), which + `test_auto_sampling_refuses_in_0_21` (`test_exact_or_horizon.py`) + reminds. A new deprecation warns through `deprecation.renamed`, `renamed_attribute`, - `called`, `ignored` or `moved`, with a test that fails once the version - reaches its removal. + `called`, `ignored`, `moved`, `replaced`, `price_on_part` or + `refuses_from`, with a test + that fails once the version reaches its removal. - **No result depends on the unit of time (or of a covariate).** A step, grid or probe is sized from the models (a typical life, `failure_time_scale`), never in absolute time, and a proportional @@ -563,10 +648,14 @@ RePyability's own in 0.17 with the same values. surpyval's deprecation policy calls public (the top level, its listed subpackages' `__all__`, `surpyval.univariate.regression.kinds`) and reads no underscored attribute; `test_public_surpyval_api.py` fails on anything -else. Two names have no public home yet and are listed there -(`NO_PUBLIC_HOME`): `DynamicPrediction` (`rbd/joint_node.py`) and -`conditional_gaps` (`rbd/_event_loop._aged_life`). Take each from its -public home once surpyval gives it one; that test fails when it does. +else. Take a model class from its subpackage, not the top level +(`surpyval.univariate.joint`'s `JointModel`, +`surpyval.univariate.regression`'s `SemiParametricRegressionModel`): from +0.29 surpyval keeps only what users call at its top level, and the rest +warn there. One name has no public home yet and is listed there +(`NO_PUBLIC_HOME`): `conditional_gaps` (`rbd/_event_loop._aged_life`). +Take it from its public home once surpyval gives it one; that test fails +when it does. What remains (each checked against surpyval 0.28 on 15 Nov 2026): @@ -594,13 +683,14 @@ What remains (each checked against surpyval 0.28 on 15 Nov 2026): condition on survival, which for a Wiener path keeps the units that crossed and came back, so it is not this.) -- **Rescaling a model's time for a duty cycle.** surpyval has no - rescaling (#845 gave models only a unit label). A spec's `"duty"` puts a - life in operating time on the calendar, `R(d t)`, by `_duty._SCALED`, one rule per surpyval distribution (a new - one needs its rule there, which `test_units` checks against `R(d t)`). - Take surpyval's rescaling once the minimum surpyval has it. (0.28's - `EquivalenceModel.at_usage` turns a two-clock life into one clock at a - usage rate; it does not rescale a model's time.) +- **Rescaling a model's time for a duty cycle** (surpyval 0.28 only). + A spec's `"duty"` puts a life in operating time on the calendar, `R(d + t)`, by the model's own `rescale_time(d)` (surpyval's release after + 0.28). With 0.28, which has none, `_duty._SCALED` moves each surpyval + distribution's parameters (a rule per distribution, which `test_units` + checks against `R(d t)` with `rescale_time` hidden). Drop `_SCALED`, + and `on_calendar`'s fallback, once the minimum surpyval has + `rescale_time`. - **Parameter ranges for drawing fits other than distributions** (no surpyval issue yet). surpyval gives no range per parameter for a regression, a degradation or repairable-unit process or a mixture, so @@ -609,6 +699,18 @@ What remains (each checked against surpyval 0.28 on 15 Nov 2026): scale. Take surpyval's ranges once the minimum surpyval says them. (0.27 keeps them private, such as a regression's `_parameter_bounds`.) +- **A share of a model's hazard** (no surpyval issue known yet: a hazard + ratio as a model option, with `isf`). A common-cause group splitting + the failure rate gives each cause a share `c` of its members' hazard, + survival `R(t)^c`, which no surpyval 0.28 model is. `ccf._hazard` and + `ccf._rate_causes` work it out from the members' own model as + `exp(-c H)` and `-expm1(-c H)` (`H` from whichever of `ff` and `sf` + keeps its digits), and `NonRepairableRBD._group_sampler` draws it + through the members' quantile function at `-expm1(-e)`, `e` the first + of the causes' exponential times. Build each cause's life with + surpyval's hazard ratio (`from_params(..., hr=c)`) once the minimum + surpyval has it. + - **A joint frailty model's own integration in `RepairOrReplace`** (`maintenance/_repair_or_replace.py`). surpyval 0.27's `JointFrailtyModel.mcf` fell towards 0 far past the write-off ages; diff --git a/README.md b/README.md index c8713efa..6879887c 100755 --- a/README.md +++ b/README.md @@ -191,6 +191,10 @@ Which analyses each model type has (the method; — where it has none): | Expected cost in a window | — | `expected_cost` | — | — | — | | Expected net present value | — | `expected_npv` | — | — | — | | A plan against what happened | — | `plan_vs_actual` | — | — | — | +| Simulated net present value (distribution) | — | `npv_distribution` | — | — | — | +| Best time to switch blocks' running (simulated NPV) | — | `best_switch_time` | — | — | — | +| Two plans' net present values compared | — | `compare_npv` | — | — | — | +| Least spend for a bad run's downtime (simulated) | — | `least_spend_for_downtime` | — | — | — | | Cost in each of a run of windows | — | `cost_by_window` | — | — | — | | Simulated cost (distribution) | — | `cost` | — | — | — | | Total cost of ownership | — | `total_cost` | — | — | — | @@ -236,6 +240,7 @@ Which analyses each model type has (the method; — where it has none): | Of the MTTF | `mean_uncertainty` | — | `mean_uncertainty` | `mean_uncertainty` | — | | Of the B-life | `bx_life_uncertainty` | — | — | — | — | | Of the cost rate | — | `expected_cost_rate_uncertainty` | — | — | — | +| Of the net present value | — | `expected_npv_uncertainty` | — | — | — | | **Design and maintenance** | | | | | | | Reliability allocation | `simple_allocation` | `simple_allocation` | — | — | — | | Availability, MTTF and MTTR allocation | — | `availability_allocation` | — | — | — | @@ -281,14 +286,14 @@ How each family of analyses is worked out on a diagram with each kind of node or |---|---|---|---|---|---|---|---|---|---|---|---|---| | Any life and repair | E | E | N | E N | E N | N | S | E | – | N | – | S | | A fitted life | E | E | N | N | E N | N | S | E | – | N | – | S | -| A fitted Crow-AMSAA process | ✗ | ✗ | N | N; ✗ `expected_cost_rate` | N; ✗ 10 of 11 | ✗ | ✗ | ✗ | – | ✗ | ✗ `capacity_distribution` | S | +| A fitted Crow-AMSAA process | ✗ | ✗ | N | N; ✗ `expected_cost_rate` | N; ✗ 10 of 11 | ✗ | S; ✗ `mean_availability_uncertainty`, `expected_cost_rate_uncertainty` | ✗ | – | ✗ | ✗ `capacity_distribution` | S | | A fitted G1, ARA or ARI process | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | – | ✗ | ✗ `capacity_distribution` | S | -| A probability per demand | ✗ | ✗ | ✗ | ✗ `expected_npv` | ✗ | ✗ | ✗ `mean_availability_uncertainty` | ✗ | – | N | ✗ `capacity_distribution` | S | +| A probability per demand | ✗ | ✗ | ✗ | ✗ `expected_npv` | ✗ | ✗ | ✗ `mean_availability_uncertainty`, `expected_npv_uncertainty` | ✗ | – | N | ✗ `capacity_distribution` | S | | A mixture life | E | E | N | E N | E N | N | S | E | – | N | – | S | | A fitted degradation process life | E | E | N | N | E N | N | S | E | – | N | – | S | | Operated part of the time (duty) | N | N | N | N | N | N | S | N | – | N | – | S | | Tasks counted in running hours (duty) | N | N | N | N | N | N | S | N | N | N | – | S | -| A standby or load-sharing life, simulated | ✗ | ✗ | ✗ | ✗ `expected_npv` | ✗ | ✗ | ✗ `mean_availability_uncertainty` | ✗ | – | ✗ | ✗ `capacity_distribution` | S | +| A standby or load-sharing life, simulated | ✗ | ✗ | ✗ | ✗ `expected_npv` | ✗ | ✗ | ✗ `mean_availability_uncertainty`, `expected_npv_uncertainty` | ✗ | – | ✗ | ✗ `capacity_distribution` | S | | k-out-of-n | E | E | N | N | E N | N | S | E | – | N | – | S | | A nested RBD | E | E | N | E N | E N | N | S | E | – | – | – | S | | A junction | E | E | N | E N | E N | N | S | E | – | N | – | S | @@ -302,15 +307,15 @@ How each family of analyses is worked out on a diagram with each kind of node or | Tests that take time | N | N | N | N | N | N | S | N | – | N | – | S | | Tests that can miss a failure | N | N | N | N | N | N | S | N | – | N | – | S | | Imperfect repair (Kijima) | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | – | ✗ | ✗ `capacity_distribution` | S | -| Minimal repair | ✗ | ✗ | N | N; ✗ `expected_cost_rate` | N; ✗ 10 of 11 | ✗ | ✗ | ✗ | – | ✗ | ✗ `capacity_distribution` | S | -| Minimal repair, repairs that take time | ✗ | ✗ | N | N; ✗ `expected_cost_rate` | N; ✗ 10 of 11 | ✗ | ✗ | ✗ | – | ✗ | ✗ `capacity_distribution` | S | +| Minimal repair | ✗ | ✗ | N | N; ✗ `expected_cost_rate` | N; ✗ 10 of 11 | ✗ | S; ✗ `mean_availability_uncertainty`, `expected_cost_rate_uncertainty` | ✗ | – | ✗ | ✗ `capacity_distribution` | S | +| Minimal repair, repairs that take time | ✗ | ✗ | N | N; ✗ `expected_cost_rate` | N; ✗ 10 of 11 | ✗ | S; ✗ `mean_availability_uncertainty`, `expected_cost_rate_uncertainty` | ✗ | – | ✗ | ✗ `capacity_distribution` | S | | Limited repair crews | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | – | ✗ | ✗ `capacity_distribution` | S | | A standby group | E | E | N | E N | E N | N | S | E | – | ✗ | – | S | | A beta-factor group, revealed failures | E | E | N | N | E N | N | S | E | – | N | – | S | | A beta-factor group, tested | E | E | N | E N | E N | N | S | E | – | N | – | S | | An alpha-factor group, revealed failures | E | E | N | N | E N | N | S | E | – | N | – | S | | A group whose tests take time | N | N | N | N | N | N | S | N | – | N | – | S | -| A structure too meshed to work out | ✗ | ✗ | ✗ | E; ✗ `expected_cost`, `expected_npv` | ✗ | ✗ | S; ✗ `mean_availability_uncertainty` | ✗ | – | N | – | S | +| A structure too meshed to work out | ✗ | ✗ | ✗ | E; ✗ `expected_cost`, `expected_npv` | ✗ | ✗ | S; ✗ `mean_availability_uncertainty`, `expected_npv_uncertainty` | ✗ | – | N | – | S | @@ -346,7 +351,8 @@ places, nested diagrams): fail to switch in or to start, in each of these; load sharing of identical units; common-cause groups, for the system's reliability, importance, sensitivity and redundancy allocation (and, splitting the - failure rate, its MTTF); + failure rate, its MTTF and the analyses given its members' one age: + [wear-out lives and ages](docs/guide/common-cause-ages.md)); - **non-repairable questions:** reliability, hazard, MTTF, B*X* life and importance measures at any time, also given each component's current age; the distribution of the system's capacity; @@ -380,18 +386,18 @@ places, nested diagrams): | Warm standby with two or more units operating, of non-exponential units | Simulated in the system's simulations; the analyses that need the group's reliability refused | Yes, in general: which spare is switched in where, and how much each has aged, branch with the order of the failures. With one unit operating it is numerical, hot standby (k-out-of-*n*) exact, and Exponential units exact (a Markov chain), spares that may fail to switch in or start included. | | Cold standby with three or more different units operating, and load sharing of different units | Simulated in the system's simulations; the analyses that need the group's reliability refused | Yes, in general: which spare goes where, and how old the others are, branch with the order of the failures. Identical units are numerical in both, and so are two different units operating; Exponential units in standby are exact. | | Anything such a node is part of | Simulated in the system's simulations; the analyses that need the node's reliability refused | Only while the node has no reliability of its own. | -| Common-cause groups: analyses given ages, and the MTTF of a group splitting a failure probability | Refused (a simulated MTTF leaves a probability split out) | No: the analyses given ages need a model of members of different ages. A group splitting the failure rate (`basis="rate"`) has an exact MTTF, and the simulations draw its shared shocks. Importance, parameter sensitivity and redundancy allocation are exact with groups (a beta-factor member's copies join its group), and parameter uncertainty is sampled with them. | +| Common-cause groups: analyses given ages for members of different ages or a group splitting a failure probability, and the MTTF of such a group | Refused (a simulated MTTF leaves a probability split out) | No. A group splitting the failure rate (`basis="rate"`) is exact given its members' one age, as a share of their hazard is one hazard only then, and a shock at its own rate that fails members of any lives and ages is an exponential node in series with them, and `shock_nodes` writes out shocks that fail each member with a probability ([the guide](docs/guide/common-cause-ages.md)). A group splitting the failure rate has an exact MTTF, and the simulations draw its shared shocks. Importance, parameter sensitivity and redundancy allocation are exact with groups (a beta-factor member's copies join its group), and parameter uncertainty is sampled with them. | | **Architecture and maintenance** | | | | Phased missions and networks too large for their decision diagrams | Refused, pointing to `method="simulate"` | Only in practice: the diagrams grow with the phases' and the network's width rather than their paths, so meshed missions and networks are exact (a network grid of 100 nodes in a second and a half); one of 121 nodes passes the limit, `repyability.network.MAX_STATES`, which can be raised. | | Block diagrams too meshed for their decision diagrams | Simulated (lifetimes, availability, cost and timelines, in Python); the exact and numerical analyses refused | Only in practice: the diagram grows with how wide the mesh is rather than with its paths, so most meshes are exact (a 10 × 10 grid in 0.04 seconds, a random mesh of 60 nodes and 345 links in 2); one of 70 nodes and 485 links passes the limit, `repyability.rbd.bdd.STEP_LIMIT`, which can be raised. | -| Common-cause groups in a repairable diagram | For exponential lives, tested or repaired: the long run, importance and the allocations exact (a beta-factor member's copies join its group, and the availability allocations keep the members' availability), and numerical where the members' tests and repairs take time (#220): a fixed or an exponential time exactly, any other length on pieces of the time since the test (#106); the values over time numerical (the groups' Markov chains), from new, from the members' states or from the long run (#106), and the simulations draw the shared causes, from new or from the members' states, in Python. Members of other lives refused, as are copies of members whose tests or repairs take time, tests and repairs that can run into the next test, and members held | Other lives: a shared cause has no one rate for members of different ages, so they need a model first. | -| Shared repair crews | For exponential lives and repairs, the long run and importance exact, and the values over time numerical (the same Markov chain, followed by uniformization), but the allocations; other lives simulated. The maintenance and test intervals are chosen as if every repair started at once on request (`assume_unlimited_crews=True`), for a plan to simulate with the crews | Other lives: yes, in general. | +| Common-cause groups in a repairable diagram | For exponential lives, tested or repaired: the long run, importance and the allocations exact (a beta-factor member's copies join its group, and the availability allocations keep the members' availability), and numerical where the members' tests and repairs take time (#220): a fixed or an exponential time exactly, any other length on pieces of the time since the test (#106); the values over time numerical (the groups' Markov chains), from new, from the members' states or from the long run (#106), and the simulations draw the shared causes, from new or from the members' states, in Python. Shocks at a rate of their own (`Shocks`: each failing each member with a probability, the members of any lives, each then repaired or found at its test on its own) are simulated, in Python, and the exact methods refuse them. Members of other lives in the groups that split the rate refused, as are copies of members whose tests or repairs take time, tests and repairs that can run into the next test, and members held | Other lives: a shared cause has no one rate for members of different ages, so they need a model first. Shocks at their own rate are that model for members of any lives, simulated; their chain would need each member's age, so yes, in general. Without repairs, [the guide](docs/guide/common-cause-ages.md) has a second: a share of the hazard of members of one age. | +| Shared repair crews | For exponential lives and repairs, the long run and importance exact, and the values over time numerical (the same Markov chain, followed by uniformization), and the redundancy allocation exact (each design's chain, its copies queueing for the crews), but the allocations of availability targets; common-cause groups whose causes strike two members in the same chain (more: simulated); other lives simulated. The maintenance and test intervals are chosen as if every repair started at once on request (`assume_unlimited_crews=True`), for a plan to simulate with the crews | Other lives: yes, in general. | | Standby groups (a duty unit and its spares, repaired) | For exponential units, the long run and importance exact, and the values over time numerical (the units' Markov chain, followed by uniformization); other units simulated | Other units: yes, in general. | | Opportunistic maintenance (renewals at a group's stops) | Simulated | Yes: each member's renewals depend on the others' ages. | | Imperfect repair (Kijima), with or without replacement at the *N*-th failure | Simulated; but minimal repair (`q = 1`, or a fitted Crow-AMSAA, Duane or Cox-Lewis process) is numerical over a window from new, and its long run, replaced at the *N*-th failure or at an age, is exact (a renewal cycle; Cox-Lewis's with a failure limit by quadrature, #402); without a replacement its long run is refused | Yes, in general: a repair does not renew the unit. Minimal repair's values over time with replacement could be numerical, as a renewal of its cycle. | | Preventive maintenance that restores a unit only partly (Kijima), with or without replacement at every *N*-th task | Simulated (availability, cost, timelines and the spares used, in Python), from new or from the unit's virtual age; the exact and numerical analyses refused | Yes, in general: a task does not renew the unit, so its failures are not a renewal process's. | -| Shutdowns: outages that hold the system or some blocks off line for a fixed time, the blocks' work done in them | On a period, over blocks that fail independently: exact or numerical as the blocks' own values are (the long run, the values over time, the expected events, costs and NPV), "older than" numerical; the simulations follow the windows, in Python. At given times, with a restoration at a shut, or with blocks tied together (crews, common causes, maintenance groups): simulated. The importance measures, capacities, first failure, spares, allocations, parameter uncertainty and interval searches refused for now | At given times, no: the exact values over time could take windows at given times, as they take them on a period. The rest are not taken in yet. | -| Planned against unplanned downtime, and the failures a plan avoids (`maintenance_effect`) | Exact or numerical where the diagram's and its run-to-failure twin's values over a window are, over blocks that fail independently: each block's probability of having failed over time, beside its downtime, from its curve (maintenance and timed tests at age or on a calendar, shuts on a period, nested RBDs), in the long run too; the simulations follow it path by path, on both engines. With planned outages and limited repair crews or common-cause groups, at given times, or with partial restoration: simulated | Crews and common-cause groups, no: their chains could keep a block in planned work apart from one in a repair, as a single block's curve does. | +| Shutdowns: outages that hold the system or some blocks off line for a fixed time, the blocks' work done in them | On a period, over blocks that fail independently: exact or numerical as the blocks' own values are (the long run, the values over time, the expected events, costs and NPV), "older than" numerical; the simulations follow the windows, in Python. At given times (outages on a timeline), the same over a horizon where the blocks worked on are renewed at each, or kept unless due (numerical, stretch by stretch), and no long run (refused: the outages end); so too a block renewed at several shutdowns, each renewal its own shut's length. With a restoration at a shut, a block tested at given times, or with blocks tied together (crews, common causes, maintenance groups): simulated. The importance measures, capacities, first failure, spares, allocations, parameter uncertainty and interval searches refused for now | A block tested at given times: no, its recursion could take the times as the renewed and the kept block's do. A restoration: yes (the unit's virtual age is not a renewal's). The rest are not taken in yet. | +| Planned against unplanned downtime, and the failures a plan avoids (`maintenance_effect`) | Exact or numerical where the diagram's and its run-to-failure twin's values over a window are, over blocks that fail independently: each block's probability of having failed over time, beside its downtime, from its curve (maintenance and timed tests at age or on a calendar, shuts on a period or at given times, nested RBDs), in the long run too (where there is one); the simulations follow it path by path, on both engines. With planned outages and limited repair crews or common-cause groups, or with partial restoration: simulated | Crews and common-cause groups, no: their chains could keep a block in planned work apart from one in a repair, as a single block's curve does. | | Replacement on condition by a measured degradation level | Numerical, from new, from a state (a level measured now, new on its calendar, or in a repair or replacement) and in the long run: the values over time and the long run follow the level's distribution on a grid of levels from one inspection to the next, as replacement on condition by age follows ages; the simulations (in Python) give the spread | No: between inspections the level is a Markov process. | | Spares with repair crews, standby groups, opportunistic maintenance, imperfect repair or partial restoration | Refused, pointing to `spares_demand(method="simulate")`. Otherwise numerical, demand and stock: block-replaced components' whether their repairs and block replacements take time or not (from a typical replacement in the long run), but for one dead on arrival while they may take none, and tested components', whatever their tests and repairs take and whether their tests miss failures | Yes, in general: a crew's queue, a group's switching or stops, an imperfect repair and a partial restoration make the replacements depend on more than each unit's own lives. A unit dead on arrival whose renewals may take no time: no, the replacements at one instant could be counted. | diff --git a/docs/api/components.md b/docs/api/components.md index b26d5cc4..53a3f42f 100644 --- a/docs/api/components.md +++ b/docs/api/components.md @@ -10,6 +10,8 @@ ::: repyability.Opportunity +::: repyability.Opportunities + ::: repyability.Calendar ::: repyability.Shutdowns @@ -28,6 +30,8 @@ ::: repyability.failure_finding +::: repyability.failure_finding_window + ::: repyability.optimal_failure_finding_interval ::: repyability.on_condition diff --git a/docs/api/index.md b/docs/api/index.md index b1672c2c..ec246e6c 100644 --- a/docs/api/index.md +++ b/docs/api/index.md @@ -11,6 +11,7 @@ explanations and runnable examples, see the [user guide](../guide/index.md). - [Fault trees, phased missions and networks](other-systems.md) - [Node models](nodes.md) - [Components and maintenance](components.md) +- [Unit plans](unit-plans.md) - [Stress-strength interference](stress-strength.md) - [Timelines](timelines.md) - [Schedules](schedule.md) diff --git a/docs/api/nodes.md b/docs/api/nodes.md index 6ab4843b..f3d89da4 100644 --- a/docs/api/nodes.md +++ b/docs/api/nodes.md @@ -44,6 +44,10 @@ models provided here (see [Building an RBD](../guide/building.md) and ::: repyability.AlphaFactor +::: repyability.Shocks + +::: repyability.shock_nodes + ## Condition-based evaluation ::: repyability.NodeState diff --git a/docs/api/repairable.md b/docs/api/repairable.md index 7c7432b2..15c5e8c9 100644 --- a/docs/api/repairable.md +++ b/docs/api/repairable.md @@ -2,6 +2,12 @@ ::: repyability.RepairableRBD +## Contracts + +::: repyability.AvailabilityContract + +::: repyability.ValueSchedule + ## Seeding simulations ::: repyability.seed_entropy diff --git a/docs/api/results.md b/docs/api/results.md index b8224b68..06664003 100644 --- a/docs/api/results.md +++ b/docs/api/results.md @@ -42,6 +42,18 @@ ::: repyability.ExpectedNPV +::: repyability.NPVDistribution + +::: repyability.SimulatedSwitchTime + +::: repyability.NPVComparison + +::: repyability.DowntimeRiskResult + +::: repyability.DowntimeDesign + +::: repyability.NPVUncertainty + ::: repyability.MaintenanceEffect ::: repyability.PlanVsActual @@ -80,6 +92,8 @@ ::: repyability.MaintenancePlan +::: repyability.PlanRobustness + ::: repyability.Lever ::: repyability.StressStrengthResult @@ -98,6 +112,10 @@ ::: repyability.run_shard +::: repyability.value_plan + +::: repyability.npv_schema + ::: repyability.MaintenancePolicy ::: repyability.FailureLimitPolicy @@ -138,6 +156,8 @@ ::: repyability.FailureFinding +::: repyability.FailureFindingWindow + ::: repyability.OnCondition ::: repyability.NextReplacement @@ -146,6 +166,10 @@ ::: repyability.CalendarPolicy +::: repyability.OpportunityPrices + +::: repyability.OpportunityPrice + ::: repyability.PlannedReplacement ::: repyability.ShutdownPolicy diff --git a/docs/api/schedule.md b/docs/api/schedule.md index cd16889b..8155125d 100644 --- a/docs/api/schedule.md +++ b/docs/api/schedule.md @@ -15,6 +15,8 @@ tasks on dates and failures, events and work by calendar period (see the ::: repyability.schedule.TaskDue +::: repyability.schedule.LongRunValue + ::: repyability.schedule.work_by_period ::: repyability.schedule.WorkByPeriod @@ -47,6 +49,8 @@ tasks on dates and failures, events and work by calendar period (see the ::: repyability.schedule.DutySchedule +::: repyability.schedule.CalendarContext + ::: repyability.schedule.failures_by_period ::: repyability.schedule.FailuresByPeriod @@ -56,3 +60,15 @@ tasks on dates and failures, events and work by calendar period (see the ::: repyability.schedule.EventsByPeriod ::: repyability.schedule.shutdown_spec + +::: repyability.schedule.task_value + +::: repyability.schedule.Replaces + +::: repyability.schedule.Finds + +::: repyability.schedule.Services + +::: repyability.schedule.Condition + +::: repyability.schedule.TaskValue diff --git a/docs/api/unit-plans.md b/docs/api/unit-plans.md new file mode 100644 index 00000000..603e50b8 --- /dev/null +++ b/docs/api/unit-plans.md @@ -0,0 +1,32 @@ +# Unit plans + +One unit's maintenance plan as plain data: its life and repair models, its +tasks, each in its own clock, and its prices. A +[`RepairableRBD`](repairable.md) node takes a `UnitPlan` as it takes a spec +dict (the plan's shorthand), and a plan is valued alone through the diagram +of its one node. See [Maintaining a system](../guide/system-maintenance.md) +for the tasks and [Costs](../guide/costs.md) for the prices. They are +exported at the top level and from `repyability.maintenance`: +`from repyability import UnitPlan`. + +::: repyability.UnitPlan + +::: repyability.Prices + +::: repyability.AgePolicy + +::: repyability.BlockPolicy + +::: repyability.ConditionPolicy + +::: repyability.CalendarReplacement + +::: repyability.AtShutdown + +::: repyability.Inspection + +::: repyability.Upgrade + +::: repyability.Restoration + +::: repyability.ImperfectRepair diff --git a/docs/guide/common-cause-ages.md b/docs/guide/common-cause-ages.md new file mode 100644 index 00000000..4989d859 --- /dev/null +++ b/docs/guide/common-cause-ages.md @@ -0,0 +1,272 @@ +# Common causes with wear-out lives and ages + +A [common-cause group](common-cause.md) is symmetric: its members carry +one model. This page is about members that wear out and have been running +for a while, which asks what the shared cause is: + +| The shared cause | How to model it | Members | +|---|---|---| +| A shock from outside, at a rate that does not depend on the members' ages, that fails every member it reaches (a flood, a surge, a wrong setting applied to all) | An exponential node in series with the members: no group | Any lives, each at its own age | +| The same shocks, each failing each member it reaches with a probability `p` (the binomial failure rate model) | `shock_nodes`, which writes a node for each set of members a shock can fail | Any lives, each at its own age | +| A share `β` of each member's own hazard, which ages as the members do (a batch defect, a shared environment that wears them together) | A group splitting the failure rate, `BetaFactor(beta, basis="rate")` | One life and one age: installed and replaced together | + +Both are taken by every analysis of a +[`NonRepairableRBD`][repyability.NonRepairableRBD], the +[condition-based](condition-based.md) ones among them. + +## A shock that fails every member + +A shock process of rate `λc` that fails every member it strikes is one more +component: it "fails" at the first shock, at an exponential time, and the +members it strikes cannot work past it. Put it in series with them. Each +member keeps its own life and its own age, and the shock has no age (an +exponential life has no memory). + +Two pumps in parallel, of Weibull lives, with a shock every 50,000 hours on +average: + +```python +import numpy as np +import surpyval as surv +from repyability import BetaFactor, CCFGroup, NodeState, NonRepairableRBD + +pump = surv.Weibull.from_params([8000, 2.5]) +shock = surv.Exponential.from_params([2e-5]) + +parallel = [("s", "p1"), ("s", "p2"), ("p1", "t"), ("p2", "t")] +with_shock = [("s", "p1"), ("s", "p2"), ("p1", "shock"), ("p2", "shock"), ("shock", "t")] + +alone = NonRepairableRBD(parallel, {"p1": pump, "p2": pump}) +pair = NonRepairableRBD(with_shock, {"p1": pump, "p2": pump, "shock": shock}) + +alone.sf(2000) # -> 0.99905 +pair.sf(2000) # -> 0.95988 = exp(-2e-5 × 2000) × 0.99905 +alone.mean() # -> 8816.9 +pair.mean() # -> 8022.8 exact +pair.mean(method="simulate", seed=0) # -> 8016.3 +``` + +**Members of different ages.** One pump has run 6000 hours and the other +1000. Each is conditioned on its own age, and the shock on nothing: + +```python +ages = {"p1": NodeState(age=6000), "p2": NodeState(age=1000)} + +alone.sf_given_state(2000, ages) # -> 0.96893 the next 2000 hours, no shared cause +pair.sf_given_state(2000, ages) # -> 0.93094 + +# The closed form: R_sys = exp(-λc x) × R_independent(x | ages) +float(np.exp(-2e-5 * 2000) * alone.sf_given_state(2000, ages)) # -> 0.93094 + +alone.remaining_life(0.9, ages) # -> 3118.0 hours until the reliability is 0.9 +pair.remaining_life(0.9, ages) # -> 2471.6 +``` + +The importance measures name the shock as they name any component, which +says how much of the risk is the shared cause's: + +```python +worth = pair.importances_given_state(2000, ages) +worth["criticality"]["shock"] # -> 0.5501 over half of the risk in the next 2000 hours +worth["criticality"]["p1"] # -> 0.4322 +worth["birnbaum"]["p2"] # -> 0.3855 the newer pump matters more: the older is likelier to fail +``` + +### Members that are not side by side + +Where the members sit in different branches, no one place in the diagram is +in series with all of them. Draw the shock once in each branch, as [one +component in several places](building.md#one-component-in-several-places): +the second node names the first, and the two fail as one. + +```python +valve = surv.Weibull.from_params([20000, 1.5]) + +# s -> c1 -> p1 -> v1 -> t +# s -> c2 -> p2 -> v2 -> t c2 is the same shock as c1: it fails both pumps +trains = NonRepairableRBD( + [("s", "c1"), ("c1", "p1"), ("p1", "v1"), ("v1", "t"), + ("s", "c2"), ("c2", "p2"), ("p2", "v2"), ("v2", "t")], + {"p1": pump, "p2": pump, "v1": valve, "v2": valve, "c1": shock, "c2": "c1"}, +) +trains.repeated # {'c2': 'c1'} +trains.sf_given_state(2000, {"p1": 6000, "p2": 1000, "v1": 3000, "v2": 3000}) # -> 0.90282 +``` + +Several shock processes (one that fails the pumps, another the valves) are +several such nodes. A shock that fails only some of the members is a node in +series with those members only. + +## A shock that fails each member with a probability + +A shock need not fail everything it reaches. In the binomial failure rate +model, shocks arrive at a rate and each fails each member independently +with probability `p`, so one shock may fail one member, another two, a +third none. By thinning the shocks, that is one independent cause for +each set of members: the cause that fails exactly a set of `j` of the `m` +members strikes at rate `rate · p^j · (1 − p)^(m − j)`. Each is an +exponential node in series with the members it fails, so +[`shock_nodes`][repyability.shock_nodes] writes them into a diagram's edges +and nodes: a node after each member a cause fails, one component in +several places. + +```python +from repyability import shock_nodes + +edges, nodes = shock_nodes( + parallel, {"p1": pump, "p2": pump}, + members=["p1", "p2"], rate=2e-5, p=0.6, +) +partial = NonRepairableRBD(edges, nodes) +len(nodes) # -> 6 the pumps, and three causes: of each pump alone (one node) and of both (two) + +partial.sf_given_state(2000, ages) # -> 0.95111 between no shocks (0.96893) and p = 1 (0.93094) +partial.mean() # -> 8404.2 + +# The closed form: the cause of both has not struck, and each pump has +# survived its own life from its age and the cause of it alone +both = np.exp(-2e-5 * 0.6 * 0.6 * 2000) +alone_ = np.exp(-2e-5 * 0.6 * 0.4 * 2000) +old = pump.sf(8000) / pump.sf(6000) * alone_ +young = pump.sf(3000) / pump.sf(1000) * alone_ +float(both * (1 - (1 - old) * (1 - young))) # -> 0.95111 +``` + +The members keep their own lives, which may differ, and their own ages; the +causes have none. `p=1` (the default) is the one node of the section above, +and `lethal_rate=` adds shocks of a second kind that fail every member, as +the model's authors have it. A process has a cause for each set of its +members (`2^m − 1`), so it takes up to ten. The importance measures name +each cause, `("shock", the members it fails, the member it follows)`, and a +member's own entry is that of its own failures. Give each process of a +diagram a name of its own (`name=`). + +The same shocks can be given as a group's model, +[`Shocks`][repyability.Shocks], which the diagram writes into its structure +exactly as `shock_nodes` does (the same nodes and the same values, to the +last bit) and saves as given: + +```python +from repyability import Shocks + +grouped = NonRepairableRBD( + parallel, {"p1": pump, "p2": pump}, + ccf_groups=[CCFGroup(["p1", "p2"], Shocks(rate=2e-5, p=0.6))], +) +grouped.sf_given_state(2000, ages) == partial.sf_given_state(2000, ages) # True +list(grouped.nodes) == list(partial.nodes) # True +grouped.to_dict()["ccf_groups"][0]["model"]["kind"] # 'shocks' +``` + +Unlike the other models, which split the failures the members' own model +describes, `Shocks` adds failures to it, so the members need not be alike. +The first group's causes are named `"shock"`; with several, `"shock 1"`, +`"shock 2"`, ... in the groups' order. + +For members with exponential lives this is an +[alpha-factor](common-cause.md#the-three-models) group by rate: a member +fails at its own rate plus `rate · p`, and the cause of each set of `j` is +its share of that. + +## A share of each member's hazard + +Where the shared cause wears as the members do, a share `β` of each member's +hazard `h(t)` is the shared cause's and the rest the member's own. The +shared cause then has survival `R(t)^β` and each member's own causes +`R(t)^(1 − β)`, `R` the members' reliability, so every member still has the +life `R(t)^β · R(t)^(1 − β) = R(t)`. That is a group splitting the failure +rate, [`BetaFactor(beta, basis="rate")`](common-cause.md#over-a-lifetime), +for members of any life: + +```python +beta = 0.1 +group = NonRepairableRBD( + parallel, {"p1": pump, "p2": pump}, + ccf_groups=[CCFGroup(["p1", "p2"], BetaFactor(beta, basis="rate"))], +) +alone.sf(5000) # -> 0.92941 +group.sf(5000) # -> 0.91250 +group.mean() # -> 8705.3 +``` + +**Members of one age.** The pumps were installed together 4000 hours ago. +Give every member that state, and each cause takes its share of the +members' hazard from that age on: + +```python +installed = {"p1": NodeState(age=4000), "p2": NodeState(age=4000)} +group.sf_given_state(2000, installed) # -> 0.91186 +group.remaining_life(0.9, installed) # -> 2136.8 +group.mean_residual_life(installed) # -> 5278.3 +group.importances_given_state(2000, installed)["birnbaum"]["p1"] # -> 0.3303 +``` + +It only means something for members of **the same age**. A share of "the +members' hazard" has no one value when one member's hazard is that of 6000 +hours and another's that of 1000: the model does not say whose the shared +cause follows. So a group whose members are given different states (or one +of them failed) is refused, and so is a group splitting a probability, +which says nothing of age: + +```python +try: + group.sf_given_state(2000, {"p1": 6000, "p2": 1000}) +except NotImplementedError as error: + refusal = str(error) +"node in series" in refusal # True +``` + +For members of different ages, model the shared cause as a shock +([above](#a-shock-that-fails-every-member)), whose rate is its own. + +### The same model drawn as nodes + +The split is itself a node in series: each member's own causes as its node, +with survival `R^(1 − β)`, and the shared cause as one node with `R^β`. For +a Weibull or an exponential life the two parts have a closed form, which +checks the group: + +| The members' life | Each member's own causes, `R^(1 − β)` | The shared cause, `R^β` | +|---|---|---| +| Weibull, scale `α` and shape `k` | Weibull, scale `α (1 − β)^(−1/k)`, shape `k` | Weibull, scale `α β^(−1/k)`, shape `k` | +| Exponential, rate `λ` | Exponential, rate `(1 − β) λ` | Exponential, rate `β λ` | + +```python +alpha, k = 8000, 2.5 +own = surv.Weibull.from_params([alpha * (1 - beta) ** (-1 / k), k]) # scale 8344.4 +shared = surv.Weibull.from_params([alpha * beta ** (-1 / k), k]) # scale 20095.1 +split = NonRepairableRBD(with_shock, {"p1": own, "p2": own, "shock": shared}) + +split.sf(5000) # -> 0.91250 the group's +split.mean() # -> 8705.3 +split.sf_given_state(2000, {"p1": 4000, "p2": 4000, "shock": 4000}) # -> 0.91186 +``` + +For an exponential life the two models of this page are one: a share `β` of +a constant hazard is a shock of rate `βλ`, which is why the members' ages +do not matter there. + +```python +rate = 1e-4 +exponential = NonRepairableRBD( + parallel, + {"p1": surv.Exponential.from_params([rate]), "p2": surv.Exponential.from_params([rate])}, + ccf_groups=[CCFGroup(["p1", "p2"], BetaFactor(beta, basis="rate"))], +) +exponential.sf(5000) # -> 0.82632 +exponential.sf_given_state(5000, {"p1": 30000, "p2": 30000}) # -> 0.82632 no memory +exponential.mean() # -> 14736.8 +``` + +## What these do not say + +- **A share of the hazard for members of different ages**: there is no one + hazard to share. Model the cause as a shock. +- **Repairable diagrams, exactly.** A node in series is down, and + repaired, as one component, where a shock leaves each member it failed + to be repaired on its own. Give a + [`RepairableRBD`][repyability.RepairableRBD] the shocks as a group's + model, `CCFGroup(members, Shocks(...))`: it + [simulates them](common-cause.md#shocks-at-a-rate-of-their-own), for + members of any lives, and its exact methods refuse, naming the + simulation. diff --git a/docs/guide/common-cause.md b/docs/guide/common-cause.md index c03fdbc7..a5a6a992 100644 --- a/docs/guide/common-cause.md +++ b/docs/guide/common-cause.md @@ -213,6 +213,8 @@ reliability: the group; - while `Q` is small it agrees with the probability split to first order, so over a mission or a proof-test interval the two give about the same. +- members that have run for a while, all to one age, are taken at that + age ([wear-out lives and ages](common-cause-ages.md)). ```python pair_rate = NonRepairableRBD( @@ -375,7 +377,7 @@ group's. | `sf_uncertainty`, `time_to_reliability_uncertainty`, `bx_life_uncertainty`, `mean_uncertainty` | Each draw worked out with the groups; the members drawn together, and the group's model too if it is given. `mean_uncertainty` refuses a group splitting a probability, as `mean` does. | | `allocate_redundancy`, `redundancy_front` | A member's copies join its group: a `BetaFactor` group's, active copies of the member's own model. Copies of an `MGL` or `AlphaFactor` group's member, and options or cold spares for a member, raise `NotImplementedError`. | | `allocate_reliability_redundancy` | Includes the groups; a member in `uses` raises `NotImplementedError` (its reliability is the group's). | -| The condition-based methods (`sf_given_state`, `remaining_life`, `importances_given_state`) | Raise `NotImplementedError`: they would need members of different ages. | +| The condition-based methods (`sf_given_state`, `remaining_life`, `mean_residual_life`, `importances_given_state`) | Include a group splitting the rate whose members are given one state (alive, at one age): each cause takes its share of the members' hazard from that age. Raise `NotImplementedError` for members in different states, and for a group splitting a probability. See [wear-out lives and ages](common-cause-ages.md), which also draws a shock that fails members of different ages as a node in series. | | `working_nodes` / `broken_nodes` naming a group member | Raises `NotImplementedError`. | ```python @@ -502,10 +504,22 @@ times the long-run grid's times) the exact values refuse, saying so, before working anything out: simulate such a system with `availability()` or `cost()`. The capacity distribution and the allocations still take every combination of every group's states at once, and refuse, before building -them, where those would take too much memory. Limited repair crews are -refused too, by every exact value, `node_availability` among them: the -groups' chains do not take the crews' queue in, and the crews' chain does -not take the common causes in, as yet. The simulations take both. +them, where those would take too much memory. + +With limited repair crews a shared failure's members queue for a crew with +the other components, which the groups' own chains do not follow: the +[crews' Markov chain](repairable.md#repair-crews) takes the groups in +instead. A shared cause strikes at its rate and fails the members it names +that are up, and they join the queue one after another in the group's +order, as in the simulation, so the first named is repaired first when a +crew is free. The long-run values, the importance measures and the values +over time then come from that chain, as without groups. It takes causes +that strike two members (any group of two; a larger `AlphaFactor` or `MGL` +group whose causes of three or more have no share): the simulation queues +three or more components struck at one instant in the order its event +queue releases them, which is not a rule a chain can copy, so those +refuse, as do members repaired instantly or found by tests. The +simulations take them all. Over time, each group's chain is followed from every member up at 0 (by uniformization, or through the members' tests, after whose first periods it @@ -639,8 +653,54 @@ exponential repairs, or tests and repairs over by the next test) holds for the exact and numerical values; the simulations need exponential lives alone. A member held working or broken, a member with a life of its own (a `level` or `model` in its state), a member maintained on a schedule, -repaired imperfectly or in a maintenance group, and a group with limited -repair crews are refused, with the reason; `analysis_routes()` says which. +repaired imperfectly or in a maintenance group, and with limited repair +crews a group one of whose causes strikes three or more members, are +refused, with the reason; `analysis_routes()` says which. (With limited +repair crews a member may be held: it is struck no more, and the causes it +shares still strike the others.) + +### Shocks at a rate of their own + +The models above split the members' own failure rate, so their members +must have exponential lives. [`Shocks(rate, p, lethal_rate)`][repyability.Shocks] +adds failures instead: shocks come at `rate`, whatever the members' ages, +and each fails each member with probability `p` (`lethal_rate` adds shocks +that fail every member), while each member keeps its own life, of any kind, +for its other failures. The members need not be alike. A strike fails the +members it names that are up, in the group's order; each is then repaired +on its own, and a tested member's failure waits, unseen, for its test (with +a test that can miss, one coin for all the failures of a strike). A member +that is down when a shock comes is not struck. + +A `RepairableRBD` simulates such a group, in Python, and its exact methods +refuse it, naming the simulation: + +```python +from repyability import Shocks + +worn = { + "reliability": surv.Weibull.from_params([300, 2.0]), + "repairability": surv.Exponential.from_params([0.1]), +} +struck = RepairableRBD( + [("s", "a"), ("s", "b"), ("a", "t"), ("b", "t")], + {"a": dict(worn), "b": dict(worn)}, + ccf_groups=[CCFGroup(["a", "b"], Shocks(rate=1e-3, p=0.5))], +) +struck.analysis_routes()["availability"].route # 'simulated' +struck.analysis_routes()["mean_availability"].route # 'refused' +run = struck.availability(5000.0, mc_samples=2000, seed=0) +``` + +For exponential members the shocks are the rate-split groups above, strike +for strike: own failures at `2^-10` with lethal shocks at `2^-10` are a +`BetaFactor(0.5)` pair of rate `2^-9`, and a seeded run of one is the +other's. A member of a `Shocks` group may be tested or repaired, and +started from its age; scheduled maintenance, imperfect repair or a +maintenance group on a member is refused, as is a tested member started +from a state (a shock may have failed it since its last test). Without +repairs, the same model is exact: see [wear-out lives and +ages](common-cause-ages.md). Common-cause groups can also be added to a diagram in the browser in [Reliafy](https://reliafy.com/guides/common-cause-group). diff --git a/docs/guide/condition-based.md b/docs/guide/condition-based.md index 81b155a9..c373bf12 100644 --- a/docs/guide/condition-based.md +++ b/docs/guide/condition-based.md @@ -417,9 +417,13 @@ the answer agrees with its halving to `tolerance` (1e-6 by default; the switch search values each switch time to 1e-4). The result says how closely it did (`error`) and that it is numerical (`method`). -- One unit only, for now: a whole diagram on a load schedule is not built - yet, as a `RepairableRBD` component cannot take a covariate-dependent - life. +- For a whole diagram, + [`RepairableRBD.best_switch_time`][repyability.RepairableRBD.best_switch_time] + asks the same question by simulation: the blocks that switch run on + covariate schedules (a spec's `"covariates"`), each candidate switch + time is simulated from one seed so the candidates are compared on the + same runs, and `difference_interval("never switch")` or `("switch at + once")` says how sure the best is better than either end. - `age` is how long the unit in service at 0 has already run, at the first stretch's covariates. - A semiparametric (Cox) model is refused: it has no proper curve to renew. diff --git a/docs/guide/costs.md b/docs/guide/costs.md index fb1f7048..6de18693 100644 --- a/docs/guide/costs.md +++ b/docs/guide/costs.md @@ -23,6 +23,23 @@ Costs are optional keys of a component's dict, plus one system-level rate: | Component | `downtime_cost` | Per unit time *this component* is down, even if the system is up (a degraded-mode or per-leg penalty). A number. | | Component | `acquisition_cost` | Once, to buy the unit. A number. Not a running cost: see [the total cost of ownership](#the-total-cost-of-ownership). | | System | `downtime_cost_rate=` | Per unit time the *system* is down (lost production). A number. | +| System | `crew_cost_rate=` | Per unit time per repair crew, busy or not (a salary), with `repair_crews=`. A number. See [paying the repair crews](#paying-the-repair-crews). | +| System | `call_out=` | A call-out crew's `"fee"` per call-out and `"rate"` per unit time engaged, with `repair_crews=`. See [a call-out crew](#a-call-out-crew). | + +Which cost is charged when, for a component: + +| When | Charged | +|---|---| +| It fails (a replacement or repair on failure) | `repair_cost` and `replace_cost`; for a component repaired imperfectly, `replace_cost` only when it is replaced. | +| A planned replacement (a `"preventive"` task) | The task's `"cost"`, not `replace_cost`. | +| An inspection of a `"condition"` policy | The task's `"inspection_cost"`. | +| A test of an `"inspection"` spec (hidden failures) | That spec's `"cost"`; a failure it finds is then charged `repair_cost` and `replace_cost`. | +| While it is down, for any reason | `downtime_cost` per unit time, and `downtime_cost_rate=` while the system is down too. | + +So a $4,000 planned replacement taking 8 hours is +`"preventive": {"policy": "age", "interval": ..., "cost": 4000.0, "duration": 8.0}` +(a number is a fixed time; a model of the time is given the same way), not +`replace_cost`, which a failure is charged. ```python import numpy as np @@ -49,6 +66,14 @@ plant = RepairableRBD( plant.has_costs # True ``` +The two downtime costs add up: a component's `downtime_cost` is charged +whenever it is down, and `downtime_cost_rate` whenever the system is, so +an hour a series component is down costs both. With +`"downtime_cost": 500.0` on a series pump and `downtime_cost_rate=1000.0`, +that hour costs 1,500. Price lost production in one place: put it in +`downtime_cost_rate`, and keep `downtime_cost` for what the component's +own outage costs (a hired stand-by unit, a penalty per leg). + Every cost defaults to 0, so any subset can be priced. Costs are undiscounted (but for the [total cost](#discounting)'s optional discount rate), and every failure is repaired at the same price (preventive @@ -87,6 +112,96 @@ With nothing priced, not even an [acquisition cost](#the-total-cost-of-ownership `routes.Refused`, a `ValueError`), as every analysis refuses a diagram with nothing it works on. +### Paying the repair crews + +With [limited repair crews](repairable.md#repair-crews), a crew more +shortens the queue for repairs, but it is paid whether it works or not. +`crew_cost_rate=` prices each of the `repair_crews` crews per unit time: +the crews cost `repair_crews · crew_cost_rate` per unit time from the +start, whatever happens, and every cost result shows it under the +category `"crews"`. Here a second crew saves less lost production than +its salary: + +```python +def crewed(crews): + return RepairableRBD( + edges, + { + "A": unit(0.1, 1.0, repair_cost=200.0), + "B": unit(0.1, 1.0, repair_cost=200.0), + "C": unit(0.02, 0.5, repair_cost=500.0, replace_cost=1500.0), + }, + downtime_cost_rate=1000.0, + repair_crews=crews, + crew_cost_rate=20.0, + ) + +crewed(1).expected_cost_rate() # -> 152.77 20.0 of it the crew's +crewed(2).expected_cost_rate() # -> 161.33 +``` + +Over a window `T` the crews cost `n c T`, and discounted at a rate `r`, +`n c (1 − exp(−r T)) / r`; a simulation adds the same amount to every +run: + +```python +crewed(1).expected_cost(100.0).by_category["crews"] # -> 2000.0 +crewed(1).expected_cost(100.0, discount_rate=0.05).by_category["crews"] # -> 397.30 +``` + +### A call-out crew + +A contract crew that comes only when repairs queue is paid only then. +`call_out={"when_waiting": k, "fee": f, "rate": c}` is one crew more: when +a job falls due, finds every crew busy and is the `k`-th waiting, the +call-out crew comes at once and starts the waiting job the next free crew +would have taken. While it is engaged there is a crew more. It leaves at +the first end of a job that leaves a crew with no waiting job to take +(the crews are alike: the job it has then, if any, is finished by the crew +that came free), and jobs that wait while it is engaged call no other. +Each call-out costs `f` and its time engaged `c` per unit time, under +`"crews"` with any salaries. + +With exponential lives and repairs the crews' Markov chain has the +call-out crew exactly, in the long run, over time and discounted; +otherwise the simulations follow the same rule (in Python). What a +contract is worth is the difference from the same system without it: + +```python +def on_call(call_out=None): + return RepairableRBD( + edges, + { + "A": unit(0.1, 1.0, repair_cost=200.0), + "B": unit(0.1, 1.0, repair_cost=200.0), + "C": unit(0.02, 0.5, repair_cost=500.0, replace_cost=1500.0), + }, + downtime_cost_rate=1000.0, + repair_crews=1, + call_out=call_out, + ) + +contract = {"when_waiting": 1, "fee": 300.0, "rate": 50.0} +on_call().expected_cost_rate() # -> 132.77 +on_call(contract).expected_cost_rate() # -> 129.69 the contract pays + +states = on_call(contract).crew_states() +float(states.probabilities @ states.call_out_rate) # -> 0.0254 call-outs per unit time +float(states.probabilities @ states.call_out_engaged) # -> 0.0148 of the time engaged + +with_it = on_call(contract).expected_npv(100.0, discount_rate=0.05) +without = on_call().expected_npv(100.0, discount_rate=0.05) +with_it.npv - without.npv # -> 37.74 the contract's value +with_it.cost_by_category["crews"] # -> 157.27 what it costs, discounted +``` + +`npv_distribution` prices simulated histories, which do not record the +call-outs: it refuses a call-out crew with a fee or a rate, and `cost()` +gives the spread of the undiscounted cost. + +A crew cost needs `repair_crews`: as many crews as are needed (the +default) cannot be priced, and the constructor refuses it. + ## The simulated cost distribution The exact rate is a mean. Budgeting usually needs the spread: what could a @@ -351,6 +466,146 @@ npv.cash_flows[3]["category"] # 'value' sum(row["present_value"] for row in npv.cash_flows) # -> 7448539.5 ``` +The average hides the risk: a plan with a slightly lower mean and a much +better worst case is often the one to choose. `npv_distribution(horizon, +discount_rate=, value_rate=, mc_samples=, seed=, hurdle=, tail=0.1)` +simulates the runs themselves (the histories of `simulate_timelines`, by +seed), prices each with the diagram's own costs at the times they fell, and +gives each run's net present value (`samples`) and their spread: `p10`, +`p50` and `p90`, the share of runs below a `hurdle`, and `cvar`, the mean of +the worst `tail` of the runs. Its `mean` estimates `expected_npv`'s, within +`mean_interval()`; `percentile_interval(q)` gives a percentile's confidence +interval by the binomial method. It works where the exact methods refuse +(crews with other lives, maintenance groups, opportunistic renewals at +shutdowns), as the simulation does. A shutdown's cost is charged at each of +its starts; a component it holds off line is not charged for the hold, and a +failure or renewal in the shut is charged as anywhere else. A +cost charged at an event the histories do not record (a standby group's +units' failures, tests, planned replacements that take no time, a set-up +cost, a calendar policy's prices) is not left out: the method refuses the +diagram, naming the cost. A cost given as a distribution is charged at its +mean (`priced_at_mean`). + +```python +runs = line.npv_distribution(87600.0, discount_rate=seven, value_rate=120.0, + mc_samples=10_000, seed=1, hurdle=7.4e6) +runs.mean # -> 7448443.9 expected_npv's 7448539.5, within mean_interval() +runs.p10, runs.p90 # -> (7417097.8, 7478039.2) +runs.probability_below_hurdle # -> 0.0268 +runs.cvar # -> 7404250.8 the worst tenth of the runs, on average +``` + +**Contracts that pay on availability.** An availability contract charges a +penalty for each point of availability below a target in each period, and +may pay a bonus for each point above it: a threshold, which an expected value +cannot price. `AvailabilityContract(periods, target, penalty_per_point, +bonus_per_point=0, cap=None)` states the terms (a point is one percentage +point; `cap` is the most a period can charge or pay), and +`npv_distribution(..., contract=)` pays them run by run, from the share of +each period the system was up in that run, at the period's end. The payments +are kept apart (`contract_samples`, `contract_payoff`), with each run's +availability by period (`period_availability`). + +**Comparing two plans.** A choice between plans is about the difference. +`compare_npv(other, horizon, ...)` runs both plans from one seed, a component +in the same place in both drawing the same random numbers (as `compare` +does), so each run's difference comes from how the plans differ rather than +from luck. Identical plans differ by exactly 0 in every run. Here a pump +repaired in 5 hours on average against one repaired in 10, under monthly +terms of 99%, over a year at 8%: + +```python +import math +import surpyval as surv +from repyability import AvailabilityContract, RepairableRBD + +def pump_line(mttr): + return RepairableRBD( + [("s", "p"), ("p", "t")], + {"p": {"reliability": surv.Exponential.from_params([1e-3]), + "repairability": surv.Exponential.from_params([1 / mttr]), + "repair_cost": 500.0}}, + ) + +terms = AvailabilityContract(730.0, target=0.99, penalty_per_point=1000.0, + bonus_per_point=100.0, cap=5000.0) +r = math.log(1.08) / 8760 +runs = pump_line(10.0).npv_distribution(8760.0, discount_rate=r, value_rate=10.0, + mc_samples=2000, seed=1, contract=terms) +runs.mean, runs.contract_payoff # -> (73784, -5546) penalties cost 5,546 on average +gain = pump_line(5.0).compare_npv(pump_line(10.0), 8760.0, discount_rate=r, + value_rate=10.0, contract=terms, + mc_samples=2000, seed=1) +gain.mean # -> 4767 the faster repair is worth this much more +gain.interval.lower, gain.interval.upper # -> (4656, 4879) +gain.interval.standard_error, gain.independent_standard_error # -> (56.9, 139.8) +gain.probability_other_better # -> 0.0005 +``` + +Two independent runs of the same size would have pinned the difference down +less than half as well (`independent_standard_error`). + +### Downtime you can be sure of + +"I want to be 95% sure I don't lose more than 100 hours to downtime this +year: what is the least I need to pay?" `least_spend_for_downtime` answers +that. A design meets the limit when an upper confidence bound on its +downtime's 95th percentile is under it: an order statistic, so that the +simulation's own noise cannot make a design look safe. The levers each +have their price (copies of a node at a price each, a node's maintenance +intervals at the cost of their tasks), and spend has no bound unless you +give `budget=`: + +```python +one_pump = RepairableRBD( + [("s", "p"), ("p", "t")], + {"p": {"reliability": surv.Exponential.from_params([1e-3]), + "repairability": surv.Exponential.from_params([0.02])}}, +) +sure = one_pump.least_spend_for_downtime(8760.0, 100.0, redundancy={"p": 5000.0}, + mc_samples=1000, seed=1) +sure.met, sure.design.copies, sure.design.spend # -> (True, {'p': 1}, 5000.0) +round(sure.design.estimate, 1), round(sure.design.bound, 1) # -> (80.6, 90.2) +round(sure.frontier[0].estimate) # -> 752 one pump's bad year, in hours +``` + +`frontier` lists the designs from the cheapest, each with its spend and +its bad-year downtime, so you see what each extra dollar buys. The +target is all system downtime by default; `downtime="unplanned"` counts +failures only, and `measure="cost"` prices each hour at the diagram's +`downtime_cost_rate` (and any `value_rate=` lost). Every design reports +both its `planned` and its `unplanned` downtime, the mean and the bad +year's, in hours and cost, so the trade-off shows. Cutting a wearing +unit's unplanned downtime with shorter intervals costs planned shutdown: + +```python +worn_unit = RepairableRBD( + [("s", "p"), ("p", "t")], + {"p": {"reliability": surv.Weibull.from_params([4000.0, 3.0]), + "repairability": surv.Exponential.from_params([1 / 72.0]), + "repair_cost": 2000.0, + "preventive": {"interval": 8000.0, "cost": 300.0, + "duration": surv.ExactEventTime.from_params([8.0])}}}, +) +pm_intervals = {"p": [4000.0, 2000.0, 1000.0, 500.0]} +trade = worn_unit.least_spend_for_downtime(8760.0, 10.0, downtime="unplanned", + intervals=pm_intervals, mc_samples=1000, + seed=3) +trade.design.intervals, round(trade.design.planned["bad_hours"]) # -> ({'p': 500.0}, 136) +[round(d.unplanned["bad_hours"]) for d in trade.frontier] # -> [347, 307, 183, 81, 0] +everything = worn_unit.least_spend_for_downtime(8760.0, 10.0, intervals=pm_intervals, + mc_samples=1000, seed=3) +everything.met, everything.floor # -> (False, 'planned') +``` + +No unplanned downtime in a bad year needs 136 hours of planned shutdown. +Counting all downtime, 10 hours cannot be reached by intervals, and the +result says which floor stopped the levers (`floor`, and `stopped` in +words): here the planned task downtime; otherwise the budget or the +levers' caps (`max_units`, the last interval). `objective="cvar"` targets +the mean of the worst 5% instead (its bound is normal, approximate). A +`UnitPlan` takes the same method, through its one-node diagram. + For one part replaced at an age or at a failure, over for ever, `NonRepairable.age_replacement_value(age, discount_rate=)` gives the net present value (Fox, 1966) and the equivalent annual cost in closed form. At a @@ -364,6 +619,94 @@ bearing.age_replacement_value(493.0).eac # -> 0.003462 bearing.age_replacement_value(493.0, discount_rate=seven).eac * 8760 # -> 30.3 ``` +### Upgrades, retirement and salvage + +"Is the upgrade worth it?" and "run it to the end, or retire it now?" are +questions a net present value answers. Three things say them: + +- **An upgrade** is on the component: `"upgrade": {"at": time, + "reliability": new_life, "cost": capital}`. From that time (in the + diagram's time from 0) its units have the new life: the unit in service + is replaced by one of it, in no time, and a unit in a repair then comes + back with it. The capital cost is charged at that time, whatever the + unit's state, under the category `"capital"`. +- **`retire_at=`** on `expected_npv` retires the system before the + horizon: nothing is earned or spent after it, and the equivalent annual + cost is over the time to it. +- **`salvage=`** credits what is left at the end (the retirement, or the + horizon), discounted from there: a number for the system, or a dict of + a number for each component; negative for a cost of disposal. The cash + flows show it under `"salvage"`, and the result's `salvage` is its + present value (`cost` stays the costs alone). + +```python +import math +import numpy as np +import surpyval as surv +from repyability import RepairableRBD + +def worn_pump(**more): + E = surv.Exponential.from_params + return RepairableRBD( + [("in", "pump"), ("pump", "out")], + {"pump": {"reliability": E([1 / 500.0]), + "repairability": E([1 / 50.0]), + "repair_cost": 2000.0, **more}}, + ) + +rate, horizon = math.log(1.08) / 8760.0, 8000.0 +kept = worn_pump().expected_npv(horizon, discount_rate=rate, value_rate=40.0) +kept.npv # -> 252977.9 +better = surv.Exponential.from_params([1 / 2000.0]) +upgraded = worn_pump( + upgrade={"at": 2000.0, "reliability": better, "cost": 30000.0} +).expected_npv(horizon, discount_rate=rate, value_rate=40.0) +upgraded.npv # -> 253936.5 +upgraded.cost_by_category["capital"] # -> 29477.5 +retired = worn_pump().expected_npv( + horizon, discount_rate=rate, value_rate=40.0, + retire_at=6000.0, salvage=8000.0, +) +retired.npv # -> 199015.8 +retired.salvage # -> 7589.2 +``` + +A component's salvage may depend on the age of its unit in service: give +a function of the age (taking an array of ages). Its expected value is +worked out from the age of the unit in service at the end, for a plain +component from new (one with maintenance, tests, an upgrade or a state at +0 takes a number, and says so); a unit down then is credited nothing. + +```python +by_age = worn_pump().expected_npv( + horizon, discount_rate=rate, value_rate=40.0, + salvage={"pump": lambda age: 8000.0 * np.exp(-age / 1000.0)}, +) +by_age.undiscounted_salvage # -> 4848.5 +``` + +An upgraded component's values over a horizon are worked out +(`point_availability`, `expected_events`, `expected_cost`, +`expected_npv`): its curve is followed to the upgrade with the old life +and from it with the new, as a [replacement at a given +time](system-maintenance.md#replacement-at-given-times) is. Once +upgraded, the component has the new life for ever, so the long-run +methods (`mean_availability`, `expected_cost_rate`, the importance +measures by default, ...) give the long run once upgraded: the values +of the diagram built with the new life, the time before the upgrade +ignored (`total_cost`, over a horizon from 0, refuses). The simulations follow it too (`availability`, `cost`, +`npv_distribution`, `compare_npv`, in Python): a life that starts at or +after the upgrade's time is drawn from the new model, from the same +random number the old one would have used, and the capital cost is +charged at its time. So `compare_npv` against keeping the old component +gives the upgrade's worth run by run, with its spread. An upgraded +component may also be under block replacement on its own interval +(`"preventive": {"policy": "block", ...}`): it is replaced every +interval with the life in service, and at the upgrade's time as at a +block time (at its cost and in its time, beside the capital cost). Age +replacement, tests and the other tasks are not taken with an upgrade +yet. + ### A plan against what happened Two years into a ten-year plan, the question changes: *how does what actually @@ -452,6 +795,32 @@ was used and what was read off the logs. A component missing from the logs is refused, never taken to have run without failing; one that never went down has `Timeline([], end=now)`. +### One call, as JSON + +An agent or a service asks an NPV question as one JSON document and gets +one back: `value_plan` takes the diagram as `to_dict()` saves it, the +analysis (`expected_npv`, `expected_npv_uncertainty`, `npv_distribution`, +`compare_npv` with the `"other"` plan, or `plan_vs_actual`) and its +inputs by name, in plain data, and answers with the request it answers, +the units, the route and the result's `to_dict()`, or the refusal and +what to run instead. The request is the record: valuing it again gives +the same answer (a seeded analysis given no seed has one written in). +`npv_schema()` gives the JSON Schema of both documents. + +```python +from repyability import value_plan + +answer = value_plan({ + "schema": 1, + "diagram": worn_pump().to_dict(), + "analysis": "expected_npv", + "inputs": {"horizon": horizon, "discount_rate": rate, + "value_rate": 40.0}, +}) +answer["route"]["route"] # -> 'exact' +value_plan(answer["request"]) == answer # -> True +``` + ### Buying redundancy A redundant copy is bought once and then runs: it fails, is repaired and @@ -476,6 +845,38 @@ hours. A third would save at most `100 · U² · (1 − U) = 0.0097` per hour, less than the 0.495 per hour its repairs cost, so it never pays, whatever it costs to buy. +Redundancy is a capital decision: the copies are bought now and what they +save comes later, so a `discount_rate` counts against them. And a plant +that is down loses what it would have earned, not only what the outage +costs. `objective="npv"` with a `value_rate` (what the system earns per +unit time while it works) chooses the design with the highest net present +value over the horizon, and gives the `npv`, its split into `value`, +`acquisition_cost` and `running_cost`, and the `eac` (the same as a steady +cost per unit time; `objective="eac"` chooses by it, which over one horizon +is the same design): + +```python +import math +hard = math.log(1.30) / 8760 # 30% a year, the models in hours +line.allocate_redundancy(87600.0, discount_rate=hard).units # {'pump': 1} +best = line.allocate_redundancy( + 87600.0, objective="npv", discount_rate=hard, value_rate=400.0 +) +best.units # {'pump': 2} an hour down now loses 500 +best.npv # -> 12314517.8 = value - acquisition_cost - running_cost +best.value # -> 12385481.5 +best.running_cost # -> 30963.7 +best.eac # -> -397.67 per hour: it earns more than it costs +``` + +A value earned while the system works is a cost of its downtime, so the +search is the same one, with an hour down costing `downtime_cost_rate + +value_rate`; with no value it gives the total cost's design. The running +costs, the downtime and the value are the long-run rates over the horizon's +present value, as `total_cost` counts them (the result's `basis` says so); +[`expected_npv`](#net-present-value) values a design from new, +with its availability over time. + The result is a [`TotalCostAllocation`][repyability.TotalCostAllocation]: `units`, `total_cost`, `acquisition_cost`, `cost_rate` (the running cost per unit time) and `availability` of the design, the `horizon` and the @@ -512,9 +913,29 @@ system's availability is theirs times the rest's, and a dynamic program over the nodes finds the optimum for any number of them; on other structures a branch and bound over the designs does, which suits a handful of nodes. -The model and its limits: copies are active and repaired independently of -each other (as many repair crews as failed copies), and fail independently -unless the component is in a common-cause group: then its copies join the +With limited [repair crews](repairable.md#repair-crews) a copy is one more +job that can wait for a crew: it can keep a crew from another component, +and a copy more can even leave the system down more. Each design is then +worked out whole, from the crews' Markov chain of its components and their +copies (exponential lives and repairs; a call-out crew and the crews' +salaries are counted), the chain counting how many of a component's alike +copies are up rather than telling them apart. The search keeps to what +still holds: no design is down less than with a crew for every job, and +every copy is bought. `"exact"` starts from the greedy design and solves +the chains of the designs that could still beat it by those two, the most +promising first; the result's `basis` says the designs came from the +crews' chain. A design it needs whose chain is too large (15,000 states) +is refused by name: bound the copies with `max_units`, or compare designs +with `compare()`. With crews, whole trains, common-cause groups, +maintenance groups and shutdowns are refused, and a node whose copies +cost nothing to buy needs a `max_units`. (The number of crews is not +chosen: compare the allocations for each. And with at least as many crews +as components, where no job waits, the copies are taken to have crews +too, as without `repair_crews`.) + +Otherwise the model and its limits: copies are active and repaired +independently of each other (as many repair crews as failed copies), and +fail independently unless the component is in a common-cause group: then its copies join the group, a `BetaFactor` group's shared cause failing them all (see [repairable systems](common-cause.md#repairable-systems); an `MGL` group's member is refused). Copies of a component with hidden failures are inspected together. A nested diff --git a/docs/guide/design.md b/docs/guide/design.md index 5fe67b7e..f08416d5 100644 --- a/docs/guide/design.md +++ b/docs/guide/design.md @@ -275,11 +275,19 @@ unsure.strategy["pump"] # 'cold' unsure.reliability # -> 0.955 ``` +A failed switch ends the arrangement. When a spare that fails to start +should be skipped and the next one tried instead, which is what a standby +block's `start_probability` means, give **`start_probability`** (a number, or +a dict by node) in its place: the search then scores each cold design as the +`StandbyModel(..., start_probability=...)` it fits, so the reliability it +reports is the diagram's once the design is applied. Give one or the other, +not both. Spares that may not start work with any number of units required. + Cold standby needs lifetime models (not fixed probabilities). Its reliability comes from `StandbyModel`: exact for identical Exponential units, a numerical convolution (accurate to about 1e-6) for one unit required, and simulated (seeded, so reproducible) otherwise; imperfect switching needs one unit -required. Each cold design is evaluated this way, which is slower than active +required (`start_probability` does not). Each cold design is evaluated this way, which is slower than active copies, so give cheap cold-standby nodes a `max_units`. A node without spares (only the copies it requires) is the same either way, and is reported as active. diff --git a/docs/guide/index.md b/docs/guide/index.md index a2a0773a..2744cce1 100644 --- a/docs/guide/index.md +++ b/docs/guide/index.md @@ -19,6 +19,7 @@ signature and docstring, see the [API reference](../api/index.md). | [Condition-based evaluation](condition-based.md) | Reliability, remaining life and importance given each component's current age, covariate-dependent components (fixed operating conditions or a load schedule), and a unit of a joint model of readings and failures, given its readings (surpyval `Measurements` too). | | [Redundancy models](redundancy-models.md) | Cold, warm and hot standby, repeated nodes, repeated standby, and load-sharing groups. | | [Common-cause failures](common-cause.md) | Beta-factor and Multiple Greek Letter groups, splitting a probability or a failure rate, in block diagrams, repairable systems (with staggered tests) and fault trees, and where they apply. | +| [Common causes with wear-out lives and ages](common-cause-ages.md) | A shock that fails members of any lives at their own ages, drawn as a node in series (a repeated node across branches), shocks that fail each member with a probability (`shock_nodes`), and a share of the hazard of members of one age, as a group splitting the failure rate given their state. | | [Repairable systems](repairable.md) | Long-run availability, failure frequency, MUT/MDT/MTBF; components operated part of the time, with tasks counted in running hours; the exact availability over time from new and over a mission, and the unavailability to its own precision; junctions; the simulated histories and their criticality measures; shared repair crews, with exact long-run values and importance and numerical values over time for exponential components; standby groups repaired one unit at a time; imperfect repair, and models fitted to a unit's repair history (Poisson processes, Kijima, G1, ARA and ARI); nested repairable RBDs, and stepping a simulation by hand. | | [System capacity](capacity.md) | How much a system can deliver: node capacities, components with several levels (derated, or degrading through stages over time), the exact distribution of the system's capacity at a time or in the long run, the probability of meeting a demand, the expected capacity, and the production availability. | | [Costs](costs.md) | The long-run cost rate in closed form, the simulated cost distribution, costs drawn from distributions, and the total cost of ownership, discounted to a present value, with the redundancy that minimises it, whole trains among it. | diff --git a/docs/guide/maintenance.md b/docs/guide/maintenance.md index b44144c4..24ee8d86 100644 --- a/docs/guide/maintenance.md +++ b/docs/guide/maintenance.md @@ -121,30 +121,42 @@ Age replacement has one planned price at every moment. In a plant, the price depends on the date: replacing a bearing in the annual shut costs little, in a quarterly shut more, at a weekly stop more again, on any other day more still (or it is not allowed), and at a failure most of all. -[`optimal_calendar_policy`][repyability.NonRepairable.optimal_calendar_policy] +[`optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy] finds the long-run optimal policy over such a calendar (opportunity-based age replacement, after Dekker et al.). The state is the date and the part's age, and the policy is a **threshold for each date**: replace the part if it is at least `a*(t)` old. -Times are numbers in the life model's unit (days here), from 0. Which dates a -rule gives is [`repyability.schedule`](schedule.md)'s. +The opportunities ([`Opportunities`][repyability.Opportunities] of +[`Opportunity`][repyability.Opportunity]) say when; the **prices come with +the part**, as one record of shuts serves every part: `planned_cost` on any +other day, `unplanned_cost` at a failure, `opportunity_cost` at an +opportunity (by default its `planned_cost`, as any other day), and +`opportunity_costs` for particular ones, by name or by the `Opportunity` +itself. Here, times are numbers in the life model's unit (days), from 0; +the same works on real dates (below). Which dates a rule gives is +[`repyability.schedule`](schedule.md)'s. ```python import surpyval as surv -from repyability import Calendar, NonRepairable, Opportunity +from repyability import NonRepairable, Opportunities, Opportunity -bearing = NonRepairable(surv.Weibull.from_params([1000.0, 2.5])) -plant = Calendar( +plant = Opportunities( [ - Opportunity("weekly", 3.0, period=7.0), - Opportunity("quarterly", 2.0, period=91.0), - Opportunity("annual", 1.0, period=364.0), + Opportunity("weekly", period=7.0), + Opportunity("quarterly", period=91.0), + Opportunity("annual", period=364.0), ], - failure=20.0, # by default the part's unplanned_cost - anytime=4.0, # any other day; None: not allowed; by default its planned_cost + any_day=True, # a planned replacement on any other day (the default) ) -policy = bearing.optimal_calendar_policy(plant) +bearing = NonRepairable( + surv.Weibull.from_params([1000.0, 2.5]), + planned_cost=4.0, # any other day + unplanned_cost=20.0, # a failure + opportunity_costs={"weekly": 3.0, "quarterly": 2.0, "annual": 1.0}, +) +policy = bearing.optimal_opportunity_policy(plant) +policy.prices.price("annual"), policy.prices.row("annual").source # -> (1.0, 'override') policy.cost_rate # -> 0.006943 a day (2.53 a year) policy.replacement_rates # a day; a year: annual 0.962, failure 0.078, @@ -159,8 +171,15 @@ policy.next_replacement(age=60.0, now=364.0) # -> PlannedReplacement(time=728.0, kind='annual', price=1.0) ``` -An [`Opportunity`][repyability.Opportunity] repeats every `period` from its -`offset`, or falls on given `dates`. +An [`Opportunity`][repyability.Opportunity] in model time repeats every +`period` from its `offset`, or falls on given `dates`. The policy's +`prices` ([`OpportunityPrices`][repyability.OpportunityPrices]) list the +price each opportunity was given and where it came from (an override, the +part's `opportunity_cost`, or its `planned_cost`), and any opportunity not +used: one shorter than the part's `job_duration` ("the 6 h job doesn't fit +in the 4 h stop"), or, with `where=`, one that does not take that label +down. (`Calendar`, with the prices on the opportunities, is deprecated; it +still works, and gives the same numbers.) - **What the policy does, and costs.** `replacement_rates` and `cost_rates` give, by kind, the replacements and the cost a unit of time in the long @@ -184,7 +203,7 @@ An [`Opportunity`][repyability.Opportunity] repeats every `period` from its The chart is drawn by `scripts/calendar_policy_chart.py`. The quarterly and annual thresholds, with what the simple policies cost over ten years of the -plant ([`calendar_policy_cost`][repyability.NonRepairable.calendar_policy_cost] +plant ([`opportunity_policy_cost`][repyability.NonRepairable.opportunity_policy_cost] prices a rule given as the age from which each kind of replacement replaces): | Policy | Rule | Cost over 10 years | @@ -214,8 +233,10 @@ prices a rule given as the age from which each kind of replacement replaces): over `mc_samples` sampled times of the cycle of a window's rate, each window an exact solve, with its standard error (`cost_rate_se`); the threshold at a time is a solve over a window from it, deterministic. Each window takes a - second or more, so `mc_samples` (64 by default) sets the cost, and - `"auto"` warns when it falls to sampling. A sampled policy's rates by kind + second or more, so `mc_samples` (64 by default) sets the cost. + `"auto"` still falls to sampling there, with a `FutureWarning`: from + 0.21 it refuses, naming a ready `horizon=` (the lowest total cost to + then, worked out exactly) and `method="sampling"`. A sampled policy's rates by kind (`replacement_rates`, `cost_rates`) and the schedule's chances are estimates from a new unit run in, with no standard error: only the cost rate has one, and the rates by kind move with the seed (by some 10% at @@ -250,16 +271,16 @@ it is followed as worked out, in a maintenance group too, whose stops are then chances to renew the part that the policy did not plan for: it is not re-optimised for them. -## Shutdown policies on real dates (`Shutdowns`) +## Shutdown policies on real dates A site keeps its shuts as rules on dates ("every Saturday", "the first Tuesday of November"), fixed dates (turnarounds), plain periods or a use -("every 15,000 km"). [`Shutdowns`][repyability.Shutdowns] holds them as **one record**: -each [`Shutdown`][repyability.Shutdown] with what replacing a part then -costs (and how long it lasts, for diagrams), the price of a planned -replacement on any other day (or none), and the site's time zone. A failure -always costs the part's own `unplanned_cost`. Given a site, -[`optimal_calendar_policy`][repyability.NonRepairable.optimal_calendar_policy] +("every 15,000 km"). [`Opportunities`][repyability.Opportunities] holds them as **one record**: +each [`Opportunity`][repyability.Opportunity] with when it happens, how long +it lasts and what it takes down, whether a planned replacement may be made +on any other day, and the site's time zone. Each part brings its prices, as +in model time. Given opportunities on real dates, +[`optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy] returns a [`ShutdownPolicy`][repyability.ShutdownPolicy] with the answer on the real dates and how it was worked out, by one of the routes it always names: @@ -269,7 +290,7 @@ names: | **exact** | The shuts repeat in the part's own clock on a short cycle (about a minute's work or less) | nothing | "Exact long-run average: $X a year." | | **long cycle** | They repeat, but only after a long cycle | `method="exact"` (slow, said beforehand) or `"sampling"` (with its ±) | "Estimated long-run average: $X a year ± $Y" | | **averaged** | They don't repeat (rules by month or year, a use on another meter) | `method="averaged"` | "Long-run average, assuming shuts fall evenly within their usual gaps (...)" | -| **horizon** | Any site | `horizon=` and `discount=` (0 for the plain total) | "Lowest net present cost to ... at 7% a year: $X. Decisions from about ... depend on where the horizon ends." | +| **horizon** | Any site; never refused | `horizon=` and `discount=` (0 for the plain total) | "Lowest net present cost to ... at 7% a year: $X (an equivalent annual cost of $Y a year). Decisions from about ... depend on where the horizon ends." | | **dated then long run** | Some shuts are on fixed dates (or you give `dated_until=`) | nothing more, or what the recurring shuts' long run needs (above) | "Dated window to 9 Sep 2028, then the long-run average: $X a year. ..." | **Fixed dates are never averaged.** Without a horizon, a site with fixed @@ -291,8 +312,17 @@ the recurring shuts' real dates until the window's decisions no longer change. Nothing is chosen silently: where a choice is needed, the call is refused -with what to choose, and -[`Shutdowns.route`][repyability.Shutdowns.route] says beforehand which +with what to choose, a ready horizon among it, worked out from the +inputs (with a discount, the day past which costs are discounted to under +one part in a billion: `horizon='2333-11-16'` at 7% from 16 Nov 2026; with +none, the full cycle and three of the part's life spans). With `discount=` +and no horizon, the answer is the exact discounted long run wherever the +shuts repeat, and a given rule (`opportunity_policy_cost`, `compare()`) +is priced the same way; shuts that drift on real dates, a duty plan or a +long cycle refuse with the ready horizon. In model time the same holds: +`horizon=` is a number in the calendar's own time, with `discount_rate=`. +And +[`Opportunities.route`][repyability.Opportunities.route] says beforehand which route, which solver (`"closed form"`, `"grid"`, `"quadrature"` or `"sampling"`) and about how long. Routes 1-3 give a cost a year, the horizon a net present cost (`measure`), so the two are never compared by accident. @@ -321,11 +351,14 @@ round(policy.cost_rate, 6) # -> 0.003462 a day plain period (a fixed length of time), so the stops repeat in the part's clock and the route is exact: +The bearing has no `opportunity_cost`, so a stop is priced as any other +day, at its `planned_cost` of 1: + ```python -from repyability import Shutdown, Shutdowns +from repyability import Opportunities, Opportunity -site = Shutdowns([Shutdown("monthly stop", every="30 days", replace_cost=1)]) -best = bearing.optimal_calendar_policy(site, unit="days") # the life's unit +site = Opportunities([Opportunity("monthly stop", every="30 days")], any_day=False) +best = bearing.optimal_opportunity_policy(site, unit="days") # the life's unit best.route # 'exact' best.rule.text # 'Replace at a monthly stop if older than 479.1 days; never on any other day (the site allows none).' round(best.cost, 3) # -> 1.265 a year @@ -340,21 +373,24 @@ dates into its clock: ```python from repyability.schedule import DutyPlan, Recurrence, Shifts -pump_bearing = NonRepairable(surv.Weibull.from_params([20_000, 2.5]), unplanned_cost=40.0) -plant = Shutdowns( +plant = Opportunities( [ - Shutdown("weekly stop", Recurrence.weekly("Sat"), replace_cost=3.0, duration="8h"), - Shutdown("quarterly shut", Recurrence.monthly(weekday="Sunday", nth=1, every=3, - anchor="2026-12-06"), - replace_cost=2.0, duration="1d"), - Shutdown("annual shut", Recurrence.yearly(month="November", weekday="Tuesday", nth=1), - replace_cost=1.0, duration="3d"), - Shutdown("turnaround", dates=["2027-03-03", "2028-09-09"], replace_cost=0.5, - duration="14d"), + Opportunity("weekly stop", Recurrence.weekly("Sat"), duration="8h"), + Opportunity("quarterly shut", Recurrence.monthly(weekday="Sunday", nth=1, every=3, + anchor="2026-12-06"), + duration="1d"), + Opportunity("annual shut", Recurrence.yearly(month="November", weekday="Tuesday", nth=1), + duration="3d"), + Opportunity("turnaround", dates=["2027-03-03", "2028-09-09"], duration="14d"), ], - any_day=4.0, time_zone="Australia/Brisbane", ) +pump_bearing = NonRepairable( + surv.Weibull.from_params([20_000, 2.5]), + planned_cost=4.0, unplanned_cost=40.0, + opportunity_costs={"weekly stop": 3.0, "quarterly shut": 2.0, + "annual shut": 1.0, "turnaround": 0.5}, +) shifts = DutyPlan(Shifts("Mon-Fri", "06:00", "22:00"), time_zone="Australia/Brisbane") plant.route(pump_bearing, plan=shifts, now="2026-11-16", unit="hours").route # 'horizon_or_averaged' ``` @@ -367,7 +403,7 @@ gaps (the turnarounds are never averaged): ```python when = dict(plan=shifts, now="2026-11-16", unit="hours", age=3100) -best = pump_bearing.optimal_calendar_policy(plant, method="averaged", **when) +best = pump_bearing.optimal_opportunity_policy(plant, method="averaged", **when) best.route # 'dated_then_long_run' best.solver, best.long_run_route # ('grid', 'averaged') round(best.cost, 2) # -> 1.9 a year, after the window @@ -385,13 +421,13 @@ turnaround on 3 Mar 2027 if older than 1,544 hours; at the turnaround on annual shut if older than 1,949 hours; ...". The long-run figure is the recurring shuts' own: the same site without the turnarounds gives $1.90 a year too. Were the turnarounds to go on every four years, -`Shutdown("turnaround", dates=[...], then_every="4 years", ...)` says so, +`Opportunity("turnaround", dates=[...], then_every="4 years", ...)` says so, and the result states "turnarounds after 9 Sep 2028 assumed every 4 years (your setting)". A horizon uses every date to its end and needs a discount: ```python -ten_years = pump_bearing.optimal_calendar_policy( +ten_years = pump_bearing.optimal_opportunity_policy( plant, horizon="2036-11-16", discount=0.07, **when ) ten_years.measure # 'net present cost' @@ -408,16 +444,18 @@ duty: the duty only turns the answers into dates. ```python from repyability.schedule import Rate, Usage -gearbox = NonRepairable(surv.Weibull.from_params([180_000, 2.2]), unplanned_cost=40_000) +gearbox = NonRepairable( + surv.Weibull.from_params([180_000, 2.2]), + planned_cost=14_000, unplanned_cost=40_000, opportunity_cost=9_000, +) truck = DutyPlan(Rate(400, per="day", meter="km")) -depot = Shutdowns( - [Shutdown("service", every=Usage(15_000, "km"), also_every="6 months", - replace_cost=9_000, duration="6h")], - any_day=14_000, +depot = Opportunities( + [Opportunity("service", every=Usage(15_000, "km"), also_every="6 months", + duration="6h")], ) road = dict(plan=truck, now="2026-11-16", readings={"km": 212_000}, unit="km") depot.route(gearbox, **road).route # 'exact' -service = gearbox.optimal_calendar_policy(depot, age=28_000, **road) +service = gearbox.optimal_opportunity_policy(depot, age=28_000, **road) service.rule.text # 'Replace at a service if older than 89,000 km; on any other day once older than 243,143 km.' str(service.next_replacement) # 'At the service, 17 May 2027, part 101,000 old' service.schedule("2027-12-31")[0] # ('2027-07-31', 'service', 103000.0) a gearbox fitted today @@ -435,20 +473,23 @@ flights = DutyPlan( per_run={"landings": 1}, # each sector is one landing time_zone="Australia/Brisbane", ) -base = Shutdowns( +base = Opportunities( [ - Shutdown("night stop", Recurrence.weekly("Mon-Sun"), at="21:00", - replace_cost=1_200, duration="7h"), - Shutdown("A-check", every=Usage(600, "hours"), replace_cost=800, duration="10h"), - Shutdown("C-check", every="2 years", replace_cost=300, duration="21d"), + Opportunity("night stop", Recurrence.weekly("Mon-Sun"), at="21:00", duration="7h"), + Opportunity("A-check", every=Usage(600, "hours"), duration="10h"), + Opportunity("C-check", every="2 years", duration="21d"), ], + any_day=False, time_zone="Australia/Brisbane", ) -brakes = NonRepairable(surv.Weibull.from_params([2_400, 3.0]), unplanned_cost=25_000) +brakes = NonRepairable( + surv.Weibull.from_params([2_400, 3.0]), unplanned_cost=25_000, + opportunity_costs={"night stop": 1_200, "A-check": 800, "C-check": 300}, +) fleet = dict(plan=flights, now="2026-11-16", unit="landings", readings={"landings": 8_410, "hours": 14_220}) base.route(brakes, **fleet).route # 'horizon_or_averaged' -brakes_policy = brakes.optimal_calendar_policy(base, method="averaged", **fleet) +brakes_policy = brakes.optimal_opportunity_policy(base, method="averaged", **fleet) brakes_policy.rule.text # 'Replace at a C-check if older than 124.6 landings; at an A-check if older than 440.5 landings; never at a night stop or on any other day (the site allows none).' ``` @@ -456,7 +497,7 @@ brakes_policy.rule.text # 'Replace at a C-check if older than 12 plain age replacement, and says so: ```python -anyday = bearing.optimal_calendar_policy(Shutdowns([], any_day=1), unit="days") +anyday = bearing.optimal_opportunity_policy(Opportunities(), unit="days") anyday.solver # 'closed form' round(anyday.rule.thresholds["any other day"][0], 2) # -> 493.05 round(anyday.cost_rate, 6) # -> 0.003462 @@ -473,10 +514,46 @@ choice.best # 'At the service, 18 Dec 2026' [str(o) for o in choice.options][:3] # ['Now', 'At the service, 18 Dec 2026', 'At the service, 25 Jan 2027'] ``` +**Example 8: one site, two parts, prices from the records.** The +opportunities are the site's; each part brings its own prices and the time +its job takes. An opportunity shorter than the job is not used for that +part, and the policy's `prices` say why. +[`NonRepairable.opportunity_prices`][repyability.NonRepairable.opportunity_prices] +works the prices out from what a replacement costs and how long the plant +is down for it (the downtime's cost is the system's, so it stays off the +part): at a stop the job fits in, the replacement alone; on any other day, +that and the downtime; at a failure, the failure's cost and its downtime. +`apply(part)` gives the part those prices. + +```python +site = Opportunities( + [ + Opportunity("weekly stop", Recurrence.weekly("Sat"), duration="8h"), + Opportunity("shift change", Recurrence.weekly("Mon-Fri"), at="14:00", duration="4h"), + ], + time_zone="Australia/Brisbane", +) +prices = NonRepairable.opportunity_prices( + site, replacement_cost=1_200, replacement_duration="6h", + failure_cost=4_200, failure_duration="18h", downtime_cost=2_500, +) +[(r.name, r.price) for r in prices.rows if r.used] +# -> [('weekly stop', 1200.0), ('any day', 16200.0), ('failure', 49200.0)] +prices.row("shift change").reason # "the 6 h job doesn't fit in the 4 h shift change" +pump = prices.apply(NonRepairable(surv.Weibull.from_params([8_000, 2.0]))) +seal = NonRepairable(surv.Weibull.from_params([3_000, 3.0]), planned_cost=300, + unplanned_cost=2_000, opportunity_cost=150, job_duration="2h") +for part in (pump, seal): + policy = part.optimal_opportunity_policy(site, now="2026-11-16", unit="hours") + print(policy.prices.unused, policy.prices.price("weekly stop")) +# ('shift change',) 1200.0 +# () 150.0 +``` + **Simpler rules, a rule's price, its spread, and diagrams.** `compare()` prices run to failure, age replacement on any day and every shut of each kind by the same route; -[`calendar_policy_cost`][repyability.NonRepairable.calendar_policy_cost] +[`opportunity_policy_cost`][repyability.NonRepairable.opportunity_policy_cost] with a site prices a rule you give and returns a [`RuleCost`][repyability.RuleCost] (cost, measure, route, replacements by kind). `cost_distribution(until=, policy=)` and `cost_by_window(dates, @@ -490,7 +567,7 @@ diagram's day 0, `now`). Change a shut's rule once, and both move. ```python rules = {c.name: round(c.cost) for c in service.compare()} rules["run to failure"], rules["every service"] # (36660, 89303) a year -priced = gearbox.calendar_policy_cost(depot, {"service": 89_000}, **road) +priced = gearbox.opportunity_policy_cost(depot, {"service": 89_000}, **road) priced.measure, round(priced.cost) # ('cost per year', 26113) ``` @@ -546,7 +623,7 @@ near its minimum, so the interval found varies more than the cost rate: ```python from surpyval.recurrent import GeneralizedRenewal -model = GeneralizedRenewal.fit_from_parameters( +model = GeneralizedRenewal.from_params( [1500, 2.0], q=0.4, kijima="i", dist=surv.Weibull ) compressor = Repairable(model) @@ -620,7 +697,7 @@ policy.cost_rate # -> 0.41626 Real plants often work in two levels. Failures are repaired on the spot, which leaves the unit as bad as it was. Every so often the unit is **overhauled**, which makes it younger but not new. After a few overhauls it is **replaced**, which clears the age the overhauls could not. The questions are how often to overhaul (`interval`) and how many periods to run before replacing (`cycles`). -The overhaul takes off a share of the unit's age: `overhaul_factor` is the share it *keeps*, from 0 (as good as new) up to, not including, 1 (no effect). The unit's failures follow a power-law or other intensity model (an analytic model, such as `CrowAMSAA`), and repairs, overhauls and replacements take no time: +The overhaul takes off a share of the unit's age: `overhaul_factor` is the share it *keeps*, from 0 (as good as new) up to, not including, 1 (no effect). The optimiser prices four plans, each at its best setting, and returns the cheapest: overhaul and replace after `cycles` periods; overhaul only, never replacing; replace only, with no overhauls; and repair each failure, replacing at a failure count. The unit's failures follow a power-law or other intensity model (an analytic model, such as `CrowAMSAA`), and repairs, overhauls and replacements take no time: ```python from surpyval.recurrent import CrowAMSAA @@ -634,12 +711,20 @@ pump.overhaul_replace_cost_rate(280.0, 1, 0.6, 20.0) # -> 0.1183 pump.overhaul_replace_cost_rate(177.7, 2, 0.6, 20.0) # -> 0.1172 best = pump.optimal_overhaul_replace_policy(0.6, 20.0, max_cycles=5) -best.interval, best.cycles # -> (177.70161320528848, 2) +best.plan, best.interval, best.cycles # -> ('overhaul only', 73.79..., inf) +best.cost_rate, best.saving # -> 0.1129..., 0.0028... +best.alternatives["overhaul and replace"]["cost_rate"] # -> 0.1172... + +# An overhaul that takes off only 10% of the age: replacing pays. +small = pump.optimal_overhaul_replace_policy(0.9, 20.0, max_cycles=5) +small.plan, small.failure_count # -> ('failure limit', 13) ``` +Here an overhaul every 74 that is never followed by a replacement is the cheapest plan, about 3.7% cheaper than overhauling every 178 and replacing every second period. An overhaul that keeps part of the age lets it build up only to a ceiling, `v* = f·T / (1 − f)` at the start of each period (where an overhaul takes off what the period added), so the long-run cost rate of never replacing is `(cr·[Λ(v* + T) − Λ(v*)] + co) / T`; an expensive replacement then rarely pays. When the overhaul does little, replacing does pay, and here replacing at the 13th failure beats replacing on a schedule. `plan` names the winner, `alternatives` holds every plan's cost rate and settings, and `saving` is how much less per unit time the winner costs than the next best. + Behind the numbers: period `j` starts at the age `v` the overhauls have left (`v_0 = 0`, `v_j = f (v_(j-1) + T)` for the share `f` kept), and expects `Λ(v + T) − Λ(v)` failures, `Λ` being the model's cumulative intensity. A replacement cycle of `K` periods then costs `cr` times the repairs, plus `(K − 1)` overhauls and one replacement, and lasts `K·T`; the long-run cost rate is that cost over that length. It is exact, with no simulation. With one period (`cycles=1`) it is the periodic replacement of `optimal_overhaul_policy`, at the replacement cost. -Take the result as a comparison of a few policies, not a sharp optimum. The cost rate is flat, here the best of two periods saves about 1% over replacing every 280, and it need not fall steadily with the number of periods: it can have a local minimum at a few periods and a slightly lower value at many (overhaul for ever, never replace). A result equal to `max_cycles` may mean more periods pay, so try a few limits. A unit that does not wear out is never overhauled (`interval` is `inf`, `cycles` is 1). The result is an [`OverhaulReplacePolicy`][repyability.OverhaulReplacePolicy]. It needs an analytic (`cif`) model: a simulation-backed imperfect-repair model counts failures from new only and is refused. +Take the result as a comparison of a few policies, not a sharp optimum: the cost rates are flat near their minima. The overhaul-and-replace rate need not fall steadily with the number of periods; `cycles_limit_reached` says its best used `max_cycles`, so more periods might pay (they tend towards overhauling only, which is priced anyway). The failure limit searches up to `max_failures` (default 30). A unit that does not wear out is run to failure (`plan` is `"run to failure"`, `interval` is `inf`, `cycles` is 1). The result is an [`OverhaulReplacePolicy`][repyability.OverhaulReplacePolicy]. It needs an analytic (`cif`) model: a simulation-backed imperfect-repair model counts failures from new only and is refused. ## Repair again or replace? A fleet with lemons (`RepairOrReplace`) @@ -887,18 +972,20 @@ counts are worked out as for one window from now. Under block replacement each window's planned replacements are known. **Under a calendar policy.** Both take `calendar=`, the `CalendarPolicy` -of [`optimal_calendar_policy`](#replacement-over-a-calendar-of-shuts-nonrepairable) +of [`optimal_opportunity_policy`](#replacement-over-a-calendar-of-shuts-nonrepairable) worked out for the part, in place of `every` and `resets`: at each opportunity the part is replaced if it is at least that time's threshold age, at that opportunity's price, and a failure costs the part's `unplanned_cost`. The calendar's times are counted from now. Here, UC-7's -best policy for the bearing, with a shut every 180 days, the next in 21: +best policy for the bearing, with a shut every 180 days, the next in 21 +(the bearing has no `opportunity_cost`, so a shut costs its +`planned_cost`, 100): ```python -from repyability import Calendar, Opportunity +from repyability import Opportunities, Opportunity -plant = Calendar([Opportunity("shut", 100.0, period=180.0, offset=21.0)], anytime=None) -best = bearing.optimal_calendar_policy(plant) +plant = Opportunities([Opportunity("shut", period=180.0, offset=21.0)], any_day=False) +best = bearing.optimal_opportunity_policy(plant) best.schedule()[0][1:3] # -> ('shut', 138.0) spend = bearing.cost_distribution(1086.0, calendar=best, age=224.0, budget=1500.0) round(spend.mean, 1), [float(c) for c in spend.percentiles] # -> (1090.0, [600.0, 1000.0, 1600.0]) @@ -953,7 +1040,7 @@ exact, in the part's time unit. ```python from repyability import ( - NonRepairable, failure_finding, on_condition, + NonRepairable, failure_finding, failure_finding_window, on_condition, optimal_failure_finding_interval, run_to_failure, scheduled_replacement, ) @@ -979,6 +1066,31 @@ optimal_failure_finding_interval(valve, target_unavailability=0.001).interval # Without a target, `optimal_failure_finding_interval` takes the test, repair and consequence costs and the demand rate, and finds the cheapest interval. +Those are long-run numbers for one even interval. `failure_finding_window` +takes the tests at any times, a device that is not new, and a window: what +each test finds, how long the device is failed, and what the plan costs, +with a discount rate if you give one. An empty list of times is a device +never tested. + +```python +trip = NonRepairable(surv.Exponential.from_params([0.1])) # per year +prices = dict(demand_rate=0.5, repair_cost=1500.0, consequence_cost=50_000.0) +tested = failure_finding_window(trip, [0.5, 1.0, 2.0], 3.0, test_cost=200.0, **prices) +round(tested.mean_unavailability, 4) # -> 0.0351 +round(tested.cost, 2) # -> 3555.15 +never = failure_finding_window(trip, [], 3.0, **prices) +round(never.cost, 2) # -> 6904.57 +``` + +Here a demand that meets the device failed costs the consequence and also +shows the failure, which is repaired then (`demands_reveal=True`, the +default). That is why "never tested" has a finite cost. With +`demands_reveal=False` only a test finds a failure, as `failure_finding` +has it, and even tests over a long window give its numbers. Where a demand +shows a failure the answer is numerical, and `precision` says how close. +For tests on real dates, see +[Is a test of a hidden failure worth it?](schedule.md#is-a-test-of-a-hidden-failure-worth-it). + **On condition** is for a failure that gives warning: the P-F interval is the time from the warning to the failure. Inspect every so often, finding the warning with some probability each time: diff --git a/docs/guide/repairable.md b/docs/guide/repairable.md index 1f62b1af..868c50a8 100644 --- a/docs/guide/repairable.md +++ b/docs/guide/repairable.md @@ -831,6 +831,14 @@ birth-death chain, and the system is down when all three are.) for no time: it waits only when every crew is busy. - **Nested RBDs** have crews of their own: a nested `RepairableRBD`'s components are repaired by its `repair_crews`, not by its parent's. +- **What the crews cost.** `crew_cost_rate=` pays each crew per unit time, + busy or not, in every cost result under `"crews"` (see + [paying the repair crews](costs.md#paying-the-repair-crews)). +- **A call-out crew.** `call_out={"when_waiting": k, "fee": f, "rate": c}` + is one crew more that comes when a job is the `k`-th waiting and leaves + at the first end of a job that leaves a crew with none to take, at a fee + each time and a rate while engaged; the chain below and the simulations + have it (see [a call-out crew](costs.md#a-call-out-crew)). - **Exact long-run values.** With fewer crews than components, components wait for each other, so they no longer fail and recover independently. When the components the crews work on all have exponential lives and @@ -842,7 +850,11 @@ birth-death chain, and the system is down when all three are.) `mean_time_between_failures`, `expected_cost_rate`, `total_cost` and `capacity_distribution` solve it exactly, for up to 15,000 states. A component held working or broken (`working_nodes`, `broken_nodes`) needs - no crew, and the others share them. + no crew, and the others share them. The chain takes + [common-cause groups](common-cause.md) in too: a shared cause fails the + members it names that are up at once, and they join the queue in the + group's order (causes that strike two members; more refuse, for the + simulation). - **Over time.** From new, or from the components' states, the same chain is followed over time by uniformization: its state after a Poisson number of steps of a discrete chain, taken until it has settled at its @@ -867,8 +879,10 @@ birth-death chain, and the system is down when all three are.) they are the independent ones. - **What is simulated.** Other lives or repair times, scheduled maintenance and inspections, and larger chains make the exact values refuse, with the - reason. The allocations assume independent components, so they refuse - whenever a job can wait. The simulations (`availability`, `cost`, + reason. The allocations of availability targets assume independent + components, so they refuse whenever a job can wait; + `allocate_redundancy` works each design out from the chain, its copies + queueing with the rest (see [Costs](costs.md#buying-redundancy)). The simulations (`availability`, `cost`, `compare`) follow the queue whatever the components, in Python. With at least as many crews as components, nothing waits, and every result is as without crews. @@ -1037,7 +1051,7 @@ maintenance replaces it (a partial `"restoration"` is refused). ```python from surpyval import ARA -pump = ARA.fit_from_parameters([1000, 2.0], 0.5) +pump = ARA.from_params([1000, 2.0], 0.5) rbd = RepairableRBD([("s", "p"), ("p", "t")], {"p": {"reliability": pump, "repairability": "instant"}}) run = rbd.availability(t_simulation=5000.0, mc_samples=1000, seed=1) diff --git a/docs/guide/saving.md b/docs/guide/saving.md index d5521b52..bcbaa43a 100644 --- a/docs/guide/saving.md +++ b/docs/guide/saving.md @@ -34,7 +34,7 @@ path = Path(tempfile.mkdtemp()) / "plant.json" rbd.to_json(path) # written; returns None NonRepairableRBD.from_json(path).sf(30) == rbd.sf(30) # True type(RBD.from_dict(data)).__name__ # 'NonRepairableRBD': the base class dispatches on type -data["type"], data["repyability_version"] # ('NonRepairableRBD', '0.19.1') +data["type"], data["repyability_version"] # ('NonRepairableRBD', '0.20') ``` What is saved: diff --git a/docs/guide/schedule.md b/docs/guide/schedule.md index b4c90152..1af025af 100644 --- a/docs/guide/schedule.md +++ b/docs/guide/schedule.md @@ -8,7 +8,9 @@ calendar. This page covers the first part: **which dates a rule gives** map between dates and operating hours it gives (`UsageForecast`), which puts tasks counted in running hours on dates; and, through that map, **failures, events and shuts on the calendar** (`failures_by_period`, -`events_by_period`, `shutdown_spec`, `Opportunity.from_recurrence`). +`events_by_period`, `shutdown_spec`, `Opportunity.from_recurrence`), +and what a task is worth against not doing it (`task_value`): a +replacement, or a test that finds a hidden failure. The module computes and stores nothing. You pass it dates, rules and what you know (when a task was last done); it never reads the clock. Dates are @@ -213,6 +215,48 @@ work.hours # (4.5, 10.0, 6.0, 6.0) work.cost # (360.0, 960.0, 480.0, 480.0) ``` +## Present values: `discount=` + +Give a yearly discount rate and the forecasts return present values +beside the plain totals. `discount=0.07` is 7% a year, the effective +yearly rate (the convention of the dated replacement policies): an +amount `y` years after the first date is worth `1 / 1.07 ** y` of +itself, with a year of 365.25 days. Money is discounted to the +forecast's first date, which is your "today". With no `discount`, +nothing changes. + +A $250 task every 30 days from 20 November 2026, over its first year: + +```python +grease = Task("grease bearings", + every=Recurrence.every(30, "days", "2026-11-20"), cost=250.0) +year = grease.due("2026-11-20", "2027-11-19", discount=0.07) +year.count # -> 13 +year.cost # -> 3250 +round(year.npv, 2) # -> 3144.10 +``` + +Each task is discounted from the date it is done (after its visit, if +it waits for one). `eac` is the equivalent annual cost: the steady cost +a year over the period that is worth the same. `work_by_period(..., +discount=0.07)` gives each period's `npv`, with `total_npv` and `eac`. + +`long_run_value` is what the task is worth repeating for ever: + +```python +value = grease.long_run_value("2026-11-20", 0.07) +round(value.npv) # -> 45112 +value.method # 'closed form' +``` + +A plain interval of days or weeks is a geometric sum, `250 / (1 - 1.07 +** (-30 / 365.25))`. Any other task (the first Tuesday of the month, a +task that waits for visits, two limits) is summed date by date until +what is left cannot matter: `precision` is the most the dates left out +could add, and `summed_to` the last date summed. It refuses, saying what +to run, where there is no such value: at `discount=0`, for given dates +(they end), and for a limit by use (its usage forecast ends). + ## Duty plans: operating hours on dates A life fitted in operating hours, or a task every 2,000 running hours, @@ -455,6 +499,23 @@ outcomes). Month by month the numbers are small, about 0.05 failures [round(float(c)) for c in months.expected_cost[:3]] # [105, 227, 217] ``` +With `discount=`, each period also has its expected cost as a present +value. An expected cost accrues as the part runs, and each part of it is +discounted from when it is expected to fall: an integral over the +forecast, worked out until its error estimate is small. `npv_precision` +is that estimate plus how far the expected cost itself can be from the +true one (the expected failures are worked out on a grid). + +```python +worth = failures_by_period(ring, usage, "month", age=5200.0, discount=0.07) +round(worth.npv) # -> 2883 +worth.npv_precision < 0.001 * worth.npv # True +``` + +`npv_tolerance` (0.001 by default) sets how small `npv_precision` must +be, as a share of `npv`. `expected_cost` and the ranges +stay undiscounted: the present values are `expected_npv` and `npv`. + One part rarely fails in a given month, so the monthly figures become useful once you add them up over many positions. The expected values add up; the ranges do not, so `total` gives the whole forecast's own @@ -471,6 +532,144 @@ starts. The model's unit comes from its label (`unit="h"` on the surpyval model), or from `unit=`. With neither, it is taken as hours and the notes say so. +### Is a replacement task worth it? + +A task's cost is only worth paying for what it prevents. `task_value` +values a task against not doing it: the part's cost with the task, without +it, and the difference, by period. Say every 6-monthly service fits a new +wear ring for $600: + +```python +from repyability.schedule import Recurrence, Replaces, Task, task_value + +new_ring = Task("new wear ring", + every=Recurrence.every(6, "months", "2026-12-01"), cost=600.0) +worth = task_value(new_ring, Replaces(ring), usage, age=5200.0, discount=0.07) +[str(d) for d in worth.dates] # ['2026-12-01', '2027-06-01'] +round(worth.total["with_task"]) # -> 1517 +round(worth.total["without_task"]) # -> 2883 +round(worth.total["value"]) # -> 1366 +round(worth.total["failures_avoided"], 3) # -> 0.549 +``` + +`Replaces(ring)` says what the task does: it puts a new ring in every +time it is done, whatever the ring's age. A failure in between is +replaced too and does not move the service dates. Without the task, the +ring runs to failure from the same age over the same dates (`with_words` +and `without_words` say so). `value` is `without_task - with_task`, so a +positive value means the task pays. Here it does: the ring is old, and +the first service replaces it in two weeks. Each failure's cost is +discounted as `failures_by_period` discounts it, and `precision` is how +far the value can be from the true one; the task's own cost is +discounted from the day it is done. With no `discount` the numbers are +plain expected costs ($1,550.82 against $2,987.56). + +The task's `cost` is the planned ring's price. A task with no cost takes +the part's `planned_cost`. If both are given and differ, the call is +refused, naming the two numbers. A task by use (`every=Usage(2000, +"hours")`) is done when the meter reaches its reading. + +### Is a test of a hidden failure worth it? + +A test of a protective device (a trip, a relief valve, a standby pump's +start) replaces nothing and prevents no failure. What it buys is time: a +device that has failed without anyone knowing is found and repaired at +the next test, instead of sitting failed until it is needed. `Finds` +says that is what the task does. Say a trip fails hidden at 0.1 a year +and is tested every 6 months at $400; a repair costs $3,000; the event +it protects against comes once in 2 years and costs $250,000 if the trip +is failed then: + +```python +from repyability.schedule import Finds, UsageForecast + +trip = NonRepairable(surv.Exponential.from_params([0.1])) # per year +trip_test = Task("trip test", + every=Recurrence.every(6, "months", "2027-01-01"), cost=400.0) +years = UsageForecast.calendar("2026-11-16", "2029-11-16") +does = Finds(trip, demand_rate=0.5, consequence_cost=250_000.0, + repair_cost=3_000.0) +tested = task_value(trip_test, does, years, unit="years", discount=0.07) +round(tested.total["found"], 3) # -> 0.228 +round(tested.total["unavailability_with"], 4) # -> 0.0213 +round(tested.total["unavailability_without"], 4) # -> 0.0894 +round(tested.total["failures_avoided"], 3) # -> 0.102 +round(tested.total["value"], -2) # -> 19800.0 +``` + +The trip's life is in calendar years, so the forecast is +`UsageForecast.calendar` and `unit="years"`; a device whose life is in +running hours takes a duty plan's forecast, and demands then come only +while it runs (`demand_rate` is per unit of the device's own time). With +the task, the cost is the tests, the repairs of what they find, and the +demands that meet the trip failed. Without it the trip is never tested. +The result's "failures" are those demands: here the tests avoid about +0.1 of them over three years, and are worth about $19,800 today. +`found` is the failures the tests find, and `unavailability_with` and +`unavailability_without` are the trip's mean unavailability in each +period (and over the whole forecast in `total`). + +By default, a demand that meets the device failed also shows the +failure, which is repaired then. That is what happens without the task, +too: a failure stays until a demand finds it. With +`demands_reveal=False`, only a test finds a failure, as +[`failure_finding`](maintenance.md) has it, so never tested, a failure +is for good. Tests and repairs take no time, a test never misses, and +the device is taken to be working when the forecast starts. The task's +`cost` is one test's. `precision` includes the error of the numerical +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 @@ -494,7 +693,12 @@ round(float(by_month.events.system_failures[0]), 3) # -> 0.372 `events` holds `expected_events_by_window`'s answer, which is exact. `cost=True` adds `cost_by_window`: each period's mean cost is exact, and -its range is simulated. +its range is simulated. With `cost=True, discount=0.07` each period also +has `expected_npv`, its expected cost as a present value, with `npv` and +`eac`; `cost` (its mean and range) stays the cost as it falls, not +discounted, as `failures_by_period`'s `expected_cost` does. This is exact: the diagram's clock is calendar time, so the +yearly rate is one continuous rate on it, which +`RepairableRBD.expected_cost(discount_rate=)` takes. ### Shuts on dates @@ -527,10 +731,11 @@ spec = shutdown_spec(overhaul, "2026-11-14", "2029-12-31", duration=48.0, at="06 spec["times"] # [8478.0, 17382.0, 26118.0] ``` -`RepairableRBD(..., shutdowns={"overhaul": spec})` takes it. Its -simulations (`cost()`, `availability()`) handle shuts at given times. -The exact methods, and so `events_by_period`, take shuts on a period -only, and refuse such a diagram with a message that says so. +`RepairableRBD(..., shutdowns={"overhaul": spec})` takes it. Shuts at +given times are valued over a horizon, exactly where the blocks worked +on in them are renewed (`expected_npv`, `expected_cost`), and simulated +(`cost()`, `availability()`); they end, so the long-run methods refuse +such a diagram with a message that says so. ### Two clocks diff --git a/docs/guide/system-maintenance.md b/docs/guide/system-maintenance.md index 6e62e68f..ccce508e 100644 --- a/docs/guide/system-maintenance.md +++ b/docs/guide/system-maintenance.md @@ -22,7 +22,7 @@ between preventive and corrective maintenance: |---|---| | `interval` | Required (but under `"calendar"`): the replacement interval `T` (`inf`: never). | | `policy` | `"age"` (the default): `T` after the unit was last put into service as new, so a failure restarts the clock. `"block"`: at `T, 2T, 3T, …` whatever the unit's age, skipped while it is down. `"condition"`: inspected at `T, 2T, 3T, …`, and replaced if likely to fail before the next inspection (see [below](#replacement-on-condition)). `"calendar"`: at the first time the unit's age reaches a calendar policy's threshold (see [below](#replacement-on-a-calendar-policy)). | -| `calendar` | Under `"calendar"`: the [`CalendarPolicy`][repyability.CalendarPolicy] of [`NonRepairable.optimal_calendar_policy`][repyability.NonRepairable.optimal_calendar_policy]. | +| `calendar` | Under `"calendar"`: the [`CalendarPolicy`][repyability.CalendarPolicy] of [`NonRepairable.optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy]. | | `duration` | `"instant"` (the default): renewed in place, never down. Or a time-to-maintain model: the unit is down meanwhile, a *planned outage*. | | `cost` | Charged at each preventive replacement: a number or a distribution (under `"calendar"`, none: the calendar's price is charged). | | `restoration` | The task restores the unit only partly: Kijima's model and restoration factor `q` (see [below](#planned-maintenance-that-restores-partly)). Left out, each task renews the unit. | @@ -142,6 +142,46 @@ they take the system down together its first years cost more than the plan's rate: `expected_cost` gives the cost from new, and from units of other ages (`state`) the cost of a staggered start. +At a discount rate, money spent later is worth less now, so a replacement +put off is worth something. `objective="eac"` chooses the intervals for the +lowest equivalent annual cost in the long run: the steady cost per unit time +worth the same, at `discount_rate` (a continuous rate per unit of the +models' time), as running the diagram for ever from new, less `value_rate` +for the time it works. Each component's own costs are discounted over its +renewal cycle, exactly (Fox, 1966), as +`NonRepairable.optimal_replacement_policy(discount_rate=)` discounts one +unit's; the cost of the system's downtime and the value it earns are taken +at its long-run availability, which the plan's `basis` says. At a rate of 0 +it is the cost rate, and the plan is the same: + +```python +import math +a_year = math.log(1.10) / 8760 # 10% a year, the models in hours +plan = with_standby(1000).optimal_replacement_intervals( + objective="eac", discount_rate=a_year +) +plan.intervals["a"] # -> 497.5 against 497.1 undiscounted +plan.objective_value # -> 6.972 the equivalent annual cost, per hour +plan = with_standby(1000).optimal_replacement_intervals( + objective="eac", discount_rate=20 * a_year +) +plan.intervals["a"] # -> 504.7 a rate 20 times as high +``` + +`objective="npv"` chooses them for the highest expected net present value +over a `horizon` from new ([`expected_npv`][repyability.RepairableRBD.expected_npv]), +which follows the system's availability over time, so nothing in it is +approximate. It takes each plan's curves over the horizon, so it is much +slower, and what a plan is worth over a horizon has a local best wherever a +replacement falls just inside it or just outside: without `allowed` the +search is a local one from the long run's best plan, and with `allowed` +every combination is valued. The targets (`min_availability`, +`max_cost_rate`) are kept with either objective: they bound the long-run +values, and the objective is the best within them. A diagram with a priced +component that has no renewal cycle of its own worked out (a standby group, +block replacement, a common-cause group, a unit whose tests or repairs take +time) refuses `"eac"` at a discount rate, and names `"npv"`. + With limited `repair_crews` a component can wait for a crew, and the exact long-run values the search uses no longer hold, so the choice is refused. `assume_unlimited_crews=True` (#184) chooses the intervals as if every repair @@ -215,25 +255,95 @@ year.system_planned_outages / year.n_simulations # -> 11.95 year.cost.by_category["preventive"] # -> 11886.8 1000 each, expected ``` +### Replacement at given times + +A real plan is often a list of jobs at times rather than one interval: +this pump is replaced at 8,000, 14,000 and 26,000 hours. Give the times as +`"replace_at"`, in the diagram's time from 0, in place of an `"interval"`. +It is block replacement at those times: the unit is replaced at each if it +is up there (a replacement due while it is down is skipped), with the +task's `"cost"` and `"duration"`, and after the last time it is replaced +no more. + +```python +import numpy as np +import surpyval as surv +from repyability import RepairableRBD + +hours = 8760.0 +planned = RepairableRBD( + [("in", "pump"), ("pump", "motor"), ("motor", "out")], + { + "pump": { + "reliability": surv.Weibull.from_params([12_000, 2.5]), + "repairability": surv.LogNormal.from_params([3.5, 0.6]), + "repair_cost": 9_000.0, + "preventive": { + "replace_at": [8_000.0, 14_000.0, 26_000.0], + "duration": surv.LogNormal.from_params([2.5, 0.3]), + "cost": 3_000.0, + }, + }, + "motor": { + "reliability": surv.Weibull.from_params([40_000, 1.5]), + "repairability": surv.LogNormal.from_params([4.0, 0.5]), + "repair_cost": 15_000.0, + }, + }, + downtime_cost_rate=400.0, +) +four_years = 4 * hours +planned.mission_availability(four_years) # -> 0.99588 +planned.expected_events(four_years).node_preventive["pump"] # -> 2.990 +planned.expected_cost(four_years).mean # -> 91650.6 +worth = planned.expected_npv( + four_years, discount_rate=np.log(1.08) / hours, periods=4 +) +worth.cost # -> 77679.1 +``` + +The values over a horizon are worked out, not simulated +(`point_availability`, `mission_availability`, `expected_events`, +`expected_cost`, `expected_npv` and what is built on them): the unit is +followed stretch by stretch, from one time of the plan to the next, each +stretch starting with the replacement of the unit if it is up and the +repairs still going on, as under block replacement on a period, and to the +same precision. Each replacement is an event at its exact time, counted +and discounted there. Equally spaced times give block replacement's +values over the same horizon. From a state (`state=`), the times are +counted from now, and the unit's own curve runs to the first of them. + +A plan ends, so a diagram with one has no long run: `mean_availability`, +`expected_cost_rate` and the other long-run methods refuse, saying to ask +for a horizon or to give the component an interval, as do the spares +counts and `plan_vs_actual` (whose rest from today would count the times +again), each saying what to run instead. The simulations replace at the +times too (in Python: a compiled engine leaves a plan to it). Each time +is a lever (`preventive.replace_at.0`, ...), between the times either +side of it, so `parameter_sensitivity(window=...)` says what moving a +replacement is worth. A stretch far shorter than the unit's repairs +cannot be followed on its grid and refuses, pointing to the simulation. + ### Replacement on a calendar policy A part whose replacement costs differently at different times (cheap in a shut, dearer on any other day) is best replaced on a threshold for each -time: the policy [`NonRepairable.optimal_calendar_policy`][repyability.NonRepairable.optimal_calendar_policy] +time: the policy [`NonRepairable.optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy] works out (see [Maintenance policies](maintenance.md#replacement-over-a-calendar-of-shuts-nonrepairable)). Give it to the component, and the simulation replaces each unit at the first time its age reaches the threshold, charging the calendar's price there; a failure is charged the component's own `replace_cost`: ```python -from repyability import Calendar, NonRepairable, Opportunity +from repyability import NonRepairable, Opportunities, Opportunity life = surv.Weibull.from_params([1000.0, 2.5]) -plant = Calendar( - [Opportunity("quarterly", 2.0, period=91.0), Opportunity("annual", 1.0, period=364.0)], - failure=20.0, anytime=4.0, +plant = Opportunities([Opportunity("quarterly", period=91.0), Opportunity("annual", period=364.0)]) +part = NonRepairable( + life, planned_cost=4.0, unplanned_cost=20.0, + opportunity_costs={"quarterly": 2.0, "annual": 1.0}, ) -policy = NonRepairable(life).optimal_calendar_policy(plant) +policy = part.optimal_opportunity_policy(plant) rbd = RepairableRBD( [("s", "bearing"), ("bearing", "t")], {"bearing": { @@ -614,11 +724,31 @@ interval is chosen by simulating each, with one seed: state, the simulations take its `virtual_age` at its last action and its `age` since (and `since_scheduled` on a calendar), but not with `replace_every`, whose count a state does not give. `q` is a lever - (`preventive.restoration.q`, from 0 to 1). + (`preventive.restoration.q`, from 0 up). - Not taken with a `"calendar"` policy (worked out for a unit renewed at each replacement), a `"level"` (a degradation level is not a virtual age), or an `"opportunity"`. +#### Maintenance that does harm + +A task can leave a unit *older* than it was: a seal reseated, a bearing +taken apart and put back, a service that disturbs what was running well. +A preventive `"restoration"` takes a `q` above 1 for that, and Kijima's +models read as before: under Kijima II, `q = 1.1` makes the virtual age +`1.1 (v + x)`; under Kijima I it adds `1.1 x`, more than the time run. +`q = 1` is a service that changes nothing, and gives the failures of no +service at all. Only a task's `q` may be above 1: a repair's stays in +`[0, 1]`. + +This is how harmful or invasive maintenance is modelled, from a factor +fitted to the unit's history (surpyval's `GeneralizedRenewal` can find +one above 1) or stated as an assumption. Its failures and cost rise with +`q`, and [`compare_npv`][repyability.RepairableRBD.compare_npv] of the +plan against the same plan without the task shows whether the task is +worth stopping: in UC-62 of the maintenance use cases, a 250-hour +service with Kijima II `q = 1.1` is worth about -919 over a year at 7% +against no service, where one with `q = 0.5` is worth about +1,529. + ## Hidden failures and inspection Some failures announce themselves: a running pump stops, and the operators @@ -1024,6 +1154,27 @@ component, any interval can be chosen: pump(100.0).optimal_inspection_intervals().intervals["p"] # -> 285.5 the formula gives 283 ``` +The tests can be chosen at a discount rate too, with the objectives of the +[age-replacement intervals](#choosing-the-intervals): `objective="eac"` for +the lowest equivalent annual cost in the long run, less a `value_rate` +earned while the system works, and `objective="npv"` for the highest +expected net present value over a `horizon`. A tested unit starts afresh at +the test that finds it failed, so its cycle is the tests up to that one: +each is paid for when it is made, the failure when it is found, and the +unit's own downtime from the failure to that test, each discounted to when +it falls. That holds for tests and repairs that take no time and find every +failure; any other tested unit refuses `"eac"` at a discount rate and names +`"npv"`. Tests cost now and hidden failures cost later, so a discount rate +puts the tests a little further apart: + +```python +plan = pump(100.0).optimal_inspection_intervals( + objective="eac", discount_rate=1e-4 +) +plan.intervals["p"] # -> 286.9 against 285.5 undiscounted +plan.objective_value # -> 13.94 the equivalent annual cost, per hour +``` + For a safety function, `min_availability=1 - PFDavg target` gives the cheapest tests that meet the target. With the valves above, each test costing 500, and tests monthly, quarterly, half-yearly, yearly or every two years: @@ -1124,11 +1275,90 @@ and carries on from where it was. | Key | Meaning | |---|---| | `period`, `offset` | Every `period`, the first at `offset` (0, the default, puts the first at `period`). | -| `times` | Or the shuts' start times, increasing (simulated). | +| `times` | Or the shuts' start times, increasing: outages at given times, valued over a horizon (they end, so there is no long run). | | `duration` | How long each shut lasts (0 for one that takes no time); shorter than the period or the gaps. | | `scope` | The nodes it holds off line (None, the default: the whole system). | | `cost` | Charged at each shut. | | `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}, +) +pump = { + "reliability": surv.Weibull.from_params([30000.0, 2.0]), + "repairability": surv.Exponential.from_params([1 / 24.0]), +} +line = RepairableRBD([("in", "pump"), ("pump", "out")], {"pump": pump}, + 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 +windows must not overlap). A block renewed at the outages +(`"preventive": {"shutdown": name}`) is replaced at each if it is up, +taking the outage's time, as under [replacement at given +times](#replacement-at-given-times), and the blocks in scope are held +off line for each window. The values over a horizon are worked out, not +simulated: `point_availability`, `mission_availability`, +`expected_events`, `expected_cost` and `expected_npv`, each outage's cost +and each job's charged and discounted at the outage's start, and +`maintenance_effect` over a window. The outages end, so the long-run +methods refuse, saying to ask for a horizon or give a period. A job +that restores a block only partly (a `"restoration"`), a block kept +unless it is due (`"older_than"`, `"policy": "condition"`) and a test +at outages at given times are simulated; the exact methods say so. + +```python +def outages(times): + W, E = surv.Weibull.from_params, surv.Exponential.from_params + lives = {"pump": W([30000.0, 2.0]), "motor": W([60000.0, 1.5]), + "bearing": W([20000.0, 3.0])} + pm = {"pump": 3000.0, "motor": 2000.0} + blocks = {} + for name, life in lives.items(): + blocks[name] = {"reliability": life, "repairability": E([1 / 24.0]), + "repair_cost": 20000.0} + if name in pm: + blocks[name]["preventive"] = {"shutdown": "outage", + "cost": pm[name]} + return RepairableRBD( + [("in", "pump"), ("pump", "motor"), ("motor", "bearing"), + ("bearing", "out")], + blocks, + shutdowns={"outage": {"times": times, "duration": 72.0, + "scope": ["pump", "motor"], "cost": 10000.0}}, + downtime_cost_rate=500.0, + ) + +four_years = 4 * 8760.0 +planned_outages = outages([3000.0, 12000.0, 26000.0]) +planned_outages.mission_availability(four_years) # -> 0.99238 +worth = planned_outages.expected_npv( + four_years, discount_rate=np.log(1.08) / 8760.0, periods=4 +) +worth.undiscounted_cost # -> 221291.9 +worth.cost # -> 193053.7 +worth.cost_by_category["shutdown"] # -> 26697.2 +``` A line of a pump, a motor and a bearing in series, shut 72 h a year at 10,000 a shut and 500 an hour of lost production; each block has its PM @@ -1273,7 +1503,7 @@ it saves. condition with a time to maintain, tests that take time, shuts on a period, nested RBDs. With planned outages and limited repair crews or common-cause groups (whose chains do not tell a block in planned work - from one in a repair), shuts at given times, or a partial restoration, + from one in a repair), or a partial restoration, a window is simulated: the plan and running to failure from one seed, on the same streams, so each simulation of the plan is paired with one without it, and `standard_errors` gives the paired errors of diff --git a/mkdocs.yml b/mkdocs.yml index fe512775..23d227dd 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -104,6 +104,7 @@ nav: - Condition-based evaluation: guide/condition-based.md - Redundancy models: guide/redundancy-models.md - Common-cause failures: guide/common-cause.md + - Common causes with wear-out lives and ages: guide/common-cause-ages.md - Repairable systems: guide/repairable.md - System capacity: guide/capacity.md - Costs: guide/costs.md @@ -125,6 +126,7 @@ nav: - Fault trees, missions, networks: api/other-systems.md - Node models: api/nodes.md - Components and maintenance: api/components.md + - Unit plans: api/unit-plans.md - Stress-strength interference: api/stress-strength.md - Timelines: api/timelines.md - Schedules: api/schedule.md diff --git a/pyproject.toml b/pyproject.toml index 7564b69e..00bff89a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -43,16 +43,18 @@ dependencies = [ # (sf/ff/qf/random/mean, extras/with_params, regression sf/sf_tvc, # to_dict/from_dict). A surpyval release reaches every fresh install at # once, so run the tests against surpyval's development branch before it - # is released, to show a break first. CI also tests this minimum. 0.28 - # is the release RePyability 0.19 is tested against (a Bayesian fit's - # quantile with an offset or shares, its qf(0), and same_unit); 0.25 + # is released, to show a break first. CI also tests this minimum. 0.29 + # is the release RePyability 0.20 is tested against (the renewal + # fitters' from_params, and the model classes in their subpackages, + # surpyval.univariate.joint among the public ones); 0.28 has a Bayesian + # fit's quantile with an offset or shares, its qf(0), and same_unit; 0.25 # has the joint models (surpyval.univariate.joint) a JointNode takes; # 0.24 gives a mixture a precise tail (sf) and has conditional_gaps read # a limited failure population's lfp_p, not a mixture's p; 0.23 named # the proportion lfp_p, takes success_run's level as alpha_ci, and # pickles its fits (for n_jobs' worker processes), as RePyability # relies on. - "surpyval>=0.28", + "surpyval>=0.29", "tqdm>=4.64", # The date arithmetic of repyability.schedule (rrule, the iCalendar # standard's recurrence). Every install had it already, through @@ -86,6 +88,8 @@ dev = [ "pytest-cov>=5.0", "coverage>=7.0", "pre-commit>=3.0", + # The schema of value_plan's documents is checked against its answers. + "jsonschema>=4.0", ] docs = [ # MkDocs 2.0 removes the plugin system with no migration path (per the @@ -130,6 +134,7 @@ include = ["repyability*"] "repyability.tests" = ["*.json"] "repyability.maintenance" = ["README.md", "CALENDAR_DECISIONS.md"] "repyability.schedule" = ["README.md"] +"repyability.schemas" = ["*.json"] # For Black pre-commit hook [tool.black] diff --git a/repyability/__init__.py b/repyability/__init__.py index 7d820d35..62ed144c 100644 --- a/repyability/__init__.py +++ b/repyability/__init__.py @@ -31,24 +31,36 @@ from repyability._version import __version__ from repyability.fault_tree import FaultTree from repyability.maintenance import ( + AgePolicy, AgeReplacementValue, + AtShutdown, + BlockPolicy, Calendar, CalendarPolicy, + CalendarReplacement, + ConditionPolicy, CostDistribution, DatedChoice, DatedReplacement, DelayEffect, FailureFinding, + FailureFindingWindow, FailureLimitPolicy, + ImperfectRepair, + Inspection, LayeredVisits, MaintenancePolicy, NextReplacement, NextReplacementOnDates, OnCondition, + Opportunities, Opportunity, + OpportunityPrice, + OpportunityPrices, OptionValue, OverhaulReplacePolicy, PlannedReplacement, + Prices, RatioChoice, RenewalForecast, RepairOrReplace, @@ -56,6 +68,7 @@ ReplacementChoice, ReplacementComparison, ReplacementRule, + Restoration, RuleCost, RunToFailure, ScheduledReplacement, @@ -69,9 +82,12 @@ SlowSolverWarning, SwitchTime, UnitDecision, + UnitPlan, + Upgrade, WindowCosts, best_switch_time, failure_finding, + failure_finding_window, layered_cost_rate, on_condition, operating_schedule_value, @@ -84,6 +100,7 @@ from repyability.network import Network from repyability.non_repairable import NonRepairable from repyability.rbd._bayesian_life import PosteriorPredictive +from repyability.rbd._contract import value_plan from repyability.rbd._mission_results import ( MissionDrivers, MissionPhaseSummary, @@ -92,8 +109,15 @@ from repyability.rbd._mission_settings import BlockSetting, MissionPhase from repyability.rbd._model_utils import model_parameters from repyability.rbd._streams import seed_entropy -from repyability.rbd.ccf import MGL, AlphaFactor, BetaFactor, CCFGroup +from repyability.rbd.ccf import ( + MGL, + AlphaFactor, + BetaFactor, + CCFGroup, + Shocks, +) from repyability.rbd.chunks import SimulationChunk +from repyability.rbd.contracts import AvailabilityContract from repyability.rbd.degrading_node import DegradingNode from repyability.rbd.helper_classes import ( PerfectReliability, @@ -124,6 +148,8 @@ CrewJob, CrewStates, Criticalities, + DowntimeDesign, + DowntimeRiskResult, EventsByWindow, ExpectedCost, ExpectedEvents, @@ -135,7 +161,11 @@ MaintenancePlan, ModelParameters, NodeActionRates, + NPVComparison, + NPVDistribution, + NPVUncertainty, PFDBreakdown, + PlanRobustness, PlanVsActual, PrimeImplicant, RateBreakdown, @@ -143,6 +173,7 @@ ReliabilityRedundancyAllocation, ReplacementCycle, RestorationCriticalityIndex, + SimulatedSwitchTime, SimulationSamples, SparesDemand, SparesStock, @@ -157,16 +188,19 @@ ) from repyability.rbd.routes import AnalysisRoute, AnalysisRoutes from repyability.rbd.shards import run_shard +from repyability.rbd.shocks import shock_nodes from repyability.rbd.standby_node import StandbyModel from repyability.repairable import ( Repairable, minimal_repair_time_to_nth_failure, ) +from repyability.schemas import npv_schema from repyability.stress_strength import ( stress_strength, stress_strength_over_time, ) from repyability.timelines import Timeline, Timelines +from repyability.value import ValueSchedule __all__ = [ "__version__", @@ -202,6 +236,8 @@ "MGL", "AlphaFactor", "CCFGroup", + "Shocks", + "shock_nodes", "minimal_repair_time_to_nth_failure", "ComponentOption", # Stress-strength interference @@ -209,6 +245,9 @@ "stress_strength_over_time", # Maintenance planning "Opportunity", + "Opportunities", + "OpportunityPrices", + "OpportunityPrice", "Calendar", "Shutdown", "Shutdowns", @@ -228,6 +267,14 @@ "ExpectedCost", "ExpectedEvents", "ExpectedNPV", + "NPVDistribution", + "SimulatedSwitchTime", + "DowntimeDesign", + "DowntimeRiskResult", + "NPVComparison", + "NPVUncertainty", + "AvailabilityContract", + "ValueSchedule", "MaintenanceEffect", "PlanVsActual", "EventsByWindow", @@ -255,6 +302,18 @@ "FailureCriticalityIndex", "RestorationCriticalityIndex", "MaintenancePolicy", + # A unit's maintenance plan and its parts (UC-63) + "AgePolicy", + "AtShutdown", + "BlockPolicy", + "CalendarReplacement", + "ConditionPolicy", + "ImperfectRepair", + "Inspection", + "UnitPlan", + "Prices", + "Restoration", + "Upgrade", "FailureLimitPolicy", "OverhaulReplacePolicy", "RepairOrReplacePolicy", @@ -276,10 +335,12 @@ "RunToFailure", "ScheduledReplacement", "FailureFinding", + "FailureFindingWindow", "OnCondition", "run_to_failure", "scheduled_replacement", "failure_finding", + "failure_finding_window", "optimal_failure_finding_interval", "on_condition", "optimal_on_condition_interval", @@ -299,6 +360,7 @@ "operating_schedule_value", "best_switch_time", "MaintenancePlan", + "PlanRobustness", "RateBreakdown", "PFDBreakdown", "AvailabilityAllocation", @@ -307,6 +369,8 @@ "TimelineSimulation", "SimulationChunk", "run_shard", + "value_plan", + "npv_schema", "seed_entropy", "model_parameters", ] diff --git a/repyability/_version.py b/repyability/_version.py index 79722dbb..32afb3c2 100644 --- a/repyability/_version.py +++ b/repyability/_version.py @@ -5,4 +5,4 @@ dependencies) via ``[tool.setuptools.dynamic]`` in ``pyproject.toml``. """ -__version__ = "0.19.1" +__version__ = "0.20" diff --git a/repyability/fault_tree.py b/repyability/fault_tree.py index d9b937a6..cfdbf676 100644 --- a/repyability/fault_tree.py +++ b/repyability/fault_tree.py @@ -82,6 +82,7 @@ ) from repyability.utils.checks import seed as checked_seed from repyability.utils.checks import simulation_options, whole_number +from repyability.utils.deprecation import refuse_removed_names from repyability.utils.wrappers import outside_level if TYPE_CHECKING: # pragma: no cover @@ -297,6 +298,7 @@ def _sort_key(s: frozenset) -> tuple: return (len(s), sorted(map(str, s))) +@refuse_removed_names class FaultTree: """A fault tree: gates over basic events. diff --git a/repyability/maintenance/CALENDAR_DECISIONS.md b/repyability/maintenance/CALENDAR_DECISIONS.md index 65baa258..4475d6c1 100644 --- a/repyability/maintenance/CALENDAR_DECISIONS.md +++ b/repyability/maintenance/CALENDAR_DECISIONS.md @@ -246,7 +246,11 @@ eye. then take every age from the youngest, so they no longer sum exactly to the cost rate. 20. **The NPV hook.** `_sweep` takes `beta`, a discount per step that - defaults to 1. There is no public API yet, as the brief asks. + defaults to 1. Discounting now reaches the long run (UC-44): + `optimal_calendar_policy(discount_rate=)` on a periodic calendar of a + short cycle (dp and integration), and a site's `discount=` without a + horizon, the dated window's run-on included; the other routes refuse + a rate, saying what to give instead. ## D. Phase 2 (integration) @@ -364,3 +368,120 @@ eye. - `test_api_docstrings` had been failing for the cost parameters of `NonRepairable`, `ReplacementPlan` and `replacement_policies`; this was fixed in #340. + +## G. Prices with the part (16 Nov 2026, UC-45) + +31. **★ The decision.** The maintainer, 16 Nov 2026: a replacement's + price "must come with the part", as an opportunity (a stop or shut) + applies to every part; and there should be one name for the two ways + of describing opportunities (`Calendar` in model time, 0.14, and + `Shutdowns` on real dates, 0.19; the word "Shutdowns" was not liked). + Done: + - **Names:** `Opportunity` says when, how long and what it takes down + (`takes_down`, by default the whole site), with no price; + `Opportunities([...], any_day=True|False, time_zone=None)` collects + them, in model time or on real dates by what they are (a mix is + refused). `optimal_opportunity_policy` and `opportunity_policy_cost` + replace `optimal_calendar_policy` and `calendar_policy_cost`, with + every keyword unchanged, and `where=` added. + - **Prices with the part:** `NonRepairable`'s `planned_cost` (any + day), `unplanned_cost` (a failure), and new `opportunity_cost` (at + an opportunity; without one, an opportunity is priced as any other + day, at `planned_cost`) and `opportunity_costs` (per opportunity). + - **Overrides by name or object, checked:** a key of + `opportunity_costs` is an opportunity's name or the `Opportunity` + itself; when the policy runs, a key that matches no opportunity of + the collection is refused, listing the names it has. Never ignored. + - **Jobs that don't fit are skipped:** an opportunity shorter than the + part's `job_duration` is not used for that part, and the policy's + `prices` say so ("the 6 h job doesn't fit in the 4 h stop"); with + either length unsaid it is used. In model time both are numbers in + the life's unit; on real dates text or hours. + - **Shown:** the policy's `prices` (`OpportunityPrices`) give each + opportunity's price and its source (an override, `opportunity_cost`, + `planned_cost`, a deprecated price, or not used and why), the any-day + and the failure prices. +32. **The old forms keep their numbers.** `Calendar(failure=, anytime=)`, + `Opportunity(name, cost, ...)`, `Shutdown(replace_cost=)` and + `Shutdowns(any_day=)` still work and warn (a `FutureWarning`, + as CONTRIBUTING has deprecations warn, naming the replacement), for + removal in 0.21. A price on an opportunity is the part's override for + it (the part's own `opportunity_costs` wins where both are given); + `failure=` the failure's price and `anytime=`/`any_day=` the any-day + price, exactly as before. The prices are laid on the opportunities as + the solvers' own `Calendar` or site, so no numerical method changed: + `test_opportunities.py` checks old against new bit for bit. +33. **Choices made here.** `Opportunities(any_day=)` defaults to True (a + planned replacement on any other day, at the part's `planned_cost`; + as `Calendar`'s `anytime="part"` did; `Shutdowns` defaulted to none). + An empty collection with no time zone is in model time, unless the + policy is given a site's arguments (`now=`, `unit=`, `plan=`, ...). + The helper is a static method, + `NonRepairable.opportunity_prices(opportunities, *, replacement_cost, + replacement_duration, failure_cost, failure_duration, downtime_cost)`, + returning `OpportunityPrices` whose `apply(part)` gives the part its + `planned_cost`, `unplanned_cost`, `opportunity_cost` and + `job_duration`; the downtime cost is the system's and is not kept on + the part. Saving a part keeps its opportunity prices, an `Opportunity` + key by its name. The results keep their names (`ShutdownPolicy`, + `ShutdownRoute`). +34. **Left for later.** A diagram does not read `takes_down` yet (a + shut's `scope` is still given to `on_diagram`). Refusals and the + horizon were parked here and decided next (H). + +## H. Exact by default, or a horizon (16 Nov 2026, UC-44) + +35. **★ The decision.** The maintainer, 16 Nov 2026: **"Exact by + default; refuse what can't be done exactly; `horizon=` never + refuses."** Done: + - **Default:** the exact repeating cycle's answer, discounted or + not, where the opportunities repeat within `MAX_CYCLE`: the exact + routes, their numbers unchanged bit for bit. + - **Refused, with a ready answer:** a cycle longer than `MAX_CYCLE`, + given dates in model time, shuts that drift on real dates and a + duty plan's clock, each with a discount (and pricing a rule there). + The message names a horizon worked out from the inputs + (`_horizon.ready_model_text`, `ready_site_text`): with a discount, + where costs are discounted to under one part in a billion + (`horizon='2333-11-16'` at 7% from 16 Nov 2026; `horizon=112000` + days in model time); with none, the full cycle and three life + spans. `method='sampling'` is named where it applies + (undiscounted). + - **`horizon=` never refuses for those reasons:** the backward sweep + (`_horizon.backward`, shared by real dates and model time), with + the net present cost and an EAC, or undiscounted the total. + Model time takes it too (a number, with `discount_rate=`). + - **Silent sampling stops:** `method="auto"` sampling a long cycle + warns with a `FutureWarning` (`deprecation.refuses_from`) and + refuses from 0.21; `test_auto_sampling_refuses_in_0_21` reminds. + - **A given rule's discounted long run** is priced exactly, the + optimiser's value iteration with the decisions fixed; + `compare()` follows. `optimal_next_replacement` discounts its own + choices at the policy's rate. +36. **Choices made here.** + - **"One part in a billion"** is `exp(-r H) < 1e-9`, the share of a + steady cost's present value past `H`: 307 whole years at 7% (the + decision's example said 300, which leaves 1.5e-9). Model-time + values are rounded up to three significant figures. + - **Undiscounted, at most two million grid steps** (`READY_STEPS`, + about a minute's sweep): a co-prime calendar's full cycle can be + hundreds of millions of steps, a horizon nobody could run; the + message then says the cycle is longer than is worth sweeping. + - **A model-time horizon ignores `tail`:** it takes the given dates + as they are and assumes nothing after them; any other day's price + still applies throughout. + - **The horizon's EAC is continuous**, `r NPC / (1 - exp(-r H))` with + `r = ln(1 + d)`, matching the long run's `ln(1 + d)` times `npv`; + `optimal_next_replacement` with a horizon policy used `d` in place + of `ln(1 + d)` before. + - **A horizon policy's `cost_rate`** (model time) is the rule's + undiscounted average to the horizon from a new part, and its + schedule's chances are from that part. +37. **Left for later.** The repairable unit's overhaul, failure-limit and + overhaul-replace policies, failure-finding and on-condition + intervals, and `RepairableRBD.optimal_replacement_intervals` are not + discounted. A site's horizon grid is sized from the life alone (the + shuts laid at the nearest step), so it agrees with the exact route + to about 1.5e-5, not 1e-9; laying it on the shuts would change the + horizon's published numbers. A rule's undiscounted price over a long + cycle in model time is still a long finite horizon differenced. diff --git a/repyability/maintenance/README.md b/repyability/maintenance/README.md index 01988719..756d7d45 100644 --- a/repyability/maintenance/README.md +++ b/repyability/maintenance/README.md @@ -14,6 +14,35 @@ schedules and meters read by date) are recorded in UC-4 and UC-10 there). The caller (the Reliafy app, or anyone) holds the records and decides what "today" is. +**Money has one home**, `repyability.value`: discounting (continuous, at +a rate per unit of the clock the money falls on; a yearly rate converted +to it in one place), escalation and real rates, `ValueSchedule`, the +cost categories and the cash-flow table. The use cases here that value a +plan (UC-19, UC-21, UC-44, UC-46, UC-57 and the others with a +`discount_rate`) and the calendar's in `repyability/schedule/README.md` +all go through it. + +## Layers + +Which module answers which question (the layering in `CLAUDE.md`, +Architecture): + +| Question | Where | Use cases | +|---|---|---| +| What is an amount at a time worth now; how do prices grow; what is the cash-flow table? | `repyability.value` | UC-19, UC-57 | +| What is one unit's plan (life, repairs, tasks, prices, salvage, growth, retirement)? | `repyability.maintenance.UnitPlan` | UC-63 | +| What is that plan worth alone, its cash flows, spread, plan against actual, long-run cost and best interval? | `UnitPlan`'s methods, each through its one-node diagram | UC-65 | +| A single part's policies (age, block, calendar, opportunities, next replacement, slack, layered visits) | `NonRepairable` and the functions of this package | UC-5 to UC-18, UC-44, UC-45 | +| The discounted cost per year of age replacement | `_options.cycle_eac`, one definition for a part and a diagram's component | UC-44 | +| A unit whose life is a subassembly | a `NonRepairableRBD` as the life | UC-66 | +| What happens on dates: rules, duty plans, each unit's plan on the calendar | `repyability.schedule` (its README) | UC-10, UC-39, UC-64 there | +| What belongs to the system: structure, system downtime and value, crews, spares, site shutdowns, common-cause groups | `RepairableRBD` | UC-21, UC-23, UC-46, UC-59 | +| 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: +- 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. + ## The use cases, by number | # | The question here, in model time | State | @@ -33,16 +62,34 @@ records and decides what "today" is. | UC-18 | The numbers behind each maintenance decision for a failure mode: run to failure, scheduled replacement, failure finding, on condition | **Built**: `run_to_failure`, `scheduled_replacement`, `failure_finding`, `on_condition` | | UC-17 | The risk added when a visit is missed and its work waits | **Built**: `NonRepairable.cost_of_missed_visit` (and `delay_effect`) | | UC-12 | When to replace this part next: now, at a scheduled outage, at a planned replacement, or at its failure? | **Built**: `NonRepairable.optimal_next_replacement` | -| UC-13 | The long-run optimal replacement policy over a calendar of shuts with prices of their own | **Built**: `NonRepairable.optimal_calendar_policy` | -| UC-19 | What a plan is worth over a horizon at a discount rate, and as a yearly cost | **Built**: `RepairableRBD.expected_npv`, `NonRepairable.age_replacement_value` | -| UC-20 | One unit run on an operating schedule (covariates and value by stretch, in model time): the value earned, the failures' cost and the NPV, and the best time to switch from one way of running to another | **Built** (one unit): `operating_schedule_value`, `best_switch_time` | +| UC-13 | The long-run optimal replacement policy over a calendar of shuts with prices of their own | **Built**: `NonRepairable.optimal_opportunity_policy` (0.14's `optimal_calendar_policy`, deprecated), the prices on the part since UC-45 | +| UC-19 | What a plan is worth over a horizon at a discount rate, and as a yearly cost | **Built**: `RepairableRBD.expected_npv`, `NonRepairable.age_replacement_value` (value over time and escalation: UC-57) | +| UC-20 | One unit run on an operating schedule (covariates and value by stretch, in model time): the value earned, the failures' cost and the NPV, and the best time to switch from one way of running to another | **Built** (one unit, numerical): `operating_schedule_value`, `best_switch_time`; (a diagram, simulated): `RepairableRBD.best_switch_time` | | 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-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 in part**: the same `shutdowns` at `"times"`, simulated (`availability`, `cost`); the exact cost by window and NPV take shuts on a period only | +| 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=)` | +| UC-53 | A protective device tested for a hidden failure at given times (not one interval), from its age, over a window: what each test finds, the time it is failed, the demands that meet it failed, and the plan's cost and present value; and the same never tested | **Built**: `failure_finding_window` (exact at the tests where only a test finds a failure, numerical where a demand shows it; to a stated precision) | | UC-25 | How much of the downtime and lost production is planned and how much is from failures, and how many failures the plan avoids against running to failure | **Built**: `RepairableRBD.maintenance_effect`, and the split in `ExpectedEvents`, `EventsByWindow`, `AvailabilityResult` and `CostResult`; exact where the blocks fail independently, simulated otherwise | | UC-26 | A pump run part of the time with its overhaul counted in running hours: availability and cost, and at another duty | **Built**: a `"preventive"` or `"inspection"` spec's `"basis": "operating"`, put on the calendar through the block's `"duty"` | -| UC-43 | A site's shuts on real dates (rules, one-offs, plain periods, a use on a meter) in one record, the best rule for a part there, worked out by a route that is always named and never chosen silently, given back as dates; the unit in service, its cost's spread, and a diagram's outages from the same record | **Built**: `Shutdowns`, `Shutdown`, `optimal_calendar_policy(site, ...)` returning a `ShutdownPolicy`, `Shutdowns.route`, `calendar_policy_cost(site, ...)`, `optimal_next_replacement(..., site=)`, `cost_distribution`/`cost_by_window(policy=)`, `Shutdowns.on_diagram` | +| UC-43 | A site's shuts on real dates (rules, one-offs, plain periods, a use on a meter) in one record, the best rule for a part there, worked out by a route that is always named and never chosen silently, given back as dates; the unit in service, its cost's spread, and a diagram's outages from the same record | **Built**: `Opportunities` of `Opportunity` on real dates (0.19's `Shutdowns` and `Shutdown`, deprecated), `optimal_opportunity_policy(site, ...)` returning a `ShutdownPolicy`, `Opportunities.route`, `opportunity_policy_cost(site, ...)`, `optimal_next_replacement(..., site=)`, `cost_distribution`/`cost_by_window(policy=)`, `Opportunities.on_diagram` | +| UC-44 | The best replacement policy in the long run at a discount rate: age replacement, a calendar of shuts in model time and a site on real dates, by the least equivalent annual cost | **Built**: `discount_rate=` of `find_optimal_replacement`, `optimal_replacement_policy` and `optimal_opportunity_policy` (`discount_rate=` in model time, and `discount=` without a horizon on real dates) | +| UC-45 | One record of a site's opportunities (stops and shuts) for every part, each part bringing its own prices (at an opportunity, on any other day, at a failure, and per opportunity) and the length of its job, so an opportunity too short for the job is not used; and the prices worked out from a replacement's cost and the plant's downtime | **Built**: `Opportunity`, `Opportunities`, `NonRepairable(opportunity_cost=, opportunity_costs=, job_duration=)`, the policy's `prices` (`OpportunityPrices`), `NonRepairable.opportunity_prices` | +| UC-55 | How sure an NPV and a choice of intervals are: the NPV's change with the discount rate, its spread over the fitted models' uncertainty with each input's share, and how often the chosen replacement intervals stay the best | **Built**: `expected_npv(rate_sensitivity=True)`, `RepairableRBD.expected_npv_uncertainty`, `optimal_replacement_intervals(robust=True or "reoptimise")` | +| UC-56 | At each planned outage, also replace the parts close enough to their own replacement, since the plant is down anyway: what the scope adds, by outage, and what the plan then costs | **Built** (simulated): a shutdown's `"opportunistic"`, the count by outage in `AvailabilityResult.outage_jobs`; the exact methods refuse, naming the simulation | +| UC-57 | What a plan is worth when the price it earns steps up, its costs escalate at their own rates, and the rate is real or nominal; and the same escalation on dates | **Built**: `expected_npv(value_rate=ValueSchedule(...), escalation=, rates=, inflation=)`; `escalation=` beside `discount=` in `repyability.schedule` | +| UC-58 | An outage's overhaul that leaves a part as if a given age, not by a Kijima factor | **Built** (simulated): a `"preventive"` spec's `"restore_to"`; `restore_to=0` is a renewal (exact where renewals are) | +| UC-62 | A service that does harm: a fitted restoration factor above 1, each service leaving the unit older than it was. What does it do to the failures, and is the service worth stopping? | **Built** (simulated): a `"preventive"` `"restoration"` with `q` above 1; `compare_npv` against no service | +| UC-63 | One pump's plan: its life and repairs, its tasks each in its own clock, and its prices, held as one object that a diagram's node takes | **Built**: `UnitPlan` with `AgePolicy`, `BlockPolicy`, `ConditionPolicy`, `CalendarReplacement`, `AtShutdown`, `Inspection`, `Upgrade`, `Restoration`, `ImperfectRepair` and `Prices`; a spec dict is its shorthand (`UnitPlan.from_spec`, `plan.spec()`) | +| UC-65 | One pump's plan valued alone: its NPV over eight years at 7%, its cash flows by year, its spread, its plan against what happened, its long-run cost and best interval; with its salvage, its prices' growth and its retirement on the plan | **Built**: `UnitPlan.expected_npv`, `cash_flows`, `npv_distribution`, `plan_vs_actual`, `expected_cost`, `expected_cost_rate`, `events_by_period`, `failures_by_period`, `optimal_replacement_interval`, `optimal_inspection_interval` and `analysis_routes`, each its one-node diagram's (`UnitPlan.diagram`), on a `CalendarContext` if given; `UnitPlan(salvage=, escalation=, retire_at=)` and the spec keys of the same names | +| UC-59 | A part renewed at a short stop every month and again at the long yearly overhaul, each renewal as long as its shut | **Built**: a `"preventive"` spec's `"shutdown"` as a list of shutdowns, exact over a horizon | +| UC-60 | A part upgraded in year 3 and block-replaced before and after, the new model on the same interval | **Built**: an `"upgrade"` with a `"preventive"` block policy, numerical over a horizon and simulated | +| UC-66 | A pump whose seal is a redundant pair, replaced whole when both have failed: its life is a diagram | **Built**: a `NonRepairableRBD` as a life wherever a life is taken (`UnitPlan`, a spec's `"reliability"`, `NonRepairable`), by its functions; `NonRepairableRBD.qf` inverts its `ff` to near machine precision | +| UC-64 | What a part costs per year once upgraded: the long run of the diagram with the new life, the time before the upgrade ignored | **Built**: the long-run methods of a diagram with an `"upgrade"` give the values of the diagram after it | +| UC-68 | "95% sure": the least spend that keeps a bad year's downtime (hours or cost) under a limit, with the frontier and both planned and unplanned downtime | **Built** (simulated): `RepairableRBD.least_spend_for_downtime` and `UnitPlan.least_spend_for_downtime`, with redundancy and interval levers; risk measures in `repyability.value._risk` | | UC-27 | A fleet whose units differ (lemons fail more and are written off sooner): the cheapest rule for a new unit (keep repairing, replace at an age, replace at a count of failures), and for one unit that has just failed, repair it again or replace it | **Built**: `RepairOrReplace` (`fleet_policy`, `unit_decision`, `break_even_frailty`), from a surpyval joint frailty model; numerical, bands from parameter draws | ## How a use case is added @@ -1145,7 +1192,26 @@ answers back into dates is Reliafy's too.) - **Status:** built (the maintainer's brief, "long-run optimal replacement policy over an outage calendar"): `NonRepairable.optimal_calendar_policy`, `calendar_policy_cost`, `Opportunity`, `Calendar`, `CalendarPolicy`. + Since UC-45 (0.20) the prices come with the part, and the names are + `optimal_opportunity_policy`, `opportunity_policy_cost` and + `Opportunities` (the old ones deprecated, with the same numbers). Decisions to take or verify: `repyability/maintenance/CALENDAR_DECISIONS.md`. +- **In the 0.20 API:** + + ```python + plant = Opportunities([ + Opportunity("weekly", period=7.0), + Opportunity("quarterly", period=91.0), + Opportunity("annual", period=364.0), + ]) # any_day=True: 4 on any other day + bearing = NonRepairable( + surv.Weibull.from_params([1000.0, 2.5]), + planned_cost=4.0, unplanned_cost=20.0, + opportunity_costs={"weekly": 3.0, "quarterly": 2.0, "annual": 1.0}, + ) + policy = bearing.optimal_opportunity_policy(plant) # 0.006943 a day + bearing.opportunity_policy_cost(plant, {"annual": 0.0}) + ``` - **Who asks, and why:** a reliability engineer setting a part's replacement rule in a plant whose shuts make replacing cheap at some times and dear at others. Age replacement assumes one planned price at @@ -1237,6 +1303,37 @@ answers back into dates is Reliafy's too.) ### UC-43: "Our shuts are on real dates: every Saturday, the first Tuesday of November, two turnarounds, and the truck's service every 15,000 km. What is the best rule for this part, on those dates, and how was it worked out?" +- **In the 0.20 API** (the prices on the part, UC-45): the plant of + the answers below is + + ```python + plant = Opportunities( + [ + Opportunity("weekly stop", Recurrence.weekly("Sat"), duration="8h"), + Opportunity("quarterly shut", Recurrence.monthly( + weekday="Sunday", nth=1, every=3, anchor="2026-12-06"), + duration="1d"), + Opportunity("annual shut", Recurrence.yearly( + month="November", weekday="Tuesday", nth=1), duration="3d"), + Opportunity("turnaround", dates=["2027-03-03", "2028-09-09"], + duration="14d"), + ], + time_zone="Australia/Brisbane", + ) + pump_bearing = NonRepairable( + surv.Weibull.from_params([20_000, 2.5]), + planned_cost=4.0, unplanned_cost=40.0, + opportunity_costs={"weekly stop": 3.0, "quarterly shut": 2.0, + "annual shut": 1.0, "turnaround": 0.5}, + ) + pump_bearing.optimal_opportunity_policy( + plant, method="averaged", plan=shifts, now="2026-11-16", + unit="hours", age=3100, + ) + ``` + + and Example 6 is `optimal_opportunity_policy(Opportunities(), + unit="days")` for a part with `planned_cost=1`. - **Status:** built: `Shutdowns([Shutdown(...)], any_day=, time_zone=)`, `NonRepairable.optimal_calendar_policy(site, plan=, now=, readings=, age=, unit=, method=, horizon=, discount=, failure_timing=)` returning a @@ -1301,7 +1398,8 @@ answers back into dates is Reliafy's too.) Dekker & Dijkstra (1992), NRL 39(2):175-190, and Dekker & Smeitink (1991), EJOR 53(1):46-63. With no shuts it is plain age replacement, route 1. - 4. **horizon** (`horizon=`, `discount=`, both required, 0% allowed): + 4. **horizon** (`horizon=`, `discount=`, both required, 0% allowed; + never refused, and named with a ready value by every refusal, UC-44): the backward dynamic programme over the real shuts to the horizon, each grid step discounted by the calendar time it spans (or UC-13's quadrature, each gap discounted at its own rate); the policy is @@ -1327,7 +1425,13 @@ answers back into dates is Reliafy's too.) part is replaced by the long run's own rule. `cost` is the long run's a year, `dated_cost` the expected cost to the window's end, and the rule is in two phases (`rule.dated`: each fixed date's own - threshold). Fixed dates all before now are left out. + threshold). Fixed dates all before now are left out. With + `discount=` and no horizon (UC-44) the window and its run-on are + discounted (the programme of 4 at that rate), so what lies past the + window is valued by the recurring shuts' discounted long run, not by + undiscounted relative values; `cost` is then the long run's + equivalent annual cost and `dated_cost` the present value to the + window's end. Results are dated through the layout: a shut's own date, a planned replacement on any other day at the first moment the part's clock @@ -1424,6 +1528,227 @@ answers back into dates is Reliafy's too.) times as they are, if that is what is meant. +### UC-44: "Money spent later is worth less to us (7% a year). What replacement age, or rule at our shuts, is cheapest in the long run at that rate?" + +- **Status:** built. +- **In the 0.20 API:** + + ```python + stops = Opportunities([Opportunity("stop", period=28.0)], any_day=False) + part = NonRepairable(surv.Weibull.from_params([1000.0, 2.5]), + unplanned_cost=20.0, opportunity_cost=3.0) + part.optimal_opportunity_policy(stops, discount_rate=math.log(1.07) / 365.25) + site = Opportunities([Opportunity("stop", Recurrence.every(4, "weeks", "2026-11-21"))], + any_day=False) + part.optimal_opportunity_policy(site, unit="days", now="2026-11-16", discount=0.07) + # Where nothing repeats exactly, a horizon (the refusal names one): + part.optimal_opportunity_policy(stops, discount_rate=math.log(1.07) / 365.25, + horizon=112000) + part.optimal_opportunity_policy(site, unit="days", now="2026-11-16", + discount=0.07, horizon="2333-11-16") + ``` +- **Who asks, and why:** a reliability or maintenance engineer whose + finance team discounts costs: the long-run cost rate (UC-13, age + replacement) treats a dollar in ten years as a dollar now, which + replaces earlier than their own figures would. +- **What they know:** the part's life and prices, as for age replacement, + UC-13 or UC-43, and a discount rate: continuous, per unit of the + life's time (`discount_rate=`) in model time; yearly (`discount=`, + 0.07 for 7%) on a site's real dates, as a horizon takes it. +- **What they want back:** the age, or the rule at each shut, with the + least equivalent annual cost (EAC), that cost, and the present value + of every replacement from now on, forever (`npv`); the undiscounted + long-run figures of the rule chosen (`cost_rate`, the rates by kind) + stay beside them. +- **How it is solved:** + - **Age replacement** (Fox, 1966): `EAC(T) = [cu (1 - exp(-r T) R(T) - + r M(T)) + cp exp(-r T) R(T)] / M(T)`, `M` the integral of `exp(-r t) + R(t)` to `T` (the cost rate at `r = 0`), scanned on a log grid of + ages by the trapezoidal rule up to where the part has all but surely + failed or a cost is discounted to `exp(-40)`, the best refined by a + bounded search on the cost by quadrature (`age_replacement_value`'s); + against running to failure, `cu (1 - r M) / M` with `M` to infinity. + A non-parametric estimate is scanned on its own grid. + - **A calendar in model time**, periodic, short cycle: value iteration + over the cycle, each grid step discounted by `exp(-r step)` (or each + gap of the quadrature at `r`), from the last sweep's values less a new + part's, stopped by MacQueen's bounds: every path through a cycle is + discounted by the same `exp(-r L)`, so the fixed point lies in a known + band of the last sweep. `npv` is a new part's at time 0. The rule so + chosen is then priced undiscounted by relative value iteration with + its decisions fixed. + - **A site:** `discount=` with no horizon takes the exact routes + discounted (the yearly rate as `ln(1 + d)` over the part's units a + year), plain age replacement on any day by Fox's formula, and the + dated window discounted with the recurring shuts' discounted long run + after it (UC-43, route 5). `cost` is the EAC a year, `ln(1 + d)` + times `npv`. + - **The rule (the maintainer, 16 Nov 2026): "Exact by default; refuse + what can't be done exactly; `horizon=` never refuses."** + - **Exact by default:** with no `horizon=`, the exact repeating + cycle's answer, discounted or not, wherever the opportunities + repeat within `MAX_CYCLE` steps (the routes above, unchanged). + - **Refused, with a ready answer:** a cycle longer than `MAX_CYCLE`, + given dates in model time, shuts that drift on real dates, a duty + plan, sampling or averaged gaps with a discount, and pricing a rule + where nothing repeats. Each refusal names a horizon worked out from + the inputs: with a discount, where costs are discounted to under + one part in a billion (`ln(1e9) / ln(1 + d)` years, 307 at 7%: from + 16 Nov 2026, `horizon='2333-11-16'`; in model time `ln(1e9) / r`, + rounded up to three figures: 112,000 days at 7% a year); with none, + the full cycle and three of the part's life spans (at most two + million grid steps). Where sampling applies (undiscounted) it names + `method='sampling'` too. + - **`horizon=` never refuses for those reasons:** a backward sweep + from the horizon (`_horizon.backward`, `_replacement._sweep` with + each step discounted), on the real dates (through a duty plan's + forecast) or in model time (`horizon=` a number, with + `discount_rate=`; given dates as they are, nothing assumed after + them). It gives the net present cost (`npv`, or a site's `cost`) + and the equivalent annual cost (`eac`: `r NPC / (1 - exp(-r H))`); + undiscounted, the total to the horizon (and it over `H`). + - **A given rule** (`opportunity_policy_cost(..., discount_rate=)` + in model time, `discount=` on a site, a site's `compare()`) is + priced over the exact discounted long run as the optimiser's is, + with the decisions fixed (`_discounted_values(fixed=)`, or the + quadrature's); where nothing repeats, the rules above. + - **`method="auto"`** in model time still samples a cycle too long + to sweep, undiscounted, as released, but with a `FutureWarning`: + from 0.21 it refuses, naming the ready horizon and + `method='sampling'`. + - **`optimal_next_replacement`** with a discounted policy discounts + its own choices at the policy's rate, its baseline the policy's + EAC (`_next`): each choice's present value and the policy's after + it, less the policy's from now, `price e^(-ru) S(u) + cu (1 - + e^(-ru) S(u) - r M(u)) - EAC M(u)`, `M(u) = ∫₀ᵘ e^(-rt) S(t) dt`; + at rate 0, the undiscounted cost as before. + - **The five cases once refused, before and after** (7% a year; + `A_DAY = ln(1.07) / 365.25`): + - (a) shuts every 7, 93 and 401 days at 3, 2 and 1, any day 4, + failure 40, Weibull(1000, 5), `discount_rate=A_DAY`: refused ("give + opportunities whose periods share a shorter cycle, or ... a site"); + now refused with `horizon=112000`, and with it NPC 18.31, 1.239 a + year, the next replacement at the 401-day shut (4.7 s). + - (b) given model-time dates [100, 400] at 1, any day 4, failure 20, + Weibull(1000, 2.5): refused ("give its shuts as a site"); now + `horizon=112000`: NPC 69.84, 4.73 a year. + - (c) an annual shut on the first Tuesday of November (364 or 371 + days apart) at 1, failure 20, `discount=0.07`: refused ("give + horizon= with discount="); now with `horizon='2333-11-16'`: $36.69 + to then, $2.48 a year, replace at the shut if older than 89.6 to + 91.4 days, next on 2 November 2027. + - (d) a stop every 4 weeks on `DutyPlan(Shifts("Mon-Fri", "06:00", + "22:00"))`, the bearing Weibull(20,000 h, 2.5), failure 40: + refused (steady pace); now `horizon='2333-11-16'`: $25.60, $1.73 a + year, at a stop from 3,815 to 3,833 hours. + - (e) pricing `{"annual shut": 400}` at (c)'s site: refused ("not yet + at a discount over the long run"); now refused only because the + shut drifts, with `horizon='2333-11-16'`: $61.03, $4.13 a year. On + the 28-day stop, which repeats, it is priced exactly: `{"stop": + 419}` at $4.22 a year, the optimiser's own EAC to 1e-9. +- **Horizon against exact** (the 28-day stop below, model time): the + horizon's EAC a year 4.0275 at 10 years, 4.1521 at 20, 4.2100 at 50, + 4.21625 at 100, 4.2164614 at 200 and 4.2164617 at 307 (the ready + horizon), against the exact 4.2164617 (gaps 4.5%, 1.5%, 0.15%, 5e-5, + 6e-8, 3e-11); the threshold at the first stop 419.125 days from 50 + years on (410.4 at 10 years, where the end is a part's life away). +- **Today:** the Weibull(1000 h, 2.5) bearing at `cp = 1`, `cu = 5`: + 493.0 h undiscounted; 493.2 h at 5% a year and 493.4 h at 10%, the + life in hours (8,760 a year), where a cycle is a few weeks and + discounting hardly matters; with the life in days, 497.7 and 502.3 + days. A shut every 28 days at 3, a failure at 20, Weibull(1000 days, + 2.5): the stop's threshold 414 days undiscounted, 419 at 7% and 433.5 at + 30% a year. +- **Checks:** `test_discounted_long_run.py`: rate 0 the undiscounted + answers unchanged; the age against Fox's cost from the density by + quadrature, and its present value against a simulation of the + discounted renewal costs; a later age as the rate rises for a part + that wears out; the rate going to 0 coming to the cost-rate optimum; + running to failure winning at a high rate; a calendar's present value + against a plain backward sweep over many cycles, grid against + quadrature; a site's against the horizon route's net present cost to + 50 years, and the dated window's decisions against a long discounted + horizon's. +- **Checks** (`test_exact_or_horizon.py`): rate 0 and the exact routes + bit for bit as before; the horizon's EAC coming to the exact one as it + lengthens, its first decisions within a step; each of (a)-(e) refused + with its ready horizon, which works and gives the same to 1e-8 doubled; + a fixed rule's discounted price against a plain backward sweep over + many cycles and a seeded simulation of its discounted costs, and the + optimiser's rule at its own EAC (grid and quadrature); the next + replacement's discounted choices against present values from the + density; the `FutureWarning` with its ready horizon. +- **Learned / open questions:** the exact EAC of the 28-day stop is + 4.2165 a year, not the 4.202 once quoted; its threshold 419.1 days. A + site's horizon lays the shuts on a grid sized from the life alone, the + exact route's on the shuts, so the two differ by about 1.5e-5 there. + Not yet discounted: the repairable unit's overhaul, failure-limit and + overhaul-replace policies, failure finding and on-condition intervals, + and `RepairableRBD.optimal_replacement_intervals`. A rule's undiscounted + price over a long cycle in model time is still differenced over a long + finite horizon, not refused. + + +### UC-45: "One list of our stops and shuts serves every part. Each part's replacement costs differently, and some jobs don't fit in a short stop. What is each part's best rule, and what did it price each stop at?" + +- **Status:** built (the maintainer's decision, 16 Nov 2026; see + `CALENDAR_DECISIONS.md`, G): `Opportunity`, `Opportunities`, + `NonRepairable(opportunity_cost=, opportunity_costs=, job_duration=)`, + `optimal_opportunity_policy` and `opportunity_policy_cost` (the policy's + `prices`, an `OpportunityPrices`), and `NonRepairable.opportunity_prices`. +- **Who asks, and why:** a planner who keeps one record of the site's + stops and shuts, and an engineer setting rules for many parts against + it. Until 0.20 the price was on the opportunity (`Opportunity(name, + cost)`, `Shutdown(replace_cost=)`), so each part needed its own copy of + the site; and a model-time `Calendar` and a real-date `Shutdowns` were + two ways to say the same thing. +- **What they know:** the site's opportunities (when, how long, what each + takes down); for each part its replacement's price at an opportunity, + on any other day and at a failure (or a replacement's cost, its + duration and the plant's downtime cost an hour, from which those + follow), any opportunity priced differently, and how long the job takes. +- **What they want back:** each part's policy, as UC-13 and UC-43, with + the price each opportunity was given and where it came from, and the + opportunities not used and why ("the 6 h job doesn't fit in the 4 h + stop"). +- **How it is solved:** no new method. The part's prices are laid on the + opportunities (`_opportunities.resolve`): at each opportunity the part's + `opportunity_costs` for it (by name, or the `Opportunity` itself), else + its `opportunity_cost`, else its `planned_cost` (an opportunity priced + as any other day); on any other day its `planned_cost` where + `any_day=True`; at a failure its `unplanned_cost`. An opportunity shorter + than `job_duration` (either length unsaid: used), or with `where=` one + whose `takes_down` leaves that label out, is dropped. The result is the + solvers' own record (a model-time `Calendar`, or a site), solved as + UC-13 and UC-43 solve it. A key of `opportunity_costs` naming no + opportunity of the collection is refused, listing those it has. The + 0.14 and 0.19 forms are read the same way, their prices taken as the + part's overrides for those opportunities. `opportunity_prices` works + out the prices: at a fitting opportunity the replacement alone, on any + day the replacement and its downtime, at a failure the failure's cost + and its downtime; `apply(part)` gives the part those prices (the + downtime cost is the system's, not kept on the part). +- **The answers, by hand:** a replacement of 1,200 taking 6 h, the plant + down at 2,500 an hour, a failure of 4,200 with 18 h down: 1,200 at a + stop of 8 h; not at a stop of 4 h; 1,200 + 2,500 x 6 = 16,200 on any + other day; 4,200 + 2,500 x 18 = 49,200 at a failure. UC-13's plant as a + part with `planned_cost=4`, `unplanned_cost=20` and overrides 3, 2 and + 1: 0.006943 a day, the `Calendar`'s figure bit for bit. +- **Checks** (`test_opportunities.py`): the old forms against the new, + bit for bit, in model time, on a site with and without fixed dates, and + discounted both ways; overrides by name and by object; a misspelt name + refused with the names; a stop too short skipped, said, and the same as + the site without it; the price with no `opportunity_cost`; the helper + against the hand-worked prices, and applied; one record serving two + parts, each its own calendar's policy; `where=`; saving and loading the + opportunities, a saved `Shutdowns`, and the part's prices; each old + form's warning. +- **Learned / open:** `takes_down` is recorded and filters a policy by + `where=`; a diagram does not read it yet (a shut's `scope` is still + given to `on_diagram`). The results keep the names `ShutdownPolicy` + and `ShutdownRoute`. + + ### UC-14: "A cheap task every visit and a deeper one every few visits: how often should we visit, and how deep?" - **Status:** built: `optimal_layered_visits(light, deep, *, visit_cost=, @@ -1565,8 +1890,9 @@ answers back into dates is Reliafy's too.) over a long horizon against Fox's formula integrated independently; the table adding up to the total; the cost rate as the rate goes to 0. - **Not yet:** value that varies in time, escalation, plans of actions at - given times, the simulated distribution, crews as cash flows, and NPV as - the optimisers' objective. + given times, crews as cash flows, and NPV as + the objective of the optimisers other than age replacement and the + calendar policies (UC-44). ### UC-20: "If we run at 70 °C instead of 30 °C we make more, but the bearings wear out faster. Does it pay?" @@ -1574,9 +1900,13 @@ answers back into dates is Reliafy's too.) - **Status:** built for one unit: `operating_schedule_value(model, times, covariates, value_rates, horizon, failure_cost=, down_time=, discount_rate=, age=)` and `best_switch_time(model, covariates, - value_rates, horizon, ...)`. A whole diagram on an operating schedule is - not built: a `RepairableRBD` component cannot yet take a covariate- - dependent life. + value_rates, horizon, ...)`. Built for a diagram, simulated: + `RepairableRBD.best_switch_time(covariates, value_rates, horizon, *, + discount_rate=, mc_samples=, seed=, scan=, engine=, state=)`, whose + switching blocks run on covariate schedules (a spec's `"covariates"`); + each candidate switch time is the diagram with those schedules, + simulated from one seed (common random numbers) and priced as + `npv_distribution` prices its runs, the value split at the switch. - **Who asks, and why:** an operations manager who can raise output at the cost of faster wear, and wants to know whether the extra output pays for the extra failures, and when to change. @@ -1631,11 +1961,19 @@ answers back into dates is Reliafy's too.) switch time against a fine scan, with an end best each way; results scaling with the unit of time from 1e-6 to 1e6 and with the covariate's unit; the refusals, JSON and `help()`. + `test_switch_time_diagram.py`: a one-block diagram against the one-unit + answer (its choice, each end's NPV within its interval, the gain over + switching at once within the interval on the difference); a block the + load does not touch in series, which leaves the switch time; seeded + searches repeat and their intervals narrow with the runs; the value + rates split at the switch against a closed form; the refusals. - **Learned / left:** each unit put in before the last change has its own life, so the work grows with the cells before it (one evaluation of the model along a path each); `best_switch_time` values each switch time to - a looser tolerance by default (1e-4) for that reason. Left: a diagram on - a schedule (covariate-dependent lives in a `RepairableRBD`), a schedule + a looser tolerance by default (1e-4) for that reason. A diagram's search + simulates each candidate; drawing a life along a schedule calls the + model's cumulative hazard a few times per draw, which is most of its + time. Left: a schedule that varies continuously (a `CovariatePath`), and value that depends on more than the stretch. @@ -1688,6 +2026,607 @@ answers back into dates is Reliafy's too.) plan allowed for?) is not given for a diagram yet: the comparison is against the plan's expectation. +### UC-46: "The expected NPV of these two plans is close. How bad could a run of each be, and how likely are we to miss our hurdle?" + +- **Status:** built: `RepairableRBD.npv_distribution(horizon, + discount_rate=, value_rate=, mc_samples=, seed=, hurdle=, tail=, + contract=)` and `compare_npv(other, horizon, ...)`. +- **Who asks, and why:** someone choosing between plans whose expected + NPVs (UC-19) are close: the mean hides the risk, and a plan with a + slightly lower mean and a much better worst case is often the one to + choose. +- **What they know:** the diagram with its costs and value per unit time + while it works, the horizon and the discount rate; optionally a hurdle + the NPV must reach and the share of worst runs to average. +- **How it is solved (simulated, model time):** the runs are the + histories `simulate_timelines` makes (the event loop's, on either + engine, by seed). Each is priced as UC-21 prices a log, with the + diagram's costs at the times they fell (`rbd/_pricing.py`, which + `plan_vs_actual` shares): each failure its repair and replace costs, + each planned outage its preventive cost, each down span its downtime + rate, the system's up spans their value, each discounted exactly; the + acquisition costs are paid at 0 in every run. Only the runs' present + values are kept, made in parts of 2,000. A cost the histories do not + record (a standby group's units' failures, tests, replacements that + take no time, calendar prices, set-up costs, a partial restoration's + replacement) refuses the diagram, naming the cost and + what to run instead, rather than being left out. The summaries are + plain: the mean with its normal interval, percentiles as order + statistics (the `ceil(p n)`-th lowest) with binomial intervals, the + share below the hurdle, and the CVaR as the mean of the `ceil(tail n)` + lowest. +- **The answer:** each run's NPV, value and cost; the mean, its interval + and the split of value and cost by category and component as in + `ExpectedNPV`; P10, P50 and P90; the chance below the hurdle; the CVaR. +- **Contracts and two plans (part 2):** an `AvailabilityContract` pays, + in each period, `bonus_per_point` for each percentage point of the + run's availability above `target` and charges `penalty_per_point` for + each below, at most `cap` either way, at the period's end; a period's + availability is the share of it covered by the system's up spans in + that run. `compare_npv` prices both plans' runs from one seed; each + component draws from its own named streams, so one in the same place + in both plans draws the same numbers (as `compare`), and each run's + difference comes from how the plans differ. A plan with a component + whose draws are not streamed is refused, naming it. +- **Checks:** `test_npv_distribution.py`: the mean against `expected_npv` + (an exponential pump, an age-replaced Weibull unit, a crew-limited + pair); with no discounting, each run against the simulation's own cost + (`cost().samples`) and uptime, also for crews with Weibull lives, which + the exact methods refuse; the engines run for run; a run made in parts + equal to one made whole; the percentiles, CVaR and a binomial interval + by hand. `test_npv_contracts.py`: a target of 0 pays nothing; a + system that never fails paid in closed form (a capped bonus each + month); each run's payments against its own availability by period, + and the periods' uptime against the run's; identical plans differ by + exactly 0, with and without a contract; the difference's variance + below the sum of the plans' (about half the independent standard + error with a contract, whose thresholds pay on small differences in a + period's uptime the plans do not share). +- **Learned / open questions:** a cost given as a distribution is charged + at its mean (`priced_at_mean`), so the spread is that of the events + alone; the costs the histories do not record could come from the event + loop's own records, which would change both engines. + +### UC-55: "The plan's NPV rests on a discount rate we argue about and on lives fitted to a few failures. How much does each move it, and would the intervals we chose still be the best?" + +- **Status:** built: `expected_npv(..., rate_sensitivity=True)`, + `RepairableRBD.expected_npv_uncertainty(horizon, uncertainty, ...)` + and `optimal_replacement_intervals(..., robust=True | "reoptimise", + uncertainty=, n_draws=, seed=)`. +- **Who asks, and why:** an owner signing off a plan valued by UC-19 and + chosen by `optimal_replacement_intervals`. The finance team's rate is + a range, not a number, and the lives came from a few dozen failures: + a choice made on point estimates can be the wrong one once that is + counted, and they want to know how often, and what it would cost. +- **What they know:** the diagram, its costs and value rate, the horizon + and the rate; which models are fitted (their covariance, or a Bayesian + posterior), or distributions over parameters given by hand. +- **What they want back:** `d NPV / d r` with its error; an interval on + the NPV, which inputs make it wide, and what was held fixed; for a + choice of intervals, the share of plausible models under which it is + still the best and the expected regret where it is not. +- **How it is solved:** + - *The rate (numerical):* the NPV is analytic in `r`, each amount at + `t` weighed by `exp(-r t)`. Its derivative is Richardson's + extrapolation of differences on steps `h = 0.01 / T` and `2h` + (`T` the time valued, so the steps follow the unit of time), central + where the rate stays at least 0 and one-sided from it otherwise; a + third of the two steps' difference is the stated error. Weighting + each cash flow by `-t exp(-r t)` through every integral would be + exact, but would add a second weighted path to each of the cost + integrals; four more valuations do it with the code that values the + plan. + - *The models (sampled):* the draws are those of + `expected_cost_rate_uncertainty` (`_repairable_uncertainty.draws` + and `build`), each draw valued by `expected_npv` exactly. The shares + are the delta method's, as `uncertainty_importance(method="delta")` + gives them: the NPV's derivatives in each drawn parameter (a central + difference of 1% of the lever, the step `parameter_sensitivity` takes + over time) against the parameters' covariance. Models no input draws + are listed as held fixed. + - *The choice (sampled):* under each draw, the choice and its + neighbours (each interval one step either way: the next allowed + interval, or a quarter longer or shorter in a continuous search) are + scored by the plan's own objective and target, all under the same + draw, so their differences are not blurred by draws they do not + share; the share in which the choice wins and its mean regret + follow. Choosing again under each draw (`"reoptimise"`) is offered, + slower; its share of draws with the same choice is given only for + allowed intervals, as a continuous search never lands on the same + point twice. +- **Today:** `expected_npv` at two rates by hand gave a difference + quotient; the uncertainty methods gave the availability and the cost + rate, not the NPV; nothing scored a choice under other models. +- **Checks:** `test_npv_uncertainty.py`: the rate sensitivity against a + closed form for an exponential pump at 8% a year, at 0 and just above + it (to 1e-6, inside the stated error), against a small change of rate, + and a salvage's part against `-T exp(-r T) S`; each draw's NPV against + the closed form at its drawn rate; the delta method's variance against + the closed form's derivative and the fit's `lambda^2 / n`, and the + draws' variance against it; seeded draws repeat; a choice built to flip + under one of two lives is the best in exactly the draws of the other, + with the regret the other life's own choice saves, and the same by + re-optimising. +- **Learned / open questions:** the neighbours' regret is a lower bound + on the regret against each draw's own optimum; the two agree where the + optimum moves at most one step. The delta method's shares assume the + NPV close to linear over the spread: the draws' variance beside + `delta_variance` says whether it is. + +### UC-56: "We have outages planned at 800, 1,500 and 2,500 hours. The pump is replaced every 1,200 hours anyway; at an outage, we'd rather change it if it's past 500. How many pumps does each outage take, and what does that save?" + +- **Status:** built (simulated): a shutdown's `"opportunistic": {node: + age}` (or one age for every block in its scope under age + replacement). +- **Who asks, and why:** the planner setting an outage's scope. The + plant is down anyway, so a part close to its own replacement is + changed then rather than on its own downtime later: that is how real + shutdown scopes are set, and it changes what the plan costs and is + worth. +- **What they know:** the diagram; the part's own age replacement (its + interval, cost and duration); the outages (UC-24: times or a period, a + duration, a scope); for each part, the age past which it is changed at + an outage. +- **What they want back:** for each outage, how many parts it is + expected to take, with a confidence interval; the plan's availability + and cost with the rule, against without it. +- **How it is solved (simulated):** at each start of the shut, the + Python event loop renews each listed part that is working and at + least that old (its time since it was put in), as a stop of a + maintenance group renews a member early (`_event_loop._stop`): the + failure or replacement it had ahead is cancelled, the renewal takes + the part's own preventive cost and duration, and its next age + replacement counts from then. A part in such a shut's scope is worked + on there, so a shut that stands idle blocks still does not stand it + still. The runs count each outage's renewals (and their squares), so + `outage_jobs` gives each outage's mean count, standard error and 95% + interval; `opportunistic_renewals` gives each part's total, and the + renewals are charged as the part's preventive work. An age of `inf` + renews nothing, so the rule is then the plan without it, seed for + seed. A shut in no time with the rule is a moment that renews parts + and holds nothing. +- **Exact routes:** refused: a part's renewal at an outage depends on + its age then, which ties its renewals to the outages' times in a way + the curves over time (each part's renewal process on its own + calendar) do not follow. The message names `availability()` and + `cost()`. numba's loop does not run it: `_compiled.unsupported` names + the shutdowns, and the Python loop runs them (as for any shut that + takes time, costs or falls at given times). +- **Today:** `"older_than"` on a task bound to a shutdown renews a part + with no schedule of its own at a shut once that old; a part with its + own age replacement could not be renewed at an outage. +- **Checks:** `test_outage_opportunistic.py`: an age of `inf` gives the + plan without the rule to the last bit (and the exact methods the same + value); with the age of the first outage's time, the count there is + the chance the part never failed, `R(800)`, within its interval, with + the binomial standard error; the counts by outage add up to the + part's renewals; the renewals cut the cost and are charged as + preventive work; a single age is the dict of every age-replaced part + in scope; chunks merged give the run's counts; saving; the refusals + and the checks of the rule. The catalogue's "outages renewing + opportunistically" runs every analysis against its route. +- **Learned / open questions:** the renewals are charged in the + `"preventive"` category, as a group's opportunistic renewals are, + rather than a category of their own (which would widen every cost + table and both engines' arrays); their cost is the count times the + part's preventive cost. `npv_distribution` prices them (UC-61). + +### UC-57: "Our selling price steps up next year, labour rises 4% a year and parts 2%, and finance quotes a real rate of 5% with 3% inflation. What is the plan worth, and does it matter whether we work in real or nominal money?" + +- **Status:** built: `expected_npv(..., value_rate=ValueSchedule(times, + rates), escalation={stream: g}, rates="nominal" | "real", + inflation=)`; on dates, `escalation=` beside `discount=` in + `repyability.schedule` (`Task.due`, `Task.long_run_value`, + `work_by_period`, `failures_by_period`, `events_by_period`, + `task_value`). +- **Who asks, and why:** the analyst valuing a plan over ten years. A + constant price and constant costs (UC-19) overstate a plan whose + costs rise faster than what it earns, and a rate quoted in real terms + applied to nominal prices (or the other way round) is the commonest + error in an NPV. +- **What they know:** the diagram, its costs (`repair_cost`, ..., + `downtime_cost_rate`, the lost production) and what it earns while it + works (`value_rate`), each in today's money; how each stream grows; the + rate and whether it is real or nominal, and inflation. +- **What they want back:** the NPV, its cash-flow table with every + stream grown (nominal, or real), and the basis stated on the result. +- **How it is solved (as exact as `expected_npv` is):** + - *What the plant earns:* `value_rate` is a number or a + `ValueSchedule(times, rates)`, steps in model time (plain data, so a + valuation can be saved and made again; a function of time is + refused). A step `v` on `[a, b)` with growth `g` adds `v * integral + exp(-(r - g) t) A(t) dt`, the uptime integral `expected_npv` already + takes at the rate `r - g`, differenced at the steps' ends. + - *Escalation:* each stream (a cost category: `repair`, `replace`, + `preventive`, `inspection`, `component_downtime`, `system_downtime`, + `setup`, `shutdown`, `crews`; a component, which takes precedence + over its categories; `"value"`; `"salvage"`) takes a continuous + growth `g`: an amount at `t` is its price times `exp(g t)`, so its + present value is the cost discounted at `r - g`, worked out once for + each distinct `r - g` by the existing discounted cost + (`_windows.expected_cost`, or `_windows._discounted_cost` for a + rate below 0, which is valid over a horizon); the undiscounted + column is at `-g`. The downtime cost rate and the value rate are the + streams `system_downtime`/`component_downtime` and `value`: no + second notion of either. The acquisition is paid at 0 and does not + grow. + - *Real or nominal:* `rates="nominal"` (the default) takes the rate + and growths as given. `rates="real"` takes them in real terms; with + `inflation=i`, every amount is made nominal (the rate `r + i`, every + stream's growth `g + i`, a stream with none `i`), which leaves every + present value as it is and makes the undiscounted columns nominal. + The result states `rate_basis`, `inflation`, `escalation` and + `value_schedule`, and its `discount_rate` is the rate given, so the + equivalent annual cost is the level annuity in the basis given: a + level real annuity with real rates. + - *On dates:* `escalation=` is an effective yearly rate (0.03 for 3% a + year) beside the yearly `discount=`: a cost `y` years after the start + is worth `((1 + e) / (1 + d)) ** y` of its price today, so every + present value (and the equivalent annual cost) is taken at the net + yearly rate `(1 + d) / (1 + e) - 1`, which may be below 0 over a + window; for ever (`Task.long_run_value`) it must be above 0. The + expected costs by period stay in today's prices, as the note says. +- **Today:** a constant `value_rate` and no growth; a schedule had to be + valued as runs over sub-horizons and added up by hand. +- **Checks:** `test_npv_escalation.py`: an exponential unit with a + value growing at `g` against the closed form; a schedule of two steps + against the sum of the steps valued apart; a stream's escalation + against the cost discounted at `r - g`, also with `g > r`; the + real/nominal identity (every stream lifted by inflation leaves the NPV + unchanged); no growth and a number for the value give every field + unchanged to the last bit; a component's growth taking precedence over + its category's; a salvage grown at its own rate; the refusals. On + dates (the same file): a task's present value with + escalation against the factor worked by hand, `events_by_period` + against `expected_npv` with the matching continuous rates, and for + ever refused when the escalation reaches the rate. +- **The spread and the log (part 2):** `npv_distribution`, + `compare_npv` and `plan_vs_actual` take the same `value_rate`, + `escalation`, `rates` and `inflation` (and `best_switch_time` the + last three, its value being its two rates). A run or a log is priced + as UC-46 and UC-21 price it (`rbd/_pricing.py`), each amount at `t` + its price times `exp(g t)` for its stream, so discounted at `r - g`: + an event `p exp(-(r - g) t)`, a rate over a span `v * integral + exp(-(r - g) t) dt` in closed form, and an up span cut at each step of + the schedule, each piece at its step's rate. A contract's payments + grow only with the inflation of real rates. `plan_vs_actual`'s plan is + `expected_npv` with the same arguments; the rest from now is valued on + its own clock with the schedule's steps from now (the step in force + then from 0), and each of its rows grown to now (`exp(g now)`) and + discounted to the start (`exp(-r now)`), so a stream's present value + is `exp(-(r - g) now)` of the rest's. Checks in + `test_npv_value_runs.py`: each run's value and cost against a + reference written out from its history (to 1e-12); the runs' mean + against `expected_npv` with the same schedule and growths (4,000 + runs, a 99.99% interval); one step and no growth equal to the rate + alone to the last bit; inflation leaving the present values (1e-12) + and lifting the undiscounted; two plans with an escalation that names + a component of only one; a pump that all but never fails, whose rest + from now is the plan after now row by row (1e-6), and whose log is + priced by hand; so far plus the rest averaging to the plan with a + step inside the rest (the tower property, 60 histories); the switch + time's present values unchanged by inflation; a JSON request. +- **Learned / open questions:** a contract's payments are no stream of + `escalation` (they grow with inflation alone): terms that index them + would be a contract's own option. + +### UC-58: "At the outage the pump is overhauled, and leaves as if 3,000 hours old whatever it was before. What does that do to the plan?" + +- **Status:** built (simulated): a `"preventive"` spec's `"restore_to": + age`, for a task at a shutdown (UC-24) or on the part's own calendar. +- **Who asks, and why:** the planner whose overhaul contractor states + the result as an age ("as good as 3,000 hours"), not as a share of the + age taken away, which is what a Kijima factor (`"restoration"`) says. +- **What they know:** the diagram, the outages and their scope, the part's + life, and the age the overhaul leaves it at. +- **What they want back:** the plan's availability, failures, costs and + their spread, as for any simulated plan. +- **How it is solved (simulated):** the task sets the unit's virtual age + to the age given, whatever it was (`_ImperfectComponent.maintained`, + beside Kijima I and II, `_Restoration` with `kijima="to_age"`); the + unit's next life is drawn given that age from the end of the task + (`_aged_life`, the virtual age's own stream), as a Kijima restoration + draws it. `restore_to=0` is a renewal: it is taken as no restoration at + all, so it is exact wherever a renewal is and the same simulation, seed + for seed. A part restored to an age is refused by the exact methods, as + a Kijima restoration is ("restored only partly ... to a virtual age of + 3000"), naming `availability()` and `cost()`; numba's loop leaves it to + Python (`_compiled.unsupported`: a restoration, and a dated shut). + `"restore_to"` and `"restoration"` are one or the other. The age is a + number; an age that depends on the age before is a Kijima factor + already. +- **Today:** a Kijima factor only, whose age left depends on the age + before. +- **Checks:** `test_restore_to.py`: `restore_to=0` the renewal's run to + the last bit, and its exact values; a memoryless part unchanged by any + age (against the renewal's exact availability, within the run's + error); a Weibull part whose repair outlasts the window (so it fails at + most once) against its survival from the age given, `R(TAU) R(a + t - + TAU - D) / R(a)`, integrated, at two ages, and far from the renewal's; + the refusals; saving. The catalogue's "outages restoring to an age" + runs every analysis against its route. +- **Learned / open questions:** an age that is a function of the age at + the outage was left out; Kijima II is the proportional one. + +### UC-62: "Our 250-hour service is invasive: the fit of the pump's history says each one leaves it older than it was (Kijima II, q = 1.1). What does that do to the failures, and is the service worth stopping?" + +**Who asks.** A reliability engineer whose fitted restoration factor +(surpyval's `GeneralizedRenewal` on the pump's repair and service history) +came out above 1: services that disturb a working unit (a seal reseated, +a bearing reassembled) and make an early failure more likely. + +**What they know.** The pump's life (Weibull, scale 1,000 h, shape 2.5), +replaced at a failure for 400; the service every 250 h, 4 h long, 20 a +time; the fitted factor, Kijima II, `q = 1.1`. + +**What they want back.** The failures with and without the service, and +the value of the service against not doing it, at 7% a year over a year. + +**How it is solved.** A `"preventive"` task with a `"restoration"` whose +`q` is above 1: Kijima's definitions hold for any `q` from 0, a service +after an operating time `x` since the last action taking the virtual age +`v` to `v + q x` (Kijima I) or `q (v + x)` (Kijima II). Below 1 the task +takes age away; at 1 it leaves the unit as old as it was; above 1 it adds +age. Only a task may do that: a repair's `q` stays in [0, 1], as a +repair restores a failed unit. The simulation takes it as it takes any +restoration (the compiled engine hands a restoring task to the Python +loop, as before), and `compare_npv` values the plan with the service +against the plan without it, run by run on the same random numbers. + +**The hand-worked answer.** With no failure, tasks at 250, 500 and 750 h +leave the virtual age at 275, 577.5 and 910.25 h under Kijima II with +`q = 1.1` (275, 550 and 825 h under Kijima I), against 250, 500 and 750 at +`q = 1`. The chance of no failure by 1,000 h is `exp(-sum of H over the +four pieces)`, `H(t) = (t / 1000)^2.5`: 0.295142 under Kijima II and +0.326487 under Kijima I with `q = 1.1`, and `exp(-1) = 0.367879` at +`q = 1`, which is the pump with no service at all (each piece of `H` +continues where the last stopped). At `q = 0.5` it is 0.703789 (II) and +0.618741 (I): a good service. + +Simulated (4,000 runs, seed 8, instant repairs, services in no time), +the failures over 3,000 h are 2.974 at `q = 1` (the renewal function +without service: 2.973), and under Kijima II 3.233 at 1.1 and 3.488 at +1.2 (standard errors 0.013). With the 400 failure cost, the 20 service +and 4 h service outages, over a year at 7% (4,000 runs, seed 3), the +service at `q = 1.1` is worth -918.97 (standard error 11.67) against no +service, worse in 87% of the runs: worth stopping. At `q = 0.5` it is +worth +1,528.85 (standard error 13.00). + +**Checks.** At `q = 1` the chance of surviving the pieces equals the +pump without service, exactly, and Kijima I and II give the same runs to +the bit (`v + 1 x` and `1 (v + x)` are the same number); the survival +chance with `q = 1.1` against the closed form above; failures and cost +rise with `q` above 1; a repair's `q` above 1 is refused, saying only a +task's may be. + +**What was learned.** Nothing new was needed in the engines: Kijima's +arithmetic was already right for any `q`; only the check on the spec +held it to [0, 1]. A factor above 1 is how harmful or invasive +maintenance is modelled, and the NPV comparison is how a plan shows that +a task is worth stopping. + +### UC-63: "One pump's plan: what are its tasks and prices, and how does the diagram take it?" + +**Who asks.** Anyone who writes a unit's maintenance down once and uses +it in several places: on a diagram today, valued alone or on the +calendar later. And a caller (the Reliafy app) that keeps a unit's plan +as a record and hands it over, rather than assembling a spec dict. + +**What they know.** The pump's life (Weibull, scale 1,000 h, shape 2.5) +and its repair time (exponential, mean 10 h); a service every 4,000 +operating hours that renews it, 20 a time, taking a fixed 4 h; a repair +costs 400 and its own downtime 5 an hour. It runs 60% of the time. + +**What they want back.** One object that says all of that, each task in +its own clock (4,000 operating hours is kept as operating hours, a +task at the site's shutdowns as a binding to them by name, a calendar +policy as the policy), that a `RepairableRBD` node takes as it takes +the spec dict, and that saves and loads. + +**How it is solved.** `UnitPlan(life, repair, tasks=(...), +prices=Prices(...))`, frozen plain data. Each task is its own object: +`AgePolicy`, `BlockPolicy` (on an interval or at given times), +`ConditionPolicy` (a threshold or a measured level), `CalendarReplacement` +(a `CalendarPolicy` or `ShutdownPolicy`), `AtShutdown` (bound to the +site's shutdowns by name), `Inspection` and `Upgrade`; a task that +restores partly carries a `Restoration` (Kijima, to an age, or a fitted +process; every so many tasks a replacement), and imperfect repairs an +`ImperfectRepair`. A task's own price is the task's (`cost`), as each +task has its own; the unit's prices (repair, replace, its own downtime, +acquisition) are `Prices`. A task counted in operating time says so +(`basis="operating"`). What belongs to the system stays on the diagram: +structure, system downtime and value, crews, spares, the site's +shutdowns and common-cause groups (a plan only names its maintenance +group and its place in the crews' queue). + +The spec dict is the plan's shorthand: `UnitPlan.from_spec(spec)` +reads one, and `plan.spec()` writes the spec the diagram's engines read. +A node given a plan is the node given its spec, so every analysis, the +routes, the levers and saving take it unchanged; `RepairableRBD.plans` +reads each spec node back as a plan. + +**The hand-worked answer.** The plan above and the spec + +``` +{"reliability": Weibull(1000, 2.5), "repairability": Exponential(0.1), + "repair_cost": 400, "downtime_cost": 5, "duty": 0.6, + "preventive": {"policy": "age", "interval": 4000, "basis": "operating", + "cost": 20, "duration": ExactEventTime(4)}} +``` + +are one node: `plan.spec()` is that dict, and `from_spec` of it is the +plan. Seeded, a diagram of plans and the same diagram of specs give the +same runs to the last bit, on both engines; their routes are the same. + +**Checks.** Every spec of the test catalogue reads into a plan and back +to the same spec (up to keys at their defaults, such as an `"age"` +policy or an `"instant"` duration); a reader that met a key it does not +place refuses, so a new spec key cannot be dropped quietly. Diagrams of +plans against diagrams of specs, seeded, to the bit, on both engines; a +plan node in the catalogue; a plan saves and loads; a plan with two +preventive tasks is refused, saying a spec holds one (bind it to several +shutdowns instead). + +**What was learned.** The spec's keys already were a unit's plan; what +the plan adds is a name for each task and its clock, and one place a +unit's maintenance is written down. Salvage, a unit's own escalation and +retirement were the analyses' arguments (`expected_npv(salvage=, +retire_at=, escalation=)`); they joined the plan when a plan was valued +alone (UC-65). + +### UC-65: "What is this pump's plan worth alone over eight years at 7%, and its cash flows by year?" + +**Who asks.** The planner of UC-63, who has written the pump's plan down +once and wants it valued without drawing a diagram around it: its net +present value, a yearly table to put beside the budget, how bad a run +could be, how the plan has gone so far, and its cost per year in the +long run. The caller (the Reliafy app) values a unit's plan alone as it +values a system. + +**What they know.** The pump's life (Weibull, scale 20,000 h, shape +2.5) and repairs (exponential, mean 24 h, 6,000 each); a renewal at +12,000 h of age for 1,500; bought for 40,000 and worth 5,000 when it +goes; eight years of 8,760 h at 7% a year. + +**What they want back.** The NPV, the cash flows by year and category, +and the other valuations a diagram has, with the salvage (and, where +given, the growth of its prices and its retirement) held by the plan. + +**How it is solved.** A plan alone is the diagram of its one node, +`UnitPlan.diagram()` (the node named `UnitPlan.NODE`, `"unit"`), and +each valuation of the plan is that diagram's method with the same +arguments: `expected_npv`, `cash_flows` (its table), `npv_distribution`, +`plan_vs_actual` (one `Timeline`), `expected_cost`, +`expected_cost_rate`, `events_by_period` and `failures_by_period` (the +diagram's events on the calendar), the optimisers and `analysis_routes`. +There is no second route: the diagram's exact methods are already the +single unit's (its renewal curves, age and block replacement, the tested +unit's model), so a plan alone and a diagram holding it agree by +construction, exact where the diagram is exact and simulated where it +simulates. A `calendar` (a `schedule.CalendarContext` whose duty names +`"unit"`) puts the diagram on it first, as `CalendarContext.diagram` +does. + +The unit's own money moves onto the plan: `salvage` (a number or a +function of the age of the unit in service), `escalation` (one growth +rate for all its prices) and `retire_at`. They are spec keys of the same +names, so a diagram holding the plan takes them too: `expected_npv` +takes each as its argument of the same name for the node, an argument +given for the node taking precedence (a system's salvage, a number, is +added to the units' own). A unit retiring is the system's retirement +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, 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 +`expected_npv(8 * 8760, discount_rate=log(1.07) / 8760, salvage={"p": +5000}, periods=8)`: an NPV of -48,719 (the purchase 40,000, the repairs +and renewals, the salvage's 5,000 worth 2,910 now), an equivalent +annual cost of 8,357 a year, and eight yearly rows by category. The +plan alone gives the same numbers to the last bit. + +**Checks.** `test_plan_alone.py`: over every plan of the catalogue that +stands alone (no maintenance group, site shutdown or standby group), the +plan's `expected_npv`, `expected_cost_rate` and `npv_distribution` equal +a diagram holding it, drawn and named otherwise, to 1e-12 (or both +refuse alike), and their routes agree; on a calendar of one share and +of weekday shifts, the plan's runs, expected NPV and events by week +equal its diagram on that calendar; the plan's salvage (a number and by +age), escalation and retirement equal the arguments for the node, the +arguments win, a retirement past the horizon is the horizon, a unit's +retirement in a diagram of several is refused, the runs refuse a +salvage by age, and the terms save and load; each run of a plan with a +salvage or retirement is the run of the plan without, to the +retirement, plus the salvage `expected_npv` credits +(`test_npv_runs_own_end.py`); the exact NPV is the mean of +4,000 seeded runs within four standard errors. + +**What was learned.** The diagram is already the single unit's engine; +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) 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?" + +- **Status:** built: a `"preventive"` spec's `"shutdown"` given as a + list of the diagram's shutdowns, valued over a horizon by + `point_availability`, `mission_availability`, `expected_events`, + `expected_cost`, `expected_npv` and the windows, with no simulation. +- **Who asks, and why:** the planner of a line with more than one kind + of outage (a short stop on a period, a long overhaul, outages at given + times), where a part is renewed at each and the renewal takes as long + as the outage it is done in. A task naming one shutdown could not say + this. +- **What they know:** a line of a pump (Weibull 20,000 h and 2.5, + repairs lognormal, 6,000 each, renewed only at the overhaul for 2,500) + and a bearing (repairs exponential, 12 h mean, 1,500 each, renewed at + both for 200); 400 an hour down; a stop every 730 h for 4 h (300 each) + and an overhaul every 8,760 h from 365 for 48 h (5,000 each). +- **What they want back:** the plan's cost and value over two years at + 8% a year, the failures and renewals to expect, and the availability. +- **How it is solved:** numerically, as a plan of replacements is + (UC-51): the part's renewal times are its shutdowns' starts merged, up + to the first after the horizon, and the part is followed stretch by + stretch between them (`_block_replacement.plan_availability`), each + stretch's grid taking the length of the renewal that starts it (its + own shut's) and the shutdowns' windows holding it off line + (`MaskedCurve`). The simulation (Python only) renews it at the first + start of any of its shutdowns, for that shut's length + (`_Preventive.due`, `duration_at`). The renewals repeat on no interval + of the part's own, so the long-run methods refuse and name the values + over a horizon; a long-run state, or a state in a renewal (whose shut + and time left are unknown), is refused. Two of the shutdowns may not + start at one time (which renewal is done there would not be said), + and a task kept unless due or restoring part-way is at one shutdown. +- **Today (by hand, before it was built):** only by simulation, the + bearing drawn as a block renewed at each of two shuts not being + something a task could say. By hand for an exponential bearing alone + (rate 1/3,000, repair rate 1/12), its two-state chain between + renewals of their own lengths (4 h, 48 h) gives its availability at + 1,000 h and 9,200 h as 0.996016 and 0.996423; the built curve gives the + same to 1e-6. The line, as built: + + ```python + plan = line(bearing_life) # the diagram above + value = plan.expected_npv(2 * 8760.0, discount_rate=np.log(1.08) / 8760.0) + # exponential bearing (mean 3,000 h): 141,458 undiscounted, 132,815 + # discounted; availability 0.98508; bearing failures 5.75, renewals 24.90 + # Weibull bearing (3,000 h, 2.0): 113,611 and 106,994; availability + # 0.98810; bearing failures 1.31, renewals 24.96 + ``` + + The simulation (`cost(2 * 8760, mc_samples=4000, seed=1, + control_variate=False, conditional=False)`) gives 141,834 ± 318 and + 113,493 ± 175. +- **Checks:** `test_shutdowns_several.py`: a list of one shutdown its + shutdown's values to 1e-10 (on a period and at given times); two + shutdowns of one length one shutdown at the merged times, to 1e-10; an + exponential block against its chain between renewals of two lengths + written out by hand; the simulation from new, from an age and from a + repair going on, 20,000 seeded runs within four standard errors; the + refusals; saving. The catalogue's "a block renewed at several + shutdowns" runs every analysis against its route. +- **Learned / open questions:** + - A block kept unless due, or tested, at shutdowns at given times is + still simulated: its recursion keeps the units by age on a grid of + one step from one inspection to the next, which stretches of + different lengths do not share. + - The same block drawn as two blocks in series is a different system + (each renewed at only its own shut), not this one. + ### UC-22: "A pump's 6-monthly overhaul restores it only partly (a fitted Kijima restoration factor), and every third overhaul replaces it. What availability, failures and cost per year, against overhauls that renew it, and which overhaul interval is cheapest?" - **Status:** built (#398): a `"preventive"` spec's `"restoration"` (Kijima's @@ -2039,21 +2978,30 @@ answers back into dates is Reliafy's too.) ### UC-24: "Our outages are planned at given times, each with a duration and a scope: some blocks are renewed in them, others restored. What does the plan cost by window, and what is it worth?" -- **Status:** built in part: the same `shutdowns`, at `"times"` with a +- **Status:** built: the same `shutdowns`, at `"times"` with a `"scope"`, and the work on each block (`"preventive": {"shutdown": - ..., "restoration": ...}`), simulated by `availability` and `cost`. - `expected_npv`, `expected_cost` and `cost_by_window` (whose mean is - exact) take shuts on a period only, and refuse given times, as does a - restoration (UC-22) anywhere. + ..., "restoration": ...}`). Where every job renews its block, + `expected_npv`, `expected_cost`, `expected_events_by_window` and the + other values over a horizon are worked out (numerical, as block + replacement is); a job that restores part-way (UC-22) is simulated by + `availability` and `cost`, and the exact methods say so. The outages + end, so the long run is refused. - **Who asks, and why:** a planner laying out the next four years of outages, irregularly spaced, who wants the plan's cash flows. - **What they know:** the line of UC-23; outages at 3,000, 12,000 and 26,000 h, 72 h each, holding the pump and motor off line, 10,000 each; the pump renewed in each, the motor restored (Kijima I, `q = 0.5`). - **What they want back:** the cost in each year, and its present value. -- **How it is solved:** simulated: the windows at their times, the tasks - bound to them at those times (`_Preventive.due` and `_Inspection.due` - read the times). +- **How it is solved:** a block renewed at the outages is a block + replaced at their times (UC-51's stretches, each replacement taking + the outage's length), the blocks in scope are held off line by the + same mask as on a period, at the given windows, and each outage's + cost is an event at its start. Simulated: the windows at their times, + the tasks bound to them at those times (`_Preventive.due` and + `_Inspection.due` read the times). A list of different outages is + several shutdowns, each with its times, duration, scope and cost; no + second record (an `Outage` class) was added beside `shutdowns` and + `Opportunities.on_diagram`, which writes them. - **Today (by hand, and as built):** the cost to each year's end by `cost(..., seed=1)`, differenced (2,000 runs each): @@ -2068,17 +3016,510 @@ answers back into dates is Reliafy's too.) Discounted at 8% a year at each year's middle, about 195,400. The shutdowns' own cost is 10,000 at each of the three, and each run's `shutdowns` is 3. -- **Checks:** `test_shutdowns.py` (shuts at given times simulated, their - count and cost, the exact methods' refusal). +- **As built, renewing both blocks** (the motor renewed too, at 2,000): + + ```python + value = rbd.expected_npv(4 * YEAR, discount_rate=np.log(1.08) / YEAR, + periods=4) + # by year: 56,310, 69,046, 76,488, 19,447; in all 221,291.9 + value.cost # 193,053.7 at 8% a year + value.cost_by_category["shutdown"] # 26,697.2 (10,000 at each) + rbd.mission_availability(4 * YEAR) # 0.99238 + rbd.cost(4 * YEAR, mc_samples=4000, seed=1, control_variate=False) + # 220,643 ± 551, simulated + ``` + + `maintenance_effect(4 * YEAR)` splits the 267.0 h down into 215.8 + planned and 51.3 unplanned, exactly (215.8 and 50.8 simulated). +- **Checks:** `test_shutdowns.py`: outages at a period's times against + the shutdown on that period (to 1e-10); one outage renewing a unit + against its replacement at that time and the window by hand; the + simulation, from new and from a state; the outages' count and cost; + the long run's refusal and what is left to the simulation. - **Learned / open questions:** - - The exact cost by window and NPV of shuts at given times need the - over-time machinery to take windows at given times (a curve's - settling, the integrals' pieces): the mask works on any windows, but - the long run and the curves' periods assume a period. Small to add - where nothing settles before the last shut; not done here. + - A shut at time 0 holds its blocks but does no work on them (a + task falls due after 0, as in the simulation). + - A block is worked on at one shutdown's times: one renewed in + outages of different lengths or scopes (two shutdowns) is not said + yet. Nor is a restoration to a given virtual age: a job restores by + a Kijima factor (UC-22). + - A block kept unless it is due (`"older_than"`, on condition) at + outages at given times is numerical too: its recursion runs stretch + by stretch, the kept units' ages moved onto each stretch's grid + keeping their mass and mean age. Equally spaced times give the + period's values (within 1.1e-8), a threshold of 0 renewing at every + outage, and an age past the horizon no task, to the grid's + first-order error (2.2e-7 at 2,000 steps a stretch, halving as the + steps double). One tested at them is simulated: its recursion is on + a period. - `cost_by_window` and `expected_npv` could take the simulated mean where the exact one refuses, as `cost_by_window` does for its spread. +### UC-51: "The pump is replaced at 8,000, 14,000 and 26,000 hours, not on one interval. What will that plan cost over four years, what is it worth at 8%, and how available is the line?" + +- **Status:** built: a `"preventive"` spec's `"replace_at"`, valued over + a horizon by `expected_npv`, `expected_cost`, `expected_events`, + `mission_availability` and `point_availability`, with no simulation. +- **Who asks, and why:** a planner whose jobs are a list of times (the + outages there are, the budget's years), not one interval; every later + question about a plan on a timeline (outages with a scope, upgrades, + re-planning from today) starts from this one. +- **What they know:** a line of a pump (Weibull life, 12,000 h and shape + 2.5; repairs lognormal, 9,000 each) and a motor (Weibull 40,000 h and + 1.5; 15,000 each), 400 an hour while the line is down; the pump + replaced at 8,000, 14,000 and 26,000 h if it is up, at 3,000 and about + 12 hours each. +- **What they want back:** the cost in each year and its present value, + the replacements and failures to expect, and the availability. +- **How it is solved:** numerically, as block replacement is, which it is + at any list of times: the unit is followed stretch by stretch, from + one time to the next, each on a grid of its own length + (`_block_replacement.plan_availability`), the repairs and replacements + still going on at a time carried onto the next stretch's grid; each + replacement is an event at its exact time, counted and discounted + there. After the last time the unit is replaced no more. From a state + the times are counted from now. +- **Today (by hand, before it was built):** only by simulation (the + times given to a shutdown of no length, the pump's task bound to it), + or, for equal gaps, block replacement on a period. As built (its own + simulation, `cost(4 * 8760, mc_samples=4000, seed=1, + control_variate=False)`, gives 91,867 ± 657): + + ```python + plan = line({"replace_at": [8_000.0, 14_000.0, 26_000.0], + "duration": LN([2.5, 0.3]), "cost": 3_000.0}) + value = plan.expected_npv(4 * 8760.0, discount_rate=np.log(1.08) / 8760.0, + periods=4) + value.undiscounted_cost, value.cost # 91,650.6 and 77,679.1 + # by year: 19,886, 20,116, 32,597, 19,052 + plan.expected_events(4 * 8760.0) # pump: 1.586 failures, 2.990 replacements + plan.mission_availability(4 * 8760.0) # 0.99588 + ``` + + Block replacement every 8,000 h costs 78,144.8 at the same rate. +- **Checks:** `test_replace_at.py`: equally spaced times against block + replacement on that period (to 1e-10); an exponential unit against its + two-state chain between replacements that take a fixed time, and a + Weibull unit that fails once at most, in closed form; replacements + discounted at their times; uneven stretches against grids four times + as fine; the simulation, from new and from a state; the refusals. +- **Learned / open questions:** + - A plan ends, so there is no long run to ask for: the long-run + methods refuse and say to ask for a horizon. + - The stretch after the last time is as long as the horizon needs, on + the other stretches' step, up to 80,000 steps: a horizon tens of + times the plan's longest gap past its last time is followed more + coarsely. + - A stretch far shorter than the repairs cannot be followed on its + grid (as a block interval cannot) and refuses. + - `plan_vs_actual` values the rest from today on the same diagram, + where a plan's times would be counted again: refused for now; the + rest is `expected_npv(state=)` on a diagram with the times still to + come. + - The compiled engine leaves a plan to the Python loop. + +### UC-52: "The pump is worn. Is upgrading it at 2,000 hours for 30,000 worth it, or should we retire it at 6,000 hours and sell it for 8,000?" + +- **Status:** built: a component spec's `"upgrade"`, and `retire_at=` + and `salvage=` on `expected_npv`. +- **Who asks, and why:** whoever holds the capital budget: an upgrade, a + retirement and a resale are what a net present value is for. +- **What they know:** a pump failing every 500 h on average, repaired in + 50 at 2,000 a repair, earning 40 an hour while it works; an upgrade at + 2,000 h, for 30,000, to a pump failing every 2,000 h; or its sale for + 8,000 at 6,000 h; 8% a year, over 8,000 h. +- **What they want back:** each plan's net present value, with the + capital and the salvage in the cash flows. +- **How it is solved:** an upgrade is a replacement at its time by a unit + of another life (UC-51's stretches, the stretches from the upgrade on + with the new life), the capital cost an event at that time. A + retirement cuts the valuation at its time. A salvage is credited at + the end and discounted from there; by age, its expected value over the + age of the unit in service (never failed, or put in at the end of a + repair and up since), for a plain component from new. +- **Today (by hand, before it was built):** the two-state chains either + side of the upgrade, integrated against `exp(-r t)` in closed form + (the test's `worth`): 252,977.9 kept as it is, 253,936.5 upgraded, + 199,015.8 retired at 6,000 h with the sale. As built: + + ```python + kept = pump().expected_npv(8000.0, discount_rate=r, value_rate=40.0) + upgraded = pump(upgrade={"at": 2000.0, "reliability": E([1 / 2000.0]), + "cost": 30000.0}).expected_npv( + 8000.0, discount_rate=r, value_rate=40.0) + retired = pump().expected_npv(8000.0, discount_rate=r, value_rate=40.0, + retire_at=6000.0, salvage=8000.0) + kept.npv, upgraded.npv, retired.npv # 252,977.9, 253,936.5, 199,015.8 + ``` +- **Checks:** `test_upgrade_retire_salvage.py`: an upgrade to the same + life at no cost against a replacement at that time (to 1e-10); + memoryless units either side of an upgrade, and a Weibull unit that + fails once at most, in closed form; the capital cost at its time; + retirement at the horizon (nothing changes) and before it (the shorter + valuation); a constant salvage, `value * exp(-r T)`; a salvage by age + of a memoryless unit against its age's closed form. +- **Learned / open questions:** + - Simulated too (`availability`, `cost`, `npv_distribution`, + `compare_npv`, in Python): a life that starts at or after the + upgrade's time is the upgrade's, turned from the same uniform of the + component's `FAILURE` stream as the old life would have been + (`_event_loop._UpgradedComponent`), so an upgrade to the same life is + a replacement at its time draw for draw, and `compare_npv` against + keeping the old pump matches the runs. The capital cost is charged + at its time in every run that reaches it. For the pump above, + `compare_npv(kept, 8000, mc_samples=10000, seed=1)` gives the + upgrade 864 ± 107 more (958.6 exact), better in 51% of the runs; its + own runs' NPV has p10 240,386 and p90 266,604. + - An upgraded component takes no maintenance or tests of its own yet, + and the long run, the spares counts and `plan_vs_actual` refuse it. + - A salvage by age is a plain component's from new; any other takes a + number. + - A retirement is the system's; a component's is not said yet. + +### UC-60: "The pump is block-replaced every 4,000 hours. In year 3 we fit a better model and keep replacing it on the same interval. What is that worth over eight years?" + +- **Status:** built: a component spec's `"upgrade"` with a + `"preventive"` of `"policy": "block"` on its own interval. +- **Who asks, and why:** the capital planner whose upgrade does not end + the maintenance plan: the new model is serviced as the old one was. +- **What they know:** a pump (Weibull 6,000 h and 2.0; repairs + exponential, 24 h mean, 5,000 each), replaced every 4,000 h in 12 h + for 2,500; 400 an hour down; an upgrade at 26,280 h (year 3) to a + Weibull of 12,000 h and 2.0, for 40,000; 8% a year over 8 years. +- **What they want back:** the plan's cost and value with and without + the upgrade, and how sure the difference is. +- **How it is solved:** the upgrade is one more replacement of the + block policy, at its time, at the policy's cost and in its time, beside + the capital cost; the units put into service from it have the new + life. Over a horizon its block times and the upgrade are a plan's + times (UC-51's stretches, the lives switching at the upgrade); the + simulation draws each life from the life in service when it starts + (UC-52). An upgrade at a block time is that block replacement. The + calendar counts from now (a `since_scheduled` is refused), and there + is no long run (refused, naming the values over a horizon). +- **Today (by hand, before it was built):** an upgrade refused any task + of its own; a plan of `replace_at` times with a second diagram for the + new life, joined by hand. A memoryless unit's chain between + replacements, its rate changing at the upgrade, is the test's + reference. As built: kept, 220,736.8 undiscounted and 163,830.7 + discounted, availability 0.99482; upgraded, 223,084.5 and 171,592.5, + 0.99571. `compare_npv(kept, mc_samples=4000, seed=1)` gives the + upgrade -7,251 ± 308 (-7,761.8 exact): it does not pay over 8 years. +- **Checks:** `test_upgrade_maintenance.py`: an upgrade to the same life + at a block time is block replacement (curve and events to 1e-10; its + NPV equals the same plan of block times to 1e-10, and block + replacement's to 2.5e-10, integrated on other pieces); between block + times, one more replacement (a plan at the merged times, to 1e-10); a + memoryless unit against its chain; the simulation from new and from + an age (20,000 runs, four standard errors); the refusals. The + catalogue's "upgraded at a time, block-replaced". +- **Learned / open questions:** age replacement and tests on an upgraded + part, its long run after the upgrade, its spares and `plan_vs_actual`, + and retiring a single part (`retire_at={node: t}`) are left for a + later use case. + +### UC-66: "Our pump's seals are a redundant pair, and the cartridge is replaced whole once both have failed. What is its plan worth?" + +**Who asks.** The planner of UC-65, whose unit is a subassembly: a +seal cartridge with two seals in parallel, each with its own fitted +life, replaced as one part when it fails. + +**What they know.** Each seal's life (exponential, 0.01 a day); the +cartridge's repair (exponential, mean 2 days) and prices. + +**What they want back.** The plan's values with the cartridge's life +being the diagram of its seals, worked out exactly where the diagram's +functions allow and simulated otherwise, as for any life. + +**How it is solved.** A `NonRepairableRBD` whose reliability changes +with time is taken by its functions, as any surpyval model with a +life's functions is (`_model_utils.by_functions`, `is_diagram_life`): +its `sf`, `ff`, `df`, `hf`, `Hf` and `mean` are the diagram's own, and +`qf` (new) inverts `ff` for a share up to a half and `sf` above, on +logarithms, by false position kept to a bracket, so a draw is seeded +from the streams as a model's is. So `UnitPlan(life=diagram)`, a spec's +`"reliability"` and `NonRepairable(diagram)` take it, saving takes it, +and every route treats it as a smooth life. + +**The hand-worked answer.** The pair's life is `(1 - exp(-0.01 t))^2` +failed, a mean of `1/0.01 + 1/0.02 = 150` days, so repaired in a mean +of 2 days the cartridge is up `150 / 152 = 0.98684` of the time, which +`UnitPlan(pair, repair).diagram().mean_availability()` gives. + +**Checks.** `test_diagram_life.py`: the parallel pair's `qf` against +its closed form, and a series pair of Weibulls of shape 2 against the +one Weibull it is, each to 1e-13 over shares from 1e-14 to 1 - 1e-9; a +unit whose life is the series pair against the unit of that one +Weibull, exact (long run, over time, NPV) and simulated (seeded +availability and NPV runs), to 1e-12; the parallel pair's availability +against `150 / 152`; a diagram taken by `NonRepairable` and a spec, +saved and loaded. A catalogue kind holds a diagram as a life. + +**What was learned.** Nothing but the quantile was missing: a diagram +already had a life's functions. A nested `RepairableRBD`'s costs +counted in its parent are left for later. + +### UC-64: "Once the pump is upgraded, what does it cost per year?" + +- **Status:** built: the long-run methods of a diagram with an + `"upgrade"` (`mean_availability`, `expected_cost_rate`, the importance + measures by default, `replacement_cycle`, ...) give the long run once + upgraded. +- **Who asks, what they know, what they want back:** the planner of + UC-60, who has the upgrade over a horizon and wants the steady state + after it: the availability and cost rate the plant settles to with + the new model, to set a budget per year. +- **How it is solved:** after its upgrade a component has the new life + for ever, so the long run is that of the diagram built with the new + life (its block replacement kept), the time before the upgrade and + its capital cost ignored. The long-run methods are asked of that + diagram, which the diagram builds once. Asked over time (`x`, + `window` or `state`), the measures follow the upgrade as before. + `total_cost(horizon)`, the long-run rate times a horizon from 0, + stays refused: the horizon starts before the upgrade. +- **Today (by hand, before it was built):** the long run was refused; + the second diagram, built by hand with the new life, gave it. +- **Checks:** `test_upgrade_long_run.py`: each long-run method equals + the diagram built with the new life (to 1e-12), with and without + block replacement; a memoryless unit's `mu / (lambda' + mu)`; the + routes say so; values over time still follow the upgrade. +- **Learned / open questions:** age replacement and tests on an + upgraded part, its spares counts and `plan_vs_actual` across the + upgrade, and retiring a single part are still open. + +### UC-68: "I want to be 95% sure I don't lose more than x on downtime this year. What is the least I need to pay to make that happen?" + +**Who asks.** An owner whose contracts, budgets and insurance are set on +a bad year, not the average one. Every optimiser so far takes expected +values; a bad year matters as much. + +**What they know.** The system's diagram (or one unit's plan), its +repairs and tasks; the levers they could pull, each at its own price: +copies of a unit in parallel (redundancy), and a unit's maintenance +interval; a limit `x` on the year's downtime, in hours or in cost; how +sure (95%). + +**What they want back.** The cheapest design whose bad year (95th +percentile) stays under `x`; the frontier of spend against the bad +year's downtime, so they see what each extra dollar buys; both the +planned and the unplanned downtime of every design (the mean and the bad +year's, in hours and cost), so the trade-off shows; and, when the levers +cannot reach `x`, which floor stopped them. + +**Decisions (the owner's, 21 Nov 2026).** +- The target is **downtime only**: the system's hours down, or their cost + (the diagram's `downtime_cost_rate` and any `value_rate` lost). Not + total cost: spending to cut downtime raises the maintenance part. +- Spend is the decision and has no bound unless `budget=` is given. +- By default all system downtime counts; `downtime="unplanned"` counts + failures only (the split of UC-25: down unplanned when it would still + be down with every planned task finished). +- The risk measure is the downtime's quantile at `level` (0.95), or the + mean of the worst share beyond it (`objective="cvar"`). The randomness + is that of failures and repairs, the models taken as known. +- "Sure" despite simulation noise: a design meets `x` only when an upper + confidence bound on its percentile is under it (an order statistic, + the binomial method, exact; the tail mean's bound is normal, and says + so). + +**How it is solved.** The risk measures sit in the money module +(`repyability.value._risk`), on priced outcomes. Each design is run by +`availability` on one seed (common random numbers), and each run's +downtime is `horizon - uptime`, its unplanned part the engines' own +(kept per run), the rest planned. The search is the allocations' +marginal analysis: from the diagram as given, each step takes the move +that lowers the bad year's downtime most per extra spend: a copy of a +node (drawn as `allocate_redundancy` draws a train of one node), or a +node's interval moved to a later candidate (any later one, as a +quantile can stay put over one step); its spend is the copies' prices +plus the change in the expected preventive cost. It stops at the first +design that meets `x`, or when no move lowers the downtime. The +frontier is the designs evaluated that no other beats on both spend and +downtime. Floors: the budget, the levers' caps, or planned task downtime +at or over the limit alone (shorter intervals add to it, and copies with +the same tasks do not remove it). A plan alone takes its one-node +diagram's method (`UnitPlan.least_spend_for_downtime`). + +**The hand-worked answer.** A pump with exponential lives (mean 1,000 h) +and repairs (mean 50 h), up at the start, over 8,760 h: its downtime is +an alternating renewal process's occupation time, whose distribution is +exact by uniformisation (given `n` jumps at rate `L = max(λ, μ)`, the +`n + 1` spacings are Dirichlet(1, ..., 1), so `k` spent down sum to +`T × Beta(k, n + 1 - k)`). Its 95th percentile is **766.35 h** (median +393.08 h; no downtime at all with chance `exp(-8.76) = 0.000157`). 4,000 +runs give 761.7 h (bound 783.3). A second pump at 5,000 brings the bad +year under 100 h (80.6 h, bound 90.2, from 1,000 runs); limits of 200, +50, 10 and 1 h are each met by copies, at a spend that rises as the +limit falls. + +The trade-off: a wearing unit (Weibull, scale 4,000 h, shape 3; repairs +of mean 72 h) with an 8 h task every 8,000 h. To be 95% sure of under 10 +h of *unplanned* downtime the interval must come down to 500 h (1,000 +runs): the bad year's unplanned downtime falls from 347 h to 0, and +planned downtime rises from none to 136 h. With all downtime counted, +10 h cannot be reached by intervals: the planned task downtime is the +floor, and the answer says so. + +**Checks.** `test_downtime_risk.py`: the single pump's percentile against +the exact distribution (within four of the quantile's standard errors, +seed fixed beforehand), and the distribution's ends; the quantile bound +against the binomial definition; level 0.5 on a symmetric loss is its +median; redundancy meets every limit at a rising spend; the frontier +never rises with spend; along the unplanned frontier planned downtime +rises; the planned floor and the budget floor named; seeded repeats and +cost as hours times the rate; a plan alone equal to its diagram; the +refusals. The bound's coverage at its stated rate is +`scripts/downtime_bound_coverage.py`, a study with fixed seeds, to run +at consolidation. + +**What was learned.** The engines already split each run's downtime into +planned and unplanned, and then summed it; keeping it per run was all +the risk needed. Spares, crews and call-out, upgrades and parameter +uncertainty are levers still to add (filed). + +### UC-61: "Our plan has two outages a year that cost 300 each, and at each we renew the pump if it is past 500 hours. The expected NPV is fine; how bad could a run be?" + +- **Status:** built: `npv_distribution`, `compare_npv` and + `best_switch_time` take a diagram with `shutdowns`. +- **Who asks, and why:** the planner of UC-46 whose plan has planned + outages (UC-23, UC-24) or renews parts at them (UC-56): the spread of + the NPV was refused, though `cost()` gave the undiscounted spread and + `expected_npv` the mean where it is exact. +- **What they know:** the diagram, its shutdowns (times or a period, a + duration, a scope, a cost, opportunistic renewals), the value rate, + the horizon and the rate. +- **What they want back:** UC-46's answer: each run's NPV, its + percentiles, the chance below a hurdle, the CVaR; two plans compared + run for run. +- **How it is solved (simulated):** the runs are priced as UC-46's, + with three things the histories alone got wrong. A shut's cost is + deterministic: charged at each of its starts in the window, in every + run, discounted exactly. A component a shut holds off line shows a + planned change down in its history, which is no task: the Python loop + (the only engine that holds anything; numba's runs shuts in no time + that cost nothing) marks each hold, and it is not charged. And the + changes a hold hides (a failure while idle in the shut, a renewal made + in it: a task at the shut that comes after the hold, an opportunistic + renewal) are recorded beside the histories, each with its time and + whether planned, and charged as a recorded change is. The public + timelines are unchanged: what the system and a component's downtime + saw is still the held view. +- **Today (by hand, before it was built):** refused, naming + `expected_npv` and `cost()`. Pricing the histories as they were, the + outage diagram of `test_shutdowns.py` (800 h, 300 runs) charged 393 a run of + preventive work for 128 done (each hold taken as a task) and missed + failures in the shuts; with the holds and hidden changes, each run's + undiscounted cost is `cost().samples`' to 1e-10. Building it showed + that a shut in no time with a cost was not charged by the simulation at + all (0 against `expected_cost`'s 45 over 10 shuts); it is now. +- **Checks:** `test_npv_shutdowns.py`: at no discounting, each run + against the simulation's own cost and uptime, and each category + against `cost()`, for outages at given times (one standing a part + still), opportunistic renewals in long shuts, a shut in no time and a + part with its own tasks held by shuts that do no work on it; that + those cases have holds and hidden changes to price; the mean against + `expected_npv` (4,000 runs, a 99.99% interval) and the shuts' cost + against its calendar sum to 1e-12; identical plans differ by exactly + 0; the shut in no time charged by `cost()`. +- **Learned / open questions:** the hidden changes could be the + component's own history (its process under the hold) recorded in + full; only the charged changes are needed, so only those are kept. + `plan_vs_actual` still refuses shutdowns: a log given by hand would + need its holds marked. + +### UC-53: "The trip is tested at 6 and 12 months and then at 2 years, not on one interval. Over the next 3 years, what will each test find, how long is the trip failed, and what does the plan cost against never testing it?" + +- **Status:** built: `failure_finding_window(device, test_times, window, + age=, test_cost=, repair_cost=, demand_rate=, consequence_cost=, + discount_rate=, demands_reveal=True)` returning a + `FailureFindingWindow`. +- **Who asks:** UC-18's engineer, whose tests are at times of their own + (dates laid on the device's clock, UC-54 of the schedule README), from + a device that is not new, over a budget's window, and who wants the + side "never tested" to set against it. +- **What they know:** a trip failing hidden at a constant 0.1 a year, + working now; tests at 0.5, 1 and 2 years, $200 each; a failure repaired + as new for $1,500; a demand once in 2 years (0.5 a year), which costs + $50,000 if it meets the trip failed, and which shows the failure, so + the trip is repaired then. +- **Today:** `failure_finding(device, tau, ...)` gives the long run of + one even interval from new, undiscounted, with a failure found only by + a test: no list of times, no window, no age, no "never tested" (its + unavailability is 1 in the long run), no discount. +- **The answer, by hand:** between two tests the trip is a two-state + chain: working, it fails at 0.1; failed, a demand shows it at 0.5. From + a test (or the start) the chance it is failed after `s` years is `0.1 / + 0.6 (1 - exp(-0.6 s))`. So the tests find it failed with chance + **0.0432** (after 0.5 years), **0.0432** and **0.0752** (after 1 year): + 0.1616 failures found. The time failed is `0.1 / 0.6 (s - (1 - exp(-0.6 + s)) / 0.6)` over each stretch (0.5, 0.5, 1 and 1 years): 0.01133 + + 0.01133 + 0.04134 + 0.04134 = **0.10535 years** (a mean unavailability + of 0.0351), so 0.0527 demands meet it failed. Cost: 3 tests $600; + repairs $1,500 x (0.1616 + 0.0527) = $321.40; consequences $50,000 x + 0.0527 = $2,633.75: **$3,555.15**. *Never tested:* one stretch of 3 + years: failed for 0.26814 years (0.0894), 0.1341 demands on a failed + trip, $201.10 of repairs and $6,703.46 of consequences: **$6,904.57**. + The three tests save $3,349. +- **How it is solved:** the device is working at an age since it was + last made new, or failed unseen. A test of a working device leaves its + age; one that finds it failed makes it new, in no time. `A(t)`, the + chance it is working, is the sum over the times it was made new of the + chance of that and of surviving since: `A(t) = R(age + t) / R(age) + + sum_k q_k R(t - t_k) + d integral_0^t U(s) R(t - s) ds`, `U = 1 - A`, + with `q_k = U(t_k)` just before test `k` (what it finds) and the last + term the devices a demand showed failed. Where only a test finds a + failure the last term is not there and `A` is exact at any time (a + table of the tests so far). With it, this is a Volterra equation of + the second kind, solved by the trapezoid rule on a grid of each stretch + between tests. The failed time (and its discounted integral) is the + trapezoid rule's on the same grid either way; the whole is worked out + on one grid and on one twice as fine, each number taken from the two + by Richardson's step, and the grid halved until the two agree to + `tolerance` (1e-6 of the failed time and of the failures found, by + default). Their difference, in money, is `precision`. A test and the + repair of what it finds are discounted from the test's time; the + demands' cost inside the integral. +- **Decisions (defaults):** + - **A demand that meets the device failed shows the failure**, which is + repaired as new then, at `repair_cost` (`demands_reveal=True`). This + is what makes "never tested" a finite number. `demands_reveal=False` + is `failure_finding`'s convention: only a test finds a failure, and + every demand until then costs the consequence. + - Tests and repairs take no time, and a test never misses a failure, + as `failure_finding` has it. + - The device is working at the window's start (a test at time 0 only + costs). `test_times=()` is "never tested". + - Demands are a Poisson process at `demand_rate`, independent of the + device. + - `discount_rate` is per unit of the device's time, continuously + compounded, as `expected_npv`'s; dates and a yearly rate are the + schedule module's (UC-54). + - At most 2,000 tests in a window (the work grows with their square), + refused naming `failure_finding` for the long run. +- **Checks** (`test_failure_finding_window.py`): + `test_uc53_trip_tested_at_uneven_times` (the numbers above), + `test_exponential_closed_form` (the two-state chain's closed form, + with and without demands revealing, with and without a discount, and + the curve), `test_even_tests_reproduce_the_long_run` (even tests, no + discount, only tests finding: `failure_finding`'s unavailability, cost + rate and failures found, for a constant rate on any whole number of + intervals and for a Weibull life over 400 mean lives), + `test_weibull_against_a_simulation` (a wearing device 4 old, tested at + uneven times and never, with and without demands revealing, within + four standard errors of a seeded simulation of the plan), + `test_never_tested_without_reveal_is_the_life_itself`, + `test_a_test_at_the_start_finds_nothing`, + `test_the_unit_of_time_does_not_matter`, `test_refusals`. +- **Learned / left:** the precision given is the two grids' difference, + which is several times the error of the extrapolated numbers (1e-15 + against 4e-7 of the cost for the trip above); a life with an infinite + density at 0 (a Weibull shape under 1) converges more slowly and takes + the finest grid. A test that can miss a failure, and tests and repairs + that take time (which `RepairableRBD`'s inspected blocks have, on a + period), are not here. The best times for the tests are not searched + for. + + ### UC-25: "How much of our downtime and lost production is planned and how much is from failures, and how many failures does the plan avoid each year against running to failure?" - **Status:** built: `RepairableRBD.maintenance_effect(t=None, diff --git a/repyability/maintenance/__init__.py b/repyability/maintenance/__init__.py index b56a939c..aa27bc36 100644 --- a/repyability/maintenance/__init__.py +++ b/repyability/maintenance/__init__.py @@ -6,7 +6,9 @@ ``README.md`` in this package records the use cases, the question each answers and how it is solved.""" +import math from dataclasses import dataclass +from typing import Any, Mapping, Optional, Union from repyability.rbd.results import _ResultMapping @@ -32,9 +34,20 @@ class MaintenancePolicy(_ResultMapping): the overhaul interval for a repairable component. ``inf`` when preventive action never pays (run to failure / never overhaul). cost_rate : float - The long-run expected cost per unit time under the policy. When - ``interval`` is ``inf`` this is the limiting cost rate of running - without preventive action. + The long-run expected cost per unit time under the policy, + undiscounted (also when the policy was chosen with a discount + rate). When ``interval`` is ``inf`` this is the limiting cost rate + of running without preventive action. + discount_rate : float + The continuous discount rate per unit of time the policy was + chosen at, 0 for none. + npv : float + The present value of every replacement from a new unit, forever, + under the policy (Fox, 1966); ``inf`` with no discounting. + eac : float + The equivalent annual cost: the steady cost per unit time worth + the same as ``npv``, ``discount_rate * npv``. With no discounting + it is ``cost_rate``. Examples -------- @@ -49,6 +62,13 @@ class MaintenancePolicy(_ResultMapping): interval: float cost_rate: float + discount_rate: float = 0.0 + npv: float = math.inf + eac: Optional[float] = None + + def __post_init__(self): + if self.eac is None: + object.__setattr__(self, "eac", self.cost_rate) @dataclass(frozen=True) @@ -77,7 +97,7 @@ class FailureLimitPolicy(_ResultMapping): >>> import surpyval as surv >>> from surpyval.recurrent import GeneralizedRenewal >>> from repyability import Repairable - >>> grp = GeneralizedRenewal.fit_from_parameters( + >>> grp = GeneralizedRenewal.from_params( ... [100.0, 2.0], 0.4, kijima="i", dist=surv.Weibull ... ) >>> unit = Repairable(grp) @@ -99,23 +119,44 @@ class OverhaulReplacePolicy(_ResultMapping): Returned by the ``optimal_overhaul_replace_policy()`` method of [`Repairable`][repyability.Repairable]: failures are repaired minimally, - the unit is overhauled every ``interval`` (an overhaul takes off part of - its age) and replaced by a new unit after ``cycles`` such periods. It is - an immutable (frozen) dataclass, read as a mapping too, with - ``to_dict()`` for JSON. + and the cheapest of four plans is kept: overhaul every ``interval`` + (an overhaul takes off part of the unit's age) and replace by a new + unit after ``cycles`` such periods; overhaul only, never replacing; + replace only, with no overhauls; or replace at the + ``failure_count``-th failure. It is an immutable (frozen) dataclass, + read as a mapping too, with ``to_dict()`` for JSON. Attributes ---------- interval : float - The time between overhauls, in the time units of the component's - model. ``inf`` when overhauling never pays. - cycles : int + The time between overhauls (between replacements for ``"replace + only"``), in the time units of the component's model. ``inf`` when + there is no planned overhaul or replacement (``"failure limit"`` + and ``"run to failure"``). + cycles : int or float The number of periods of ``interval`` between replacements: the unit is overhauled ``cycles - 1`` times, and replaced at the end of the ``cycles``-th period. ``1`` means no overhaul: replace every - ``interval``. + ``interval``. ``inf`` for ``"overhaul only"``: never replace. cost_rate : float The long-run expected cost per unit time under the policy. + plan : str + The plan that won: ``"overhaul and replace"``, ``"overhaul + only"``, ``"replace only"``, ``"failure limit"``, or ``"run to + failure"`` when the unit does not wear out, so that nothing pays. + failure_count : int or None + For ``"failure limit"``, the failure at which the unit is replaced + (the earlier ones are repaired); otherwise None. + alternatives : dict + Each plan compared, by name, with its cost rate and its best + ``interval``, ``cycles`` or ``failure_count``. + saving : float + How much less the winner costs per unit time than the next best + plan; 0 when nothing else was compared. + cycles_limit_reached : bool + True when the best ``"overhaul and replace"`` plan used the most + periods searched (``max_cycles``): more might pay, and they tend + towards ``"overhaul only"``. Examples -------- @@ -126,20 +167,25 @@ class OverhaulReplacePolicy(_ResultMapping): >>> policy = unit.optimal_overhaul_replace_policy( ... overhaul_factor=0.6, replacement_cost=20.0, max_cycles=5 ... ) - >>> policy.cycles, round(policy.interval, 1), round(policy.cost_rate, 4) - (2, 177.7, 0.1172) + >>> policy.plan, policy.cycles, round(policy.interval, 1) + ('overhaul only', inf, 73.8) + >>> sorted(policy.alternatives) # doctest: +NORMALIZE_WHITESPACE + ['failure limit', 'overhaul and replace', 'overhaul only', + 'replace only'] """ interval: float - cycles: int + cycles: Union[int, float] cost_rate: float + plan: str = "overhaul and replace" + failure_count: Optional[int] = None + alternatives: Optional[Mapping[str, Mapping[str, Any]]] = None + saving: float = 0.0 + cycles_limit_reached: bool = False # After the policies, which the modules it imports may import from here. -from repyability.maintenance._calendar import ( # noqa: E402 - Calendar, - Opportunity, -) +from repyability.maintenance._calendar import Opportunity # noqa: E402 from repyability.maintenance._decisions import ( # noqa: E402 FailureFinding, OnCondition, @@ -152,6 +198,10 @@ class OverhaulReplacePolicy(_ResultMapping): run_to_failure, scheduled_replacement, ) +from repyability.maintenance._finding_window import ( # noqa: E402 + FailureFindingWindow, + failure_finding_window, +) from repyability.maintenance._next import ( # noqa: E402 NextReplacement, ReplacementChoice, @@ -162,6 +212,14 @@ class OverhaulReplacePolicy(_ResultMapping): best_switch_time, operating_schedule_value, ) +from repyability.maintenance._opportunities import ( # noqa: E402 + Calendar, + Opportunities, + OpportunityPrice, + OpportunityPrices, + Shutdown, + Shutdowns, +) from repyability.maintenance._options import ( # noqa: E402 AgeReplacementValue, DelayEffect, @@ -170,6 +228,19 @@ class OverhaulReplacePolicy(_ResultMapping): ReplacementComparison, SlackEffect, ) +from repyability.maintenance._plan import ( # noqa: E402 + AgePolicy, + AtShutdown, + BlockPolicy, + CalendarReplacement, + ConditionPolicy, + ImperfectRepair, + Inspection, + Prices, + Restoration, + UnitPlan, + Upgrade, +) from repyability.maintenance._repair_or_replace import ( # noqa: E402 RepairOrReplace, RepairOrReplacePolicy, @@ -180,9 +251,7 @@ class OverhaulReplacePolicy(_ResultMapping): PlannedReplacement, ) from repyability.maintenance._shutdowns import ( # noqa: E402 - Shutdown, ShutdownRoute, - Shutdowns, SlowSolverWarning, ) from repyability.maintenance._site_policy import ( # noqa: E402 diff --git a/repyability/maintenance/_calendar.py b/repyability/maintenance/_calendar.py index 123d7c87..228e18f3 100644 --- a/repyability/maintenance/_calendar.py +++ b/repyability/maintenance/_calendar.py @@ -12,9 +12,10 @@ import math import warnings -from dataclasses import dataclass +from dataclasses import dataclass, fields +from datetime import date from fractions import Fraction -from typing import Optional, Tuple +from typing import Any, Optional, Tuple import numpy as np @@ -61,64 +62,312 @@ def _price(value, name: str) -> float: return float(value) -@dataclass(frozen=True) +#: The names that are no opportunity's: a planned replacement on any day, +#: and a failure (on real dates, the words results use for them). +_NOT_NAMES = (ANYTIME,) +_NOT_NAMES_ON_DATES = (ANYTIME, "failure", "any other day", "any day") + + +def _price_deprecated(where: str) -> None: + """Warn that a price was put on an opportunity (``where`` says how).""" + from repyability.utils.deprecation import price_on_part + + price_on_part(where) + + +@dataclass(frozen=True, init=False, repr=False) class Opportunity: - """A kind of scheduled opportunity to replace a part: a shut (weekly, - quarterly, annual, ...) at which replacing it costs ``cost``. + """A kind of opportunity to replace a part: a stop or shut (weekly, + quarterly, annual, a turnaround, a service) that says when it happens, + how long it lasts and what it takes down. It carries no price: an + opportunity applies to every part, and each part brings its own + (`NonRepairable`'s ``opportunity_cost`` and ``opportunity_costs``). + Opportunities are collected in + [`Opportunities`][repyability.Opportunities]. - Its times are either every ``period`` from ``offset`` (on and on, both - ways: ``offset + k * period`` for every whole ``k``), or the given - ``dates``. Times are in the life model's unit, from 0. + It is either in **model time** (numbers in the life's unit, from 0): + + - every ``period`` from ``offset`` (on and on, both ways: + ``offset + k * period`` for every whole ``k``), or + - ``dates`` given as numbers; + + or on **real dates**: + + - a ``rule`` (a [`Recurrence`][repyability.schedule.Recurrence]: + every Saturday, the first Tuesday of November), + - ``dates`` given as dates (with ``then_every`` they recur at that gap + after the last), or + - ``every``, a plain period (``"30 days"``; a number is that many of + the part's own units) or a use (``Usage(15_000, "km")``), with + ``also_every`` a calendar limit, whichever comes first. Parameters ---------- name : str - The opportunity's name, as the policy's schedule lists it (not - ``"anytime"``, which names a replacement on any day). - cost : float - What replacing the part at it costs, at least 0. + Its name, as results list it (not ``"anytime"``, which names a + replacement on any day; on real dates not ``"failure"``, + ``"any day"`` or ``"any other day"`` either). + rule : Recurrence, optional + When it happens, on real dates. + dates : list of float, or of date or str, optional + Its times: numbers in model time, or dates (``"2027-03-03"``). period : float, optional - The time from one to the next, more than 0. + In model time: the time from one to the next, more than 0. offset : float, optional - The time of one of them, by default 0. Only with ``period``. - dates : array_like, optional - Its times, instead of ``period``: finite numbers, put in order. + In model time: the time of one of them, by default 0. Only with + ``period``. + then_every : str, optional + On real dates, with ``dates``: the gap at which it recurs after + its last date (``"4 years"``, ``"18 months"``; whole numbers). + every : str, float or Usage, optional + On real dates: a plain period or a use, instead of a rule or + dates. + also_every : str, optional + With ``every=Usage(...)``: a plain period, whichever comes first. + duration : float or str, optional + How long it lasts. In model time a number in the life's unit; on + real dates text (``"8h"``, ``"3d"``) or a number of hours. A part + whose ``job_duration`` is longer does not use it; a diagram takes + it as the outage. None (the default): not said, and every part + may use it. + at : str, optional + On real dates: the clock time it starts (``"21:00"``), by default + midnight. Not with a use. + 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. 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 + opportunity, applied to the part being solved as its override + for this opportunity. Give the part ``opportunity_cost`` or + ``opportunity_costs`` instead. Examples -------- >>> from repyability import Opportunity - >>> weekly = Opportunity("weekly", 3.0, period=7.0) - >>> annual = Opportunity("annual", 1.0, period=364.0, offset=182.0) - >>> turnarounds = Opportunity("turnaround", 0.5, dates=[400.0, 1130.0]) + >>> from repyability.schedule import Recurrence + >>> weekly = Opportunity("weekly", period=7.0) + >>> annual = Opportunity("annual", period=364.0, offset=182.0) + >>> turnarounds = Opportunity("turnaround", dates=[400.0, 1130.0]) >>> weekly.times(0.0, 30.0).tolist() [0.0, 7.0, 14.0, 21.0, 28.0] + >>> stop = Opportunity("weekly stop", Recurrence.weekly("Sat"), + ... duration="8h") + >>> stop.model_time, stop.describe() + (False, 'weekly stop (every Saturday, 8 h)') + >>> Opportunity("turnaround", dates=["2027-03-03", "2028-09-09"], + ... duration="21d", takes_down=["Line 2"]).describe() + 'turnaround (3 Mar 2027, 9 Sep 2028, 504 h, takes down Line 2)' """ name: str - cost: float + cost: Optional[float] = None period: Optional[float] = None offset: float = 0.0 - dates: Optional[Tuple[float, ...]] = None + dates: Optional[Tuple[Any, ...]] = None + rule: Any = None + then_every: Optional[str] = None + every: Any = None + also_every: Optional[str] = None + duration: Optional[float] = None + at: Any = None + takes_down: Optional[Tuple[str, ...]] = None + idle_ageing: bool = True + opportunistic: Any = None + + def __init__( + self, + name, + rule=None, + *legacy, + dates=None, + period=None, + offset=None, + then_every=None, + every=None, + also_every=None, + duration=None, + 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). + if cost is not None: + raise TypeError( + "Opportunity() got the price twice: as its second " + "argument and as cost=." + ) + if len(legacy) > 3: + raise TypeError( + "Opportunity(name, cost, period, offset, dates) takes " + f"at most 5 arguments; got {2 + len(legacy)}." + ) + cost, rule = rule, None + given = dict(zip(("period", "offset", "dates"), legacy)) + for key, value in given.items(): + if {"period": period, "offset": offset, "dates": dates}[ + key + ] is not None: + raise TypeError(f"Opportunity() got {key} twice.") + period = given.get("period", period) + offset = given.get("offset", offset) + dates = given.get("dates", dates) + _price_deprecated("Opportunity(name, cost, ...)") + elif legacy: + raise TypeError( + "Opportunity() takes the name and a rule as its only " + "positional arguments; give the rest by name (dates=, " + "period=, duration=, ...)." + ) + elif cost is not None: + _price_deprecated("Opportunity(..., cost=)") + for key, value in ( + ("name", name), + ("cost", cost), + ("period", period), + ("offset", offset), + ("dates", dates), + ("rule", rule), + ("then_every", then_every), + ("every", every), + ("also_every", also_every), + ("duration", duration), + ("at", at), + ("takes_down", takes_down), + ("idle_ageing", idle_ageing), + ("opportunistic", opportunistic), + ): + object.__setattr__(self, key, value) + self._check() - def __post_init__(self): + def __repr__(self) -> str: + shown = [repr(self.name)] + for f in fields(self): + value = getattr(self, f.name) + if f.name == "name" or value is None: + 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)})" + + def _check(self) -> None: if not isinstance(self.name, str) or not self.name: raise TypeError( f"An opportunity's name must be text; got {self.name!r}." ) if self.name == ANYTIME: raise ValueError( - f"{ANYTIME!r} names a planned replacement on any day (the " - "calendar's anytime price): give the opportunity another " - "name." + f"{ANYTIME!r} names a planned replacement on any day: give " + "the opportunity another name." ) - object.__setattr__( - self, "cost", _price(self.cost, f"The cost of {self.name!r}") + if self.cost is not None: + object.__setattr__( + self, "cost", _price(self.cost, f"The cost of {self.name!r}") + ) + on_dates = ( + self.rule is not None + or self.every is not None + or (self.dates is not None and not _numbers(self.dates)) + ) + in_model = self.period is not None or ( + self.dates is not None and _numbers(self.dates) ) - if (self.period is None) == (self.dates is None): + if on_dates and self.period is not None: raise ValueError( - f"Opportunity {self.name!r}: give a period (with an " - "offset) or dates, one of the two." + f"Opportunity {self.name!r}: period= is for model time, and " + "a rule, dates or every= for real dates: give one of the " + "two." ) + if not (on_dates or in_model): + raise ValueError( + f"Opportunity {self.name!r}: say when it happens, one of: a " + "period (with an offset) or dates as numbers, in model " + "time; or a rule (a Recurrence), dates or every=, on real " + "dates." + ) + if in_model: + self._check_model_time() + else: + self._check_dates() + takes_down = self.takes_down + if takes_down is not None: + if isinstance(takes_down, str): + takes_down = (takes_down,) + takes_down = tuple(takes_down) + if not takes_down or not all( + isinstance(t, str) and t for t in takes_down + ): + raise ValueError( + f"Opportunity {self.name!r}: takes_down must be a list " + "of labels (text), at least one, or None for the whole " + 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"): + if getattr(self, key) is not None: + raise ValueError( + f"Opportunity {self.name!r}: {key}= is for real dates; " + "this one is in model time." + ) if self.period is not None: if not ( checks.is_number(self.period) @@ -128,22 +377,26 @@ def __post_init__(self): f"Opportunity {self.name!r}: the period must be a " f"number, more than 0; got {self.period!r}." ) - if not ( - checks.is_number(self.offset) - and math.isfinite(float(self.offset)) - ): + if self.dates is not None: + raise ValueError( + f"Opportunity {self.name!r}: give a period (with an " + "offset) or dates, one of the two." + ) + offset = 0.0 if self.offset is None else self.offset + if not (checks.is_number(offset) and math.isfinite(offset)): raise ValueError( f"Opportunity {self.name!r}: the offset must be a " f"finite number; got {self.offset!r}." ) object.__setattr__(self, "period", float(self.period)) - object.__setattr__(self, "offset", float(self.offset)) + object.__setattr__(self, "offset", float(offset)) else: - if self.offset != 0.0: + if self.offset not in (None, 0.0): raise ValueError( f"Opportunity {self.name!r}: an offset applies only to " "a period; dates give the times themselves." ) + object.__setattr__(self, "offset", 0.0) dates = checks.real_array(self.dates, "dates") if dates.ndim != 1 or dates.size == 0: raise ValueError( @@ -158,20 +411,166 @@ def __post_init__(self): object.__setattr__( self, "dates", tuple(float(d) for d in np.unique(dates)) ) + if self.duration is not None: + if not ( + checks.is_number(self.duration) + and 0.0 < float(self.duration) < math.inf + ): + raise ValueError( + f"Opportunity {self.name!r}: in model time a duration " + "is a number in the life's unit, more than 0; got " + f"{self.duration!r}." + ) + object.__setattr__(self, "duration", float(self.duration)) + + def _check_dates(self) -> None: + from repyability.maintenance._shutdowns import _duration, check_when + + if self.name in _NOT_NAMES_ON_DATES: + raise ValueError( + f"{self.name!r} names what is not an opportunity (a planned " + "replacement on any other day, or a failure): give the " + "opportunity another name." + ) + if self.offset not in (None, 0.0): + raise ValueError( + f"Opportunity {self.name!r}: an offset is for a period in " + "model time." + ) + object.__setattr__(self, "offset", 0.0) + dates, every, at = check_when( + f"Opportunity {self.name!r}", + self.name, + rule=self.rule, + dates=self.dates, + then_every=self.then_every, + every=self.every, + also_every=self.also_every, + at=self.at, + ) + object.__setattr__(self, "dates", dates) + object.__setattr__(self, "every", every) + object.__setattr__(self, "at", at) + object.__setattr__(self, "duration", _duration(self.duration)) + + # -- made inside the package --------------------------------------- + + def _replaced(self, **changes) -> "Opportunity": + """A copy with ``changes`` (fields already checked), made without + the deprecation the public form of a price warns of.""" + new = object.__new__(Opportunity) + for f in fields(Opportunity): + object.__setattr__( + new, f.name, changes.get(f.name, getattr(self, f.name)) + ) + return new + + @classmethod + def _at_price( + cls, name, cost, *, period=None, offset=0.0, dates=None + ) -> "Opportunity": + """An opportunity in model time with a price, as the solvers take + it (no deprecation: the price is the part's, worked out here).""" + return cls(name, period=period, offset=offset, dates=dates)._replaced( + cost=_price(cost, f"The cost of {name!r}") + ) + + @classmethod + def _from_shutdown(cls, shut) -> "Opportunity": + """A shut of the 0.19 form (``Shutdown``) as an opportunity on real + dates, its ``replace_cost`` kept as the (deprecated) price.""" + return cls( + shut.name, + shut.rule, + dates=shut.dates, + then_every=shut.then_every, + every=shut.every, + also_every=shut.also_every, + duration=shut.duration, + at=shut.at, + )._replaced(cost=float(shut.replace_cost)) + + def _shutdown(self, price: float): + """This opportunity (on real dates) as the site solvers take it: a + shut at ``price``.""" + from repyability.maintenance._shutdowns import Shutdown + + return Shutdown( + self.name, + self.rule, + dates=self.dates, + then_every=self.then_every, + every=self.every, + also_every=self.also_every, + replace_cost=price, + duration=self.duration, + at=self.at, + ) + + # -- what it is ---------------------------------------------------- + + @property + def model_time(self) -> bool: + """Whether it is in model time (a period, or dates as numbers); + False on real dates.""" + return self.period is not None or ( + self.dates is not None and isinstance(self.dates[0], float) + ) + + @property + def periodic(self) -> bool: + """Whether its times are on a period in model time (not given + dates).""" + return self.period is not None + + @property + def by_use(self) -> bool: + """Whether it recurs by use (``every=Usage(...)``).""" + from repyability.schedule import Usage + + return isinstance(self.every, Usage) + + def when(self) -> str: + """When it happens, in words.""" + if self.model_time: + if self.period is not None: + text = f"every {self.period:g}" + return text + (f" from {self.offset:g}" if self.offset else "") + return "at " + ", ".join(f"{d:g}" for d in self.dates or ()) + return self._shutdown(0.0).when() + + def describe(self) -> str: + """It in a few words: ``"weekly stop (every Saturday, 8 h)"``.""" + from repyability.maintenance._shutdowns import _money, _number + + words = [self.when()] + if self.duration is not None: + words.append( + f"{self.duration:g} long" + if self.model_time + else f"{_number(self.duration)} h" + ) + if self.takes_down is not None: + words.append("takes down " + ", ".join(self.takes_down)) + if self.cost is not None: + words.append(_money(self.cost)) + return f"{self.name} ({', '.join(words)})" @classmethod def from_recurrence( cls, name: str, - cost: float, rule, start, - end, - *, + end=None, + *legacy, unit: str = "hours", usage=None, at=None, time_zone: Optional[str] = None, + duration=None, + takes_down=None, + cost=None, ) -> "Opportunity": """An opportunity at a rule's dates, laid on the part's model time. @@ -182,14 +581,13 @@ def from_recurrence( operating time since the forecast's start, for a life in operating hours; without, the real time since ``start``'s midnight, for a life in calendar time. Dates at one operating time (shuts while - the plant is idle) become one time. + the plant is idle) become one time. (To keep the rule on real + dates, give it to ``Opportunity`` itself.) Parameters ---------- name : str The opportunity's name. - cost : float - What replacing the part at it costs. rule : Recurrence When the shuts are ([`repyability.schedule.Recurrence`][repyability.schedule.Recurrence]). @@ -206,6 +604,14 @@ def from_recurrence( The clock time each shut starts, by default midnight. time_zone : str, optional The site's IANA zone with no ``usage`` (with one, its zone). + duration : float, optional + How long each lasts, in the life's unit. + takes_down : list of str, optional + What it takes down, as for ``Opportunity``. + cost : float, optional + **Deprecated** (also as the second argument, the 0.14 form + ``from_recurrence(name, cost, rule, start, end)``): a price on + the opportunity; give the part ``opportunity_cost`` instead. Returns ------- @@ -219,7 +625,7 @@ def from_recurrence( >>> from repyability import Opportunity >>> from repyability.schedule import Recurrence >>> overhaul = Opportunity.from_recurrence( - ... "overhaul", 1.0, + ... "overhaul", ... Recurrence.yearly(month=11, weekday="Tuesday", nth=1), ... "2026-11-14", "2029-12-31", unit="days", ... ) @@ -228,6 +634,26 @@ def from_recurrence( """ from repyability.schedule._forecast import opportunity_times + if checks.is_number(rule): + # The 0.14 form, from_recurrence(name, cost, rule, start, end). + if cost is not None or len(legacy) != 1: + raise TypeError( + "Opportunity.from_recurrence(name, cost, rule, start, " + "end) takes the price once and all five arguments." + ) + cost, rule, start, end = rule, start, end, legacy[0] + _price_deprecated("Opportunity.from_recurrence(name, cost, ...)") + elif legacy: + raise TypeError( + "Opportunity.from_recurrence takes name, rule, start and " + "end; give the rest by name." + ) + elif cost is not None: + _price_deprecated("Opportunity.from_recurrence(..., cost=)") + if end is None: + raise TypeError( + "Opportunity.from_recurrence needs the last date: end=." + ) times = opportunity_times( rule, start, @@ -242,15 +668,20 @@ def from_recurrence( f"Opportunity {name!r}: the rule ({rule.describe()}) gives " f"no dates from {start} to {end}." ) - return cls(name, cost, dates=tuple(float(t) for t in times)) - - @property - def periodic(self) -> bool: - """Whether its times are on a period (not given dates).""" - return self.period is not None + made = cls( + name, + dates=tuple(float(t) for t in times), + duration=duration, + takes_down=takes_down, + ) + return ( + made + if cost is None + else made._replaced(cost=_price(cost, f"The cost of {name!r}")) + ) def times(self, start: float, end: float) -> np.ndarray: - """Its times from ``start`` up to ``end``. + """Its times from ``start`` up to ``end``, in model time. Parameters ---------- @@ -264,6 +695,12 @@ def times(self, start: float, end: float) -> np.ndarray: numpy.ndarray Its times, in order. """ + if not self.model_time: + raise ValueError( + f"Opportunity {self.name!r} is on real dates: its times in " + "model time come from a part's clock (a policy lays them " + "there); give dates in model time, or a period." + ) if self.period is None: dates = np.asarray(self.dates, float) return dates[(dates >= start) & (dates < end)] @@ -272,15 +709,138 @@ def times(self, start: float, end: float) -> np.ndarray: times = self.offset + np.arange(first, last) * self.period return times[(times >= start) & (times < end)] + # -- saving -------------------------------------------------------- + + def to_dict(self) -> dict: + """The opportunity as plain data, ready for ``json.dumps`` + (``"kind"`` ``"opportunity"``).""" + from repyability.schedule import Usage + + out: dict = {"kind": "opportunity", "name": self.name} + if self.model_time: + out.update( + time="model", + period=self.period, + offset=self.offset, + dates=None if self.dates is None else list(self.dates), + duration=self.duration, + ) + else: + every: Any = self.every + if isinstance(every, Usage): + every = every.to_dict() + out.update( + time="dates", + rule=None if self.rule is None else self.rule.to_dict(), + dates=( + None + if self.dates is None + else [d.isoformat() for d in self.dates] + ), + then_every=self.then_every, + every=every, + also_every=self.also_every, + duration_hours=self.duration, + at=None if self.at is None else self.at.strftime("%H:%M"), + ) + out["takes_down"] = ( + None if self.takes_down is None else list(self.takes_down) + ) + 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 + def from_dict(cls, data: dict) -> "Opportunity": + """An opportunity from its ``to_dict()``. + + Parameters + ---------- + data : dict + What ``to_dict()`` gave. + + Returns + ------- + Opportunity + """ + from repyability.schedule import Recurrence, Usage + + if not isinstance(data, dict) or data.get("kind") != "opportunity": + raise ValueError( + "Not a saved Opportunity: its kind must be 'opportunity'; " + f"got {data!r:.80}." + ) + if data.get("time") == "model": + made = cls( + data["name"], + period=data.get("period"), + offset=data.get("offset") if data.get("period") else None, + dates=data.get("dates"), + duration=data.get("duration"), + takes_down=data.get("takes_down"), + ) + else: + every = data.get("every") + if isinstance(every, dict): + every = Usage.from_dict(every) + rule = data.get("rule") + made = cls( + data["name"], + None if rule is None else Recurrence.from_dict(rule), + dates=data.get("dates"), + then_every=data.get("then_every"), + every=every, + also_every=data.get("also_every"), + duration=data.get("duration_hours"), + at=data.get("at"), + takes_down=data.get("takes_down"), + ) + 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 + + +def _numbers(values) -> bool: + """Whether ``values`` (dates, as given) are numbers (model time), not + dates.""" + if isinstance(values, (str, date)): + return False + try: + listed = list(values) + except TypeError: + return checks.is_number(values) + return all(checks.is_number(v) for v in listed) + class Calendar: - """The prices of replacing a part over time: its scheduled - opportunities, a planned replacement on any day, and a failure. + """The prices of replacing a part over time, as the model-time solvers + take them: its opportunities, each with the part's price, a planned + replacement on any day, and a failure. A policy lays a part's prices + on [`Opportunities`][repyability.Opportunities] as one of these; + ``repyability.Calendar``, which a caller builds with the prices on the + opportunities, is deprecated. Parameters ---------- opportunities : list of Opportunity - The scheduled opportunities, each with its own name. + The opportunities in model time, each with its own name and price. failure : float or "part", optional What a replacement at a failure costs. By default ``"part"``: the part's ``unplanned_cost``. @@ -292,11 +852,11 @@ class Calendar: Examples -------- - >>> from repyability import Calendar, Opportunity + >>> from repyability.maintenance._calendar import Calendar, Opportunity >>> calendar = Calendar( ... [ - ... Opportunity("weekly", 3.0, period=7.0), - ... Opportunity("annual", 1.0, period=364.0), + ... Opportunity._at_price("weekly", 3.0, period=7.0), + ... Opportunity._at_price("annual", 1.0, period=364.0), ... ], ... failure=40.0, ... anytime=4.0, @@ -317,6 +877,19 @@ def __init__(self, opportunities=(), failure=PART, anytime=PART): "A calendar's opportunities must each be an " f"Opportunity; got {opportunity!r}." ) + if not opportunity.model_time: + raise ValueError( + f"Opportunity {opportunity.name!r} is on real dates, " + "and a Calendar is in model time: give the " + "opportunities to Opportunities." + ) + if opportunity.cost is None: + raise ValueError( + f"Opportunity {opportunity.name!r} has no price, and a " + "Calendar (deprecated) takes each opportunity's own: " + "give the opportunities to Opportunities, which takes " + "the prices from the part (its opportunity_cost)." + ) names = [o.name for o in opportunities] repeated = sorted({n for n in names if names.count(n) > 1}) if repeated: diff --git a/repyability/maintenance/_cycles.py b/repyability/maintenance/_cycles.py index f5758da7..16fdbae2 100644 --- a/repyability/maintenance/_cycles.py +++ b/repyability/maintenance/_cycles.py @@ -139,9 +139,29 @@ def _best_interval( ) -> Tuple[float, float]: """The interval minimising ``g(., K)`` and its cost rate: ``inf`` and the rate at the far end of the grid where lengthening it keeps paying.""" + return _minimise(unit, lambda t: _rate(unit, t, cycles, factor, cp), scale) + + +def _never_replace_rate(unit, t: np.ndarray, factor: float) -> np.ndarray: + """``g_inf(T)``: the long-run cost rate of overhauling every ``T`` and + never replacing. The age at the start of a period settles where an + overhaul takes off what the period added, ``v* = f T / (1 - f)``, so + each period then expects ``Lambda(v* + T) - Lambda(v*)`` repairs and + costs one overhaul. ``g(T, K)`` tends to it as ``K`` grows.""" + v = factor * t / (1.0 - factor) + repairs = _lambda(unit, v + t) - _lambda(unit, v) + return (unit.cr * repairs + unit.co) / t + + +def _minimise(unit, rate, scale: float) -> Tuple[float, float]: + """The interval minimising ``rate`` (a function of an array of + intervals) by a grid search and a bounded refinement: ``inf`` and the + rate at the far end of the grid where lengthening it keeps paying.""" for _ in range(8): grid = scale * np.logspace(-3.0, 3.0, 1201) - rates = _rate(unit, grid, cycles, factor, cp) + with np.errstate(over="ignore", invalid="ignore"): + # A steep intensity (Cox-Lewis's) overflows far out: no plan. + rates = np.nan_to_num(rate(grid), nan=math.inf) i = int(np.argmin(rates)) if i == len(grid) - 1: big = float(grid[-1]) @@ -158,7 +178,7 @@ def _best_interval( continue def f(x: float) -> float: - return float(_rate(unit, np.array([x]), cycles, factor, cp)[0]) + return float(rate(np.array([x]))[0]) res = minimize_scalar( f, @@ -170,8 +190,32 @@ def f(x: float) -> float: return float(grid[i]), float(rates[i]) +def _failure_limit(unit, cp: float, max_failures: int) -> Tuple[int, float]: + """The best replace-at-the-``n``-th-failure plan at the replacement + cost ``cp``: ``(cr (n - 1) + cp) / E[T_n]``, with ``E[T_n]`` exact for + an analytic model. ``(0, inf)`` when ``E[T_n]`` is infinite (an + intensity that falls away).""" + try: + expected = unit._exact_times_to_failures(max_failures) + except ValueError: + return 0, math.inf + n = np.arange(1, len(expected) + 1) + rates = (unit.cr * (n - 1) + cp) / expected + i = int(np.nanargmin(rates)) + return int(n[i]), float(rates[i]) + + +#: The plans compared, in the order a tie is settled (the first wins). +PLANS = ( + "replace only", + "overhaul and replace", + "overhaul only", + "failure limit", +) + + def optimal_policy( - unit, overhaul_factor, replacement_cost, max_cycles + unit, overhaul_factor, replacement_cost, max_cycles, max_failures ) -> OverhaulReplacePolicy: """See ``Repairable.optimal_overhaul_replace_policy``.""" unit._require_costs() @@ -183,18 +227,67 @@ def optimal_policy( "max_cycles must be a whole number, 1 or more; got " f"{max_cycles!r}." ) + if not (checks.is_whole(max_failures) and int(max_failures) >= 1): + raise ValueError( + "max_failures must be a whole number, 1 or more; got " + f"{max_failures!r}." + ) scale = _scale(unit, cp) + interval, rate = _best_interval(unit, 1, factor, cp, scale) + if math.isinf(interval): + # No wear-out: neither overhauls nor replacements pay; run the + # unit to failure, repairing it. + return OverhaulReplacePolicy( + interval=interval, + cycles=1, + cost_rate=rate, + plan="run to failure", + alternatives={"run to failure": {"cost_rate": rate}}, + saving=0.0, + ) + found = { + "replace only": {"interval": interval, "cycles": 1, "cost_rate": rate} + } best = None - for k in range(1, int(max_cycles) + 1): + for k in range(2, int(max_cycles) + 1): interval, rate = _best_interval(unit, k, factor, cp, scale) - if math.isinf(interval): - # No wear-out: neither overhauls nor replacements pay. - return OverhaulReplacePolicy( - interval=interval, cycles=1, cost_rate=rate - ) if best is None or rate < best[2] * (1.0 - 1e-12): best = (interval, k, rate) - assert best is not None + limit_reached = False + if best is not None: + limit_reached = best[1] == int(max_cycles) + found["overhaul and replace"] = { + "interval": best[0], + "cycles": best[1], + "cost_rate": best[2], + } + interval, rate = _minimise( + unit, lambda t: _never_replace_rate(unit, t, factor), scale + ) + found["overhaul only"] = { + "interval": interval, + "cycles": math.inf, + "cost_rate": rate, + } + count, rate = _failure_limit(unit, cp, int(max_failures)) + if count: + found["failure limit"] = {"failure_count": count, "cost_rate": rate} + + winner = PLANS[0] + for plan in PLANS[1:]: + if plan in found and found[plan]["cost_rate"] < found[winner][ + "cost_rate" + ] * (1.0 - 1e-12): + winner = plan + others = [found[plan]["cost_rate"] for plan in found if plan != winner] + chosen = found[winner] return OverhaulReplacePolicy( - interval=best[0], cycles=best[1], cost_rate=best[2] + interval=chosen.get("interval", math.inf), + cycles=chosen.get("cycles", 1), + cost_rate=chosen["cost_rate"], + plan=winner, + failure_count=count if winner == "failure limit" else None, + alternatives=found, + saving=min(others) - chosen["cost_rate"] if others else 0.0, + cycles_limit_reached=limit_reached, ) diff --git a/repyability/maintenance/_dated.py b/repyability/maintenance/_dated.py index d77faea5..6694c999 100644 --- a/repyability/maintenance/_dated.py +++ b/repyability/maintenance/_dated.py @@ -124,6 +124,8 @@ def _then_every_notes(layout: _Layout, window_day: date) -> List[str]: def _run_to_failure(layout: _Layout) -> _Decision: + """The long run with nothing planned: running to failure, by the + closed form (discounted where the decision is given a discount).""" return _Decision( "run_to_failure", "After the window no shut recurs and the site allows no planned " @@ -138,7 +140,13 @@ def _run_to_failure(layout: _Layout) -> _Decision: def dated_decision( - layout: _Layout, *, method, failure_timing, refuse, dated_until + layout: _Layout, + *, + method, + failure_timing, + refuse, + dated_until, + discount=None, ) -> Optional[_Decision]: """The dated window's decision, or None where the site has no window (no fixed date from now on and no ``dated_until``) and no fixed dates @@ -175,13 +183,13 @@ def dated_decision( recurring = _recurring_site(site) rec_layout = _Layout(layout.part, recurring, **layout.given) if not recurring.shutdowns and recurring.any_day is None: - long_run = _run_to_failure(rec_layout) + long_run = replace(_run_to_failure(rec_layout), discount=discount) else: long_run = _decide( rec_layout, method=method, horizon=None, - discount=None, + discount=discount, failure_timing=failure_timing, refuse=False, ) @@ -192,7 +200,7 @@ def dated_decision( rec_layout, method=method, horizon=None, - discount=None, + discount=discount, failure_timing=failure_timing, ) return replace(long_run, long_run=long_run, recurring=rec_layout) @@ -200,6 +208,13 @@ def dated_decision( window_end = float(layout.model_at([end_moment])[0]) day = _day_text(last) lead = f"Dated window to {day}, then the long-run average." + if discount is not None: + from repyability.maintenance._shutdowns import _percent + + lead = ( + f"Dated window to {day}, then the discounted long run, at " + f"{_percent(discount)} a year." + ) using = ( f"Using {_fixed_words(fixed)} as dated" if fixed @@ -217,6 +232,7 @@ def dated_decision( text, None, None, + discount=discount, window_day=last, long_run=long_run, recurring=rec_layout, @@ -251,14 +267,20 @@ def dated_decision( f"{lead} {using}, every shut in the window on its real dates, worked " f"out {how}; after {day} only the recurring shuts remain" + (f" ({'; '.join(notes)})" if notes else "") - + ", and their long-run average values everything beyond: " - f"{long_run.text} {_seconds_text(seconds).capitalize()} in all." + + ( + ", and their long-run average values everything beyond: " + if discount is None + else ", and their discounted long run values everything beyond " + "(the window itself discounted to now too): " + ) + + f"{long_run.text} {_seconds_text(seconds).capitalize()} in all." ) return _Decision( "dated_then_long_run", text, solver, seconds, + discount=discount, failure_timing=failure_timing, why=using, how=how, @@ -277,7 +299,11 @@ def _settled(layout: _Layout, decision: _Decision): """The window solved by the backward programme over every shut on its real dates, run on past its end until its decisions agree between two runs: the grid's (``_horizon._grid_solve``) or the quadrature's - (``_horizon._quadrature_solve``).""" + (``_horizon._quadrature_solve``). With a discount every step, the + run-on's too, is discounted by the calendar time it spans, so what + lies past the window is valued by the recurring shuts' discounted + long run (their own on the real dates), not by undiscounted relative + values.""" from repyability.maintenance._horizon import ( _grid_solve, _later_end, @@ -286,11 +312,12 @@ def _settled(layout: _Layout, decision: _Decision): end = float(decision.window_end or 0.0) extra = _later_end(layout, end) - end + discount = float(decision.discount or 0.0) previous = None found: Any = None for _ in range(DOUBLINGS + 1): if decision.failure_timing == "exact": - shuts, values = _quadrature_solve(layout, end + extra, 0.0) + shuts, values = _quadrature_solve(layout, end + extra, discount) inside = _within(shuts.times, end) seen = ( tuple(np.asarray(shuts.kinds, object)[inside]), @@ -298,7 +325,7 @@ def _settled(layout: _Layout, decision: _Decision): ) found = ("exact", shuts, values, extra) else: - solved = _grid_solve(layout, end + extra, 0.0) + solved = _grid_solve(layout, end + extra, discount) first, kinds, grid, step = ( solved[1], solved[2], @@ -470,6 +497,16 @@ def _run_to_failure_rate(layout: _Layout) -> float: return float(part.cu) / _mean(part, _survival(part)) +def _run_to_failure_eac(layout: _Layout, discount: float) -> float: + """Running to failure's equivalent annual cost a unit of the part's + clock, at the yearly ``discount``.""" + from repyability.maintenance._options import discounted_run_to_failure + from repyability.maintenance._site_policy import model_rate + + rate = model_rate(layout, discount) + return discounted_run_to_failure(layout.part, rate, float(layout.part.cu)) + + def _phrase_dated(layout, rows, unit) -> Tuple[List[str], List[str]]: """The window's shuts of kinds with fixed dates, one phrase each.""" unit_words = f" {unit}" if unit else "" @@ -531,6 +568,7 @@ def dated_policy( ) from repyability.maintenance._site_policy import ( ANY_DAY, + EAC, ReplacementRule, ShutdownPolicy, _figure, @@ -540,6 +578,7 @@ def dated_policy( ) site = layout.site + discount = decision.discount end = float(decision.window_end or 0.0) assert decision.window_day is not None day = _day_text(decision.window_day) @@ -554,10 +593,11 @@ def dated_policy( n: (math.inf, math.inf) for n in decision.recurring.site.names } long_route, long_solver = "run_to_failure", "closed form" - long_statement = ( - f"running to failure: {_figure(measure, rate * scale, None)}" - ) cost, cost_se, cost_rate = rate * scale, None, rate + if discount is not None: + measure = EAC + cost = _run_to_failure_eac(layout, discount) * scale + long_statement = f"running to failure: {_figure(measure, cost, None)}" by_kind = { "failure": scale / R._mean(layout.part, R._survival(layout.part)) } @@ -570,6 +610,7 @@ def dated_policy( long_statement = long_policy.route_text cost, cost_se = long_policy.cost, long_policy.cost_se cost_rate = long_policy.cost_rate + measure = long_policy.measure by_kind = dict(long_policy.replacements_by_kind) kind, solved, values, extra = _settled(layout, decision) names_site = list(site.names) @@ -599,9 +640,24 @@ def dated_policy( share = np.zeros(ages.size + 1) share[min(int(round(age / step)), ages.size)] = 1.0 _, replaced, failures = R._propagate(share, first[:n], ages.p) - planned = replaced > 0 - dated_cost = float(np.dot(replaced[planned], costs[:n][planned])) - dated_cost += float(failures) * float(failure) + if discount is None: + planned = replaced > 0 + dated_cost = float(np.dot(replaced[planned], costs[:n][planned])) + dated_cost += float(failures) * float(failure) + else: + # The window's own decisions, each step discounted by the + # calendar time it spans: the present value to its end. + from repyability.maintenance._horizon import _betas + + to_end, _, _ = R._sweep( + np.zeros(ages.size + 1), + costs[:n], + ages.p, + failure, + _betas(layout, n, step, discount), + fixed=first[:n], + ) + dated_cost = float(to_end[min(int(round(age / step)), ages.size)]) for k, name in enumerate(names): label = ANY_DAY if name == ANYTIME else name window_replacements[label] = float(replaced[kinds[:n] == k].sum()) @@ -640,6 +696,15 @@ def merge(until): # The window's own decisions to its end, priced from the part now. from repyability.maintenance._horizon import _Shuts + rhos = None + if discount is not None: + from repyability.maintenance._horizon import _segment_rates + + rhos = _segment_rates( + layout, + np.concatenate([[0.0], shuts.times[inside], [end]]), + discount, + ) priced = _Shuts( layout.part, shuts.times[inside], @@ -648,7 +713,7 @@ def merge(until): 0.0, end, layout.part.cu, - None, + rhos, shuts.thresholds[inside], ) priced_values = priced.solve() @@ -712,11 +777,22 @@ def merge(until): ) notes = _then_every_notes(layout, decision.window_day) figure = _figure(measure, cost, cost_se) + if discount is None: + then = "the long-run average" + cost_words = "Expected cost" + else: + from repyability.maintenance._shutdowns import _percent + + then = f"the discounted long run at {_percent(discount)} a year" + figure += " (equivalent annual cost)" + cost_words = "Present value of the cost" text = ( - f"Dated window to {day}, then the long-run average: {figure}. " - f"{using}, then the recurring shuts' long-run average after {day}" + f"Dated window to {day}, then {then}: {figure}. " + f"{using}, then the recurring shuts' " + + ("long-run average" if discount is None else "discounted long run") + + f" after {day}" + (f"; {'; '.join(notes)}" if notes else "") - + f". Expected cost to {day}: " + + f". {cost_words} to {day}: " + ( _money(round(dated_cost, 2)) if dated_cost >= 0.01 @@ -755,6 +831,7 @@ def merge(until): dated_cost=float(dated_cost), long_run_route=long_route, long_run_solver=long_solver, + discount=None if discount is None else float(discount), )._bind(engine, layout, decision) @@ -774,7 +851,9 @@ def dated_rule_cost( ): """A fixed rule at a site with a dated window: its long-run cost after the window (on the recurring shuts, by their route), and the - expected cost of a new part to the window's end.""" + expected cost of a new part to the window's end; with a discount, + the recurring shuts' discounted long run (its equivalent annual + cost) and the present value to the window's end.""" from repyability.maintenance._horizon import _grid_solve, _quadrature_solve from repyability.maintenance._site_policy import ( ANY_DAY, @@ -791,33 +870,44 @@ def dated_rule_cost( kept = recurring_rule(decision, rule) pace, measure = _measure(layout) scale = pace if pace is not None else 1.0 + discount = float(decision.discount or 0.0) + eac = None if long_run.route == "run_to_failure": rate = _run_to_failure_rate(layout) long = None + if discount: + eac = _run_to_failure_eac(layout, discount) * scale else: long = _rule_cost(recurring, long_run, kept, name, settings) rate = float(long.cost_rate or 0.0) + eac = long.eac if decision.failure_timing == "exact": - _, values = _quadrature_solve(layout, end, 0.0, rule) + _, values = _quadrature_solve(layout, end, discount, rule) dated_cost = float(values[0]) else: grid_rule = { (ANYTIME if k == ANY_DAY else k): v for k, v in rule.items() } grid_rule = {k: v for k, v in grid_rule.items() if math.isfinite(v)} - v, *_ = _grid_solve(layout, end, 0.0, grid_rule) + v, *_ = _grid_solve(layout, end, discount, grid_rule) dated_cost = float(v[0]) day = _day_text(decision.window_day) + figure = float(rate * scale) if eac is None else float(eac) + if eac is not None: + from repyability.maintenance._site_policy import EAC + + measure = EAC + worth = "expected cost" if eac is None else "present value" return RuleCost( name=name, rule=dict(rule), - cost=float(rate * scale), + cost=figure, measure=measure, cost_se=None if long is None else long.cost_se, route="dated_then_long_run", route_text=( - f"{name}: {_figure(measure, rate * scale, None)} after {day}; " - f"expected cost to {day} {_money(round(dated_cost, 2))}" + f"{name}: {_figure(measure, figure, None)} after {day}; " + f"{worth} to {day} {_money(round(dated_cost, 2))}" ), solver=decision.solver or "", failure_timing=decision.failure_timing, @@ -828,4 +918,5 @@ def dated_rule_cost( ), cost_rate=rate, dated_cost=dated_cost, + eac=eac, ) diff --git a/repyability/maintenance/_finding_window.py b/repyability/maintenance/_finding_window.py new file mode 100644 index 00000000..62d310ec --- /dev/null +++ b/repyability/maintenance/_finding_window.py @@ -0,0 +1,600 @@ +"""A hidden failure tested at given times, over a window from the device's +age (UC-53 of this package's ``README.md``). + +``failure_finding`` gives the long run of one even interval. Here the +tests are at any times, the device starts working at an age, and the +answer is over a window: the chance each test finds the device failed, +the time it is failed, the demands that meet it failed, and what the +plan costs. + +**The model.** The device is working, at an age since it was last made +new, or failed without anyone knowing. A test of a working device leaves +its age; one that finds it failed makes it new, in no time. Demands come +at a rate ``d`` (a Poisson process, independent of the device), and one +that meets the device failed costs the consequence; with +``demands_reveal`` it also shows the failure, which is repaired as new +then. + +**How it is worked out.** ``A(t)``, the chance the device is working at +``t``, is the sum over the times it was made new of the chance of that +and of surviving since:: + + A(t) = R(age + t) / R(age) + + sum_{tests t_k < t} q_k R(t - t_k) + + d integral_0^t U(s) R(t - s) ds, U = 1 - A, + +with ``q_k = U(t_k)`` just before the test (what it finds), and the last +term only where demands reveal. Without it ``A`` is exact at any time +(a sum over the tests so far). With it, this is a Volterra equation of +the second kind, solved on a grid of each stretch between tests by the +trapezoid rule. Either way the integrals of ``U`` are the trapezoid +rule's on that grid, the whole worked out at one grid and at twice as +fine, and every number taken from the two by Richardson's step (``fine + +(fine - coarse) / 3``, the trapezoid's error falling four-fold); the +difference of the two is the precision given, and the grid is halved +until that is within the tolerance. +""" + +from dataclasses import dataclass +from typing import Callable, Literal, Optional + +import numpy as np + +from repyability.rbd.results import _ResultMapping +from repyability.utils import checks +from repyability.utils.vectors import dot + +from ._decisions import _check_protective, _number, _prices, _survival_at + +#: The most tests in a window: the work grows with their square. +MAX_TESTS = 2000 +#: How close the failed time and the failures found are worked out, as a +#: share of each, by default. +TOLERANCE = 1e-6 +#: Steps across the window at the coarsest grid, and the least in a +#: stretch between two tests. +_STEPS = 32 +_LEAST = 2 +#: The most survival values a grid may take (its work); a finer grid is +#: not tried, and the precision says how close the last one is. +_WORK = 4.0e7 + + +@dataclass(frozen=True) +class _Pass: + """The device's chance of being failed on one grid: at the nodes of + each stretch between tests (a test's time is the end of one stretch, + before the test, and the start of the next, after it).""" + + left: np.ndarray # each step's start and end, and the values there + right: np.ndarray + down_left: np.ndarray + down_right: np.ndarray + cum_left: np.ndarray # the failed time to each step's start and end + cum_right: np.ndarray + found: np.ndarray # the chance each test finds the device failed + nodes: np.ndarray + weights: np.ndarray + down: np.ndarray + + def _step(self, times: np.ndarray, side: Literal["left", "right"]): + k = np.searchsorted(self.left, times, side=side) - 1 + k = np.clip(k, 0, self.left.size - 1) + width = self.right[k] - self.left[k] + return k, width, np.clip((times - self.left[k]) / width, 0.0, 1.0) + + def failed_time(self, times: np.ndarray) -> np.ndarray: + """The integral of the chance of being failed from 0 to each of + ``times``: the cubic through each step's ends with their slopes + (the chances there).""" + k, h, s = self._step(times, "right") + return ( + (2 * s**3 - 3 * s**2 + 1) * self.cum_left[k] + + (s**3 - 2 * s**2 + s) * h * self.down_left[k] + + (3 * s**2 - 2 * s**3) * self.cum_right[k] + + (s**3 - s**2) * h * self.down_right[k] + ) + + def unavailability(self, times: np.ndarray) -> np.ndarray: + """The chance of being failed at each of ``times``: at a test's + time, just before it.""" + k, _, s = self._step(times, "left") + return (1.0 - s) * self.down_left[k] + s * self.down_right[k] + + +def _solve( + survival: Callable, + age: float, + tests: np.ndarray, + window: float, + reveal: float, + counts: np.ndarray, +) -> _Pass: + """One grid's pass: ``tests`` the distinct test times in ``(0, + window]``, ``reveal`` the rate at which a failed device is shown and + repaired (the demand rate, or 0), ``counts`` each stretch's steps.""" + inside = tests[tests < window] + edges = np.concatenate([[0.0], inside, [window]]) + stretches = edges.size - 1 + nodes_: list = [] + weights_: list = [] + stretch_: list = [] + first_: list = [] + for m in range(stretches): + n = int(counts[m]) + h = (edges[m + 1] - edges[m]) / n + weights = np.full(n + 1, h) + weights[0] = weights[-1] = 0.5 * h + first_.append(sum(len(x) for x in nodes_)) + nodes_.append(np.linspace(edges[m], edges[m + 1], n + 1)) + weights_.append(weights) + stretch_.append(np.full(n + 1, m)) + nodes = np.concatenate(nodes_) + weights = np.concatenate(weights_) + stretch = np.concatenate(stretch_) + first = set(first_) + up = survival(age + nodes) / survival(np.array([age]))[0] + down = np.zeros(nodes.size) + mass = np.zeros(inside.size) # the chance of being made new at a test + flow = np.zeros(nodes.size) # weights x the rate of being made new + for i in range(nodes.size): + m = int(stretch[i]) + value = float(up[i]) + if m > 0: + value += dot(mass[:m], survival(nodes[i] - inside[:m])) + if reveal > 0.0 and i > 0: + value += dot(flow[:i], survival(nodes[i] - nodes[:i])) + if i not in first: + # This node's own half step of the integral. + half = reveal * weights[i] + if i + 1 < nodes.size and stretch[i + 1] == m: + half *= 0.5 + value = (value + half) / (1.0 + half) + down[i] = min(max(1.0 - value, 0.0), 1.0) + if i in first: + # Just after a test (or at the start) the device is working. + down[i] = 0.0 + flow[i] = reveal * weights[i] * down[i] + if i + 1 < nodes.size and stretch[i + 1] != m: + mass[m] = down[i] + inner = np.flatnonzero(stretch[:-1] == stretch[1:]) + areas = 0.5 * (nodes[inner + 1] - nodes[inner]) + areas = areas * (down[inner] + down[inner + 1]) + cum = np.concatenate([[0.0], np.cumsum(areas)]) + found = mass + if tests.size > inside.size: # a test at the window's end + found = np.append(mass, down[-1]) + return _Pass( + left=nodes[inner], + right=nodes[inner + 1], + down_left=down[inner], + down_right=down[inner + 1], + cum_left=cum[:-1], + cum_right=cum[1:], + found=found, + nodes=nodes, + weights=weights, + down=down, + ) + + +@dataclass(frozen=True) +class _Solved: + """A device's hidden failures over a window, from two grids.""" + + window: float + tests: np.ndarray + fine: Optional[_Pass] + coarse: Optional[_Pass] + + def _both(self, of: Callable[[_Pass], np.ndarray]) -> np.ndarray: + assert self.fine is not None and self.coarse is not None + fine = of(self.fine) + return fine + (fine - of(self.coarse)) / 3.0 + + @property + def found(self) -> np.ndarray: + """The chance each test finds the device failed.""" + if self.fine is None: + return np.zeros(self.tests.size) + return np.clip(self._both(lambda p: p.found), 0.0, 1.0) + + def failed_time(self, times) -> np.ndarray: + """The expected time failed from 0 to each of ``times``.""" + times = np.clip(np.asarray(times, float), 0.0, self.window) + if self.fine is None: + return np.zeros(times.shape) + flat = times.ravel() + total = self._both(lambda p: p.failed_time(flat)) + return np.maximum(total, 0.0).reshape(times.shape) + + def unavailability(self, times) -> np.ndarray: + """The chance the device is failed at each of ``times`` (just + before a test at a test's time).""" + times = np.clip(np.asarray(times, float), 0.0, self.window) + if self.fine is None: + return np.zeros(times.shape) + flat = times.ravel() + value = self._both(lambda p: p.unavailability(flat)) + return np.clip(value, 0.0, 1.0).reshape(times.shape) + + def discounted_failed_time(self, rate: float) -> float: + """The integral of the chance of being failed, discounted at + ``rate`` a unit of time.""" + if self.fine is None: + return 0.0 + return float( + self._both( + lambda p: np.array( + dot(p.weights * np.exp(-rate * p.nodes), p.down) + ) + ) + ) + + @property + def time_error(self) -> float: + """How far the failed time over the window can be out.""" + if self.fine is None or self.coarse is None: + return 0.0 + end = np.array([self.window]) + return float( + abs(self.fine.failed_time(end) - self.coarse.failed_time(end))[0] + ) + + @property + def found_error(self) -> float: + """How far the failures found, in all, can be out.""" + if self.fine is None or self.coarse is None: + return 0.0 + return float(np.abs(self.fine.found - self.coarse.found).sum()) + + +def _hidden( + model, + age: float, + tests: np.ndarray, + window: float, + reveal: float, + tolerance: float = TOLERANCE, +) -> _Solved: + """The device's hidden failures over ``window`` from ``age``, tested + at ``tests`` (distinct, increasing, in ``(0, window]``), a failed + device shown and repaired at the rate ``reveal`` (0: only tests find + it).""" + tests = np.asarray(tests, float) + if not window > 0.0: + return _Solved(float(window), tests, None, None) + if tests.size > MAX_TESTS: + raise NotImplementedError( + f"{tests.size} tests in the window: at most {MAX_TESTS} are " + "worked out (the work grows with their square). Value a " + "shorter window, or, for one even interval in the long run, " + "use failure_finding." + ) + + def survival(times) -> np.ndarray: + return _survival_at(model, times) + + if not survival(np.array([age]))[0] > 0.0: + raise ValueError( + f"The device has no chance of reaching age={age:g}: give " + "the age of a working device." + ) + edges = np.concatenate([[0.0], tests[tests < window], [window]]) + lengths = np.diff(edges) + counts = np.maximum( + _LEAST, np.ceil(lengths / (window / _STEPS)).astype(int) + ) + + def work(steps: np.ndarray) -> float: + nodes = float(steps.sum() + steps.size) + return nodes * tests.size + (0.5 * nodes**2 if reveal > 0.0 else 0.0) + + coarse = _solve(survival, age, tests, window, reveal, counts) + while True: + counts = 2 * counts + fine = _solve(survival, age, tests, window, reveal, counts) + solved = _Solved(float(window), tests, fine, coarse) + total = float(solved.failed_time(np.array([window]))[0]) + close = solved.time_error <= tolerance * total and ( + solved.found_error <= tolerance * float(solved.found.sum()) + ) + if close or work(2 * counts) > _WORK: + return solved + coarse = fine + + +# -- the public calculation -------------------------------------------------- + + +@dataclass +class FailureFindingWindow(_ResultMapping): + """A hidden failure tested at given times, over a window: returned by + [`failure_finding_window`][repyability.failure_finding_window]. + + Attributes + ---------- + window : float + The window's length, from now. + age : float + The device's age at the window's start (working then). + test_times : numpy.ndarray + The times of the tests, from the window's start. + demands_reveal : bool + Whether a demand that meets the device failed shows the failure, + which is then repaired as new. + found_at_tests : numpy.ndarray + The chance each test finds the device failed (the device's + unavailability just before it). + failures_found : float + The expected failures the tests find (the sum of + ``found_at_tests``). + failed_time : float + The expected time the device is failed in the window. + mean_unavailability : float + ``failed_time / window``: the average chance the device is + failed when a demand comes. + demands_on_failed : float or None + The expected demands that meet the device failed (the demand + rate times ``failed_time``); None without a demand rate. + times : numpy.ndarray + The times the unavailability is given at. + unavailability : numpy.ndarray + The chance the device is failed at each of ``times`` (at a + test's time, just before the test). + tests_cost : float + The expected cost of the tests, undiscounted. + repairs_cost : float + The expected cost of the repairs, of the failures the tests find + and of those demands show, undiscounted. + consequence_cost : float + The expected cost of the demands that meet the device failed, + undiscounted. + cost : float + The sum of the three. + discount_rate : float + The discount rate, per unit of time, continuously compounded. + present_value : float + ``cost`` discounted to the window's start: each test and the + repair of what it finds from its time, the demands' cost as it + accrues. ``cost`` itself at a rate of 0. + precision : float + How far ``present_value`` (and ``cost``) can be from the true + one: the difference between the last two grids' answers. + """ + + window: float + age: float + test_times: np.ndarray + demands_reveal: bool + found_at_tests: np.ndarray + failures_found: float + failed_time: float + mean_unavailability: float + demands_on_failed: Optional[float] + times: np.ndarray + unavailability: np.ndarray + tests_cost: float + repairs_cost: float + consequence_cost: float + cost: float + discount_rate: float + present_value: float + precision: float + + def __repr__(self) -> str: + return ( + f"FailureFindingWindow({self.test_times.size} tests over " + f"{self.window:g}: mean unavailability " + f"{self.mean_unavailability:.6g}, failures found " + f"{self.failures_found:.6g}, cost {self.cost:.6g}, present " + f"value {self.present_value:.6g})" + ) + + +def _test_times(test_times, window: float) -> np.ndarray: + try: + times = np.atleast_1d(np.asarray(test_times, dtype=float)) + except (TypeError, ValueError): + times = np.array([np.nan]) + if np.size(test_times) == 0: + return np.array([], float) + ok = ( + times.ndim == 1 + and np.all(np.isfinite(times)) + and np.all(times >= 0.0) + and np.all(times <= window) + and np.all(np.diff(times) > 0.0) + ) + if not ok: + raise ValueError( + "test_times must be the tests' times from the window's " + f"start, increasing, each from 0 to window={window:g} (leave " + f"out the tests after it); got {test_times!r}." + ) + return times + + +def failure_finding_window( + protective, + test_times, + window, + *, + age=0.0, + test_cost=0.0, + repair_cost=0.0, + demand_rate=None, + consequence_cost=0.0, + discount_rate=0.0, + demands_reveal=True, + times=None, + tolerance=TOLERANCE, +) -> FailureFindingWindow: + """A hidden failure tested at given times, over a window from the + device's age: what each test finds, how long the device is failed, + the demands that meet it failed, and what the plan costs and is + worth. + + In plain terms: a protective device (a relief valve, a trip) fails + without anyone knowing. It is working now, at ``age``, and is tested + at ``test_times`` from now (any times, not one interval; none for + "never tested"). A test finds and repairs a failed device as new, in + no time; a working one carries on at its age. Demands come at + ``demand_rate``, and one that meets the device failed costs + ``consequence_cost``; with ``demands_reveal`` (the default) it also + shows the failure, which is repaired as new then, at + ``repair_cost``. Without it, only a test finds a failure, as + [`failure_finding`][repyability.failure_finding] has it in the long + run. + + Exact at the tests where demands do not reveal (or there are none), + and numerical otherwise, to ``precision``. + + Parameters + ---------- + protective : NonRepairable + The device: its life (a failure is hidden) as a part. Its own + costs are not used. + test_times : array_like + The tests' times from now, increasing, within the window; empty + for a device never tested. + window : float + How far ahead, more than 0. + age : float, optional + The device's age now (it is working), by default 0. + test_cost : float, optional + What a test costs, by default 0. + repair_cost : float, optional + What repairing a failure costs, found by a test or shown by a + demand, by default 0. + demand_rate : float, optional + How often the protected event comes, per unit time. + consequence_cost : float, optional + What a demand met by a failed device costs (needs + ``demand_rate``), by default 0. + discount_rate : float, optional + The discount rate per unit of time, continuously compounded, by + default 0. + demands_reveal : bool, optional + Whether a demand that meets the device failed shows the failure + and has it repaired, by default True. + times : array_like, optional + The times to give the unavailability at; by default 101 evenly + over the window. + tolerance : float, optional + How close the failed time and the failures found are worked out, + as a share of each; by default 1e-6. + + Returns + ------- + FailureFindingWindow + + Raises + ------ + NotImplementedError + The device's life has no survival function in closed form, or + there are more than 2,000 tests in the window. + ValueError + A number out of its range; test times not increasing or outside + the window; a consequence with no demand rate. + + Examples + -------- + A trip failing hidden at 0.1 a year, tested at 6 and 12 months and + then at 2 years, over 3 years; a demand comes once in 2 years: + + >>> import surpyval as surv + >>> from repyability import NonRepairable, failure_finding_window + >>> trip = NonRepairable(surv.Exponential.from_params([0.1])) + >>> tested = failure_finding_window( + ... trip, [0.5, 1.0, 2.0], 3.0, demand_rate=0.5, + ... test_cost=200.0, repair_cost=1500.0, consequence_cost=50_000.0, + ... ) + >>> [round(float(q), 4) for q in tested.found_at_tests] + [0.0432, 0.0432, 0.0752] + >>> round(tested.mean_unavailability, 4), round(tested.cost, 2) + (0.0351, 3555.15) + >>> never = failure_finding_window( + ... trip, [], 3.0, demand_rate=0.5, consequence_cost=50_000.0, + ... repair_cost=1500.0, + ... ) + >>> round(never.mean_unavailability, 4), round(never.cost, 2) + (0.0894, 6904.57) + """ + _check_protective(protective) + window = _number(window, "window", strict=True) + age = _number(age, "age") + test, repair, consequence, demand = _prices( + test_cost, repair_cost, consequence_cost, demand_rate + ) + rate = _number(discount_rate, "discount_rate") + if not isinstance(demands_reveal, (bool, np.bool_)): + raise ValueError( + f"demands_reveal must be True or False; got {demands_reveal!r}." + ) + if not (checks.is_number(tolerance) and 0.0 < float(tolerance) < 1.0): + raise ValueError( + "tolerance must be a share, more than 0 and less than 1 " + f"(such as 1e-6); got {tolerance!r}." + ) + tests = _test_times(test_times, window) + if times is None: + at = np.linspace(0.0, window, 101) + else: + at = checks.real_array(times, "times") + if np.any(at < 0.0) or np.any(at > window): + raise ValueError( + f"times must be from 0 to window={window:g}; got {times!r}." + ) + reveal = demand if demands_reveal and demand is not None else 0.0 + solved = _hidden( + protective.reliability, + age, + tests[tests > 0.0], + window, + reveal, + float(tolerance), + ) + found = np.zeros(tests.size) + found[tests > 0.0] = solved.found # at time 0 the device is working + failed = float(solved.failed_time(np.array([window]))[0]) + discounted = solved.discounted_failed_time(rate) + met = None if demand is None else demand * failed + each = consequence + (repair if reveal > 0.0 else 0.0) + factors = np.exp(-rate * tests) + tests_cost = test * tests.size + repairs_cost = repair * float(found.sum()) + if reveal > 0.0: + repairs_cost += repair * reveal * failed + consequences = 0.0 if demand is None else consequence * demand * failed + present = ( + test * float(factors.sum()) + + repair * dot(factors, found) + + (0.0 if demand is None else each * demand * discounted) + ) + cost = tests_cost + repairs_cost + consequences + if rate == 0.0: + present = cost # the same sum, to the last bit + precision = repair * solved.found_error + if demand is not None: + precision += each * demand * solved.time_error + return FailureFindingWindow( + window=window, + age=age, + test_times=tests, + demands_reveal=bool(demands_reveal), + found_at_tests=found, + failures_found=float(found.sum()), + failed_time=failed, + mean_unavailability=failed / window, + demands_on_failed=met, + times=at, + unavailability=solved.unavailability(at), + tests_cost=tests_cost, + repairs_cost=repairs_cost, + consequence_cost=consequences, + cost=cost, + discount_rate=rate, + present_value=present, + precision=precision, + ) diff --git a/repyability/maintenance/_horizon.py b/repyability/maintenance/_horizon.py index 5e6e2b75..36a961c5 100644 --- a/repyability/maintenance/_horizon.py +++ b/repyability/maintenance/_horizon.py @@ -37,17 +37,14 @@ _Layout, _money, ) +from repyability.value._rates import continuous as _rate +from repyability.value._rates import equivalent as _equivalent #: The horizon is moved on by at least this many years to see which #: decisions depend on where it ends. LATER_YEARS = 5.0 -def _rate(discount: float) -> float: - """A yearly discount rate as a continuous one.""" - return math.log1p(float(discount)) - - def _grid_setup(layout: _Layout, end: float): from repyability.maintenance import _replacement as R from repyability.maintenance._site_policy import _dated_calendar @@ -74,27 +71,40 @@ def _betas( return np.exp(-_rate(discount) * np.diff(years)) -def _grid_solve(layout: _Layout, end: float, discount: float, rule=None): - """The backward sweep to model time ``end``: the values at the first - step by age, each step's first replacing age index and kind, the - prices, and the grid.""" +def backward(grid, ages, failure, n: int, beta, rule=None): + """The backward sweep over the first ``n`` steps of ``grid`` with + nothing counted after them (``_replacement._sweep`` from zero + values), each step discounted by ``beta`` (a number, or one a step): + the values at the first step by age, each step's first replacing age + index and kind, the prices, and whether the replacing ages were + thresholds. ``rule`` fixes the decisions (the age from which each + kind replaces, by name). The horizon route's sweep, on a site's real + dates and in model time alike.""" from repyability.maintenance import _replacement as R from repyability.maintenance._site_policy import _rule_kinds - grid, ages, failure, step = _grid_setup(layout, end) - n = max(int(math.ceil(end / step - 1e-9)), 1) - beta = _betas(layout, n, step, discount) if rule is None: costs, kinds = grid.prices(0, n) - v, first, _ = R._sweep( + v, first, upper = R._sweep( np.zeros(ages.size + 1), costs, ages.p, failure, beta ) else: costs, first = R._rule_prices(grid, rule, 0, n) kinds = _rule_kinds(grid, rule, n) - v, first, _ = R._sweep( + v, first, upper = R._sweep( np.zeros(ages.size + 1), costs, ages.p, failure, beta, fixed=first ) + return v, first, kinds, costs, upper + + +def _grid_solve(layout: _Layout, end: float, discount: float, rule=None): + """The backward sweep to model time ``end``: the values at the first + step by age, each step's first replacing age index and kind, the + prices, and the grid.""" + grid, ages, failure, step = _grid_setup(layout, end) + n = max(int(math.ceil(end / step - 1e-9)), 1) + beta = _betas(layout, n, step, discount) + v, first, kinds, costs, _ = backward(grid, ages, failure, n, beta, rule) return v, first, kinds, costs, grid, ages, failure, step @@ -508,9 +518,11 @@ def horizon_policy(layout: _Layout, decision: _Decision, age: float, life): settings = {"step": step, "steps": int(first.size)} per_year = {k: x / years for k, x in counts.items()} when = _day_text(layout.clock.local_naive(end_moment).date()) + eac = _equivalent(npc, _rate(discount), years) text = ( f"Lowest net present cost to {when} at {discount:.0%} a year: " - f"{_money(round(npc, 2)) if npc >= 0.01 else f'${npc:.3g}'}." + f"{_cents(npc)} (an equivalent annual cost of {_cents(eac)} a " + "year)." ) if depends is not None: moment = layout.moment_at([depends])[0] @@ -566,9 +578,14 @@ def horizon_policy(layout: _Layout, decision: _Decision, age: float, life): notes=tuple(layout.notes), settings=settings, life=life, + eac=eac, )._bind(engine, layout, decision) +def _cents(value: float) -> str: + return _money(round(value, 2)) if value >= 0.01 else f"${value:.3g}" + + def horizon_rule_cost(layout: _Layout, decision: _Decision, rule, name): """A fixed rule's net present cost to the horizon, from a new part.""" from repyability.maintenance._site_policy import ANY_DAY, RuleCost @@ -599,6 +616,7 @@ def horizon_rule_cost(layout: _Layout, decision: _Decision, rule, name): counts = {_label(k): x for k, x in counted.items()} if layout.site.any_day is None: counts.pop(ANY_DAY, None) + eac = _equivalent(npc, _rate(discount), years) return RuleCost( name=name, rule=dict(rule), @@ -606,11 +624,16 @@ def horizon_rule_cost(layout: _Layout, decision: _Decision, rule, name): measure="net present cost", cost_se=None, route="horizon", - route_text=f"{name}: net present cost {_money(round(npc, 2))}", + route_text=( + f"{name}: net present cost {_money(round(npc, 2))} (an " + f"equivalent annual cost of {_cents(eac)} a year)" + ), solver=decision.solver or "", failure_timing=decision.failure_timing, replacements_by_kind={k: x / years for k, x in counts.items()}, cost_rate=None, + npv=npc, + eac=eac, ) @@ -731,3 +754,232 @@ def shuts_between(a, b): life=life, ) return policy._bind(table, names + [ANYTIME], None, oldest) + + +# ------------------------------------------------------ a ready horizon + +#: A ready horizon (what a refusal offers in its place): costs past it, +#: discounted, count for under this share of the total. +READY_SHARE = 1e-9 +#: Undiscounted, a ready horizon is the full cycle and this many of the +#: part's life spans (the age it outlives with a chance of 1e-3) past it. +READY_SPANS = 3 +#: ... but no more than this many steps of the grid (about a minute's +#: sweep), where the full cycle is longer (co-prime periods). +READY_STEPS = 2_000_000 + + +def ready_years(discount: float) -> int: + """The whole years past which costs at the yearly ``discount`` (more + than 0) are discounted to under ``READY_SHARE``.""" + return int( + math.ceil(math.log(1.0 / READY_SHARE) / math.log1p(float(discount))) + ) + + +def _rounded_up(value: float) -> float: + """``value`` rounded up to three significant figures.""" + if not value > 0.0: + return value + scale = 10.0 ** (math.floor(math.log10(value)) - 2) + return float(math.ceil(value / scale - 1e-9) * scale) + + +def _literal(value: float) -> str: + """A model time as it would be typed: ``112000``, ``2.5``.""" + if float(value).is_integer(): + return str(int(value)) + return f"{value:.6g}" + + +def ready_model_horizon( + rate: float, span: float, cycle=None, end=None, step=None +): + """A horizon in model time that works for a calendar a long run + refuses: with a continuous discount ``rate`` a unit of time, where + costs are discounted to under ``READY_SHARE``; with none, the full + ``cycle`` and ``READY_SPANS`` life spans past it, but at most + ``READY_STEPS`` of the grid's ``step``. At least a plan's last date + (``end``) and the spans past it. Rounded up to three significant + figures; with the reason in words.""" + if rate > 0.0: + value = math.log(1.0 / READY_SHARE) / rate + why = ( + "at this rate, costs past then are discounted to under one part " + "in a billion" + ) + else: + value = (cycle or 0.0) + READY_SPANS * span + why = ( + "the full cycle and three of the part's life spans past it" + if cycle + else "three of the part's life spans" + ) + if step is not None and value > READY_STEPS * step: + value = READY_STEPS * step + why = ( + f"{READY_STEPS:,} steps of the grid, about a minute's work: " + "the full cycle is longer than is worth sweeping" + ) + if end is not None: + value = max(value, float(end) + READY_SPANS * span) + return _rounded_up(value), why + + +def ready_model_text( + rate: float, span: float, cycle=None, end=None, step=None +) -> str: + """``horizon=`` and why, for a refusal in model time.""" + value, why = ready_model_horizon(rate, span, cycle, end, step) + return f"horizon={_literal(value)} (in the calendar's time; {why})" + + +def _years_after(day, years: int): + try: + return day.replace(year=day.year + years) + except ValueError: # 29 February + return day.replace(year=day.year + years, day=28) + + +def ready_site_text( + layout: _Layout, discount, cycle_years=None, step=None +) -> str: + """``horizon=''`` with ``discount=``, and why, for a refusal at + a site: with a yearly ``discount`` the day past which costs are + discounted to under ``READY_SHARE``; with none, the full cycle of the + shuts' dates (``cycle_years``, by default the 28 years after which + weekdays fall on the same dates again) and ``READY_SPANS`` life spans + past it.""" + from repyability.maintenance._shutdowns import ( + SPAN_YEARS, + _life_scale, + _percent, + ) + + rate = float(discount or 0.0) + if rate > 0.0: + years = ready_years(rate) + why = ( + f"at {_percent(rate)} a year, costs past then are discounted to " + "under one part in a billion" + ) + else: + cycle = float(cycle_years if cycle_years is not None else SPAN_YEARS) + pace = layout.pace() + spans = 0.0 + if pace: + spans = READY_SPANS * _life_scale(layout.part)[2] / pace + why = ( + "the full cycle of the shuts' dates and three of the part's " + "life spans past it" + ) + if ( + pace + and step is not None + and cycle + spans > (READY_STEPS * step / pace) + ): + cycle, spans = READY_STEPS * step / pace, 0.0 + why = ( + f"{READY_STEPS:,} steps of the grid, about a minute's work: " + "the full cycle is longer than is worth sweeping" + ) + years = int(math.ceil(cycle + spans - 1e-9)) + given = f"discount={rate:g}" + if layout.now is None: + return ( + f"now= and a horizon= {years} years after it, with {given} " + f"({why})" + ) + day = _years_after(layout.now, years) + return f"horizon='{day.isoformat()}' with {given} ({why})" + + +# ----------------------------------------------------- in model time + + +def _model_solve( + part, calendar, anytime, failure, step, max_age, end, rate, rule=None +): + """The backward sweep in model time to ``end``, from a new part at 0, + each step discounted by ``exp(-rate * step)`` (1 at 0): the given + dates as they are (no tail), periods as they fall.""" + from repyability.maintenance import _replacement as R + + ages = R._Ages(part, step, max_age) + grid = R._Grid(calendar, anytime, step, tail=None) + n = max(int(math.ceil(end / step - 1e-9)), 1) + beta = math.exp(-rate * step) + v, first, kinds, costs, upper = backward( + grid, ages, failure, n, beta, rule + ) + return v, first, kinds, costs, upper, grid, ages, n + + +def model_horizon_policy( + part, calendar, anytime, failure, step, max_age, horizon, rate, life +): + """A policy in model time to a horizon: the lowest net present cost + of a new part at 0 and its successors to ``horizon``, at the + continuous ``rate`` a unit of time (0: the plain total), on every + opportunity as it falls (given dates as they are, nothing assumed + past them). Its ``npv`` is that cost and ``eac`` the steady cost a + unit of time worth it; ``cost_rate`` and the rates by kind are the + rule's undiscounted average to the horizon, from a new part. + ``determined_until`` is the first time a decision changes when the + horizon is moved later (a settling length on).""" + from repyability.maintenance import _replacement as R + from repyability.maintenance._site_policy import _FixedTable + + v, first, kinds, costs, upper, grid, ages, n = _model_solve( + part, calendar, anytime, failure, step, max_age, horizon, rate + ) + length = n * step + npc = float(v[0]) + later = length + R._settle(grid, ages) * step + _, first2, kinds2, *_ = _model_solve( + part, calendar, anytime, failure, step, max_age, later, rate + ) + differ = np.flatnonzero((first != first2[:n]) | (kinds != kinds2[:n])) + until = float(differ[0] * step) if differ.size else length + new = np.zeros(ages.size + 1) + new[0] = 1.0 + _, replaced, failures = R._propagate(new, first, ages.p) + rates, spent = R._summary( + grid.names, anytime, kinds, costs, replaced, failures, failure, length + ) + R._warn_not_threshold(upper) + policy = R.CalendarPolicy( + cost_rate=float(sum(spent.values())), + cost_rate_se=None, + replacement_rates=rates, + cost_rates=spent, + method="dp", + basis="horizon", + step=step, + period=None, + determined_until=until, + threshold_only=upper, + settings={ + "horizon": length, + "steps": int(n), + "table_until": length, + "max_age": ages.size * step, + }, + life=life, + discount_rate=rate, + npv=npc, + eac=_equivalent(npc, rate, length), + ) + table = _FixedTable(first, kinds, replaced) + return policy._bind(table, grid.names, grid, ages.size * step) + + +def model_horizon_rule_cost( + part, calendar, anytime, failure, step, max_age, rule, horizon, rate +) -> float: + """A fixed rule's net present cost (the plain total at ``rate`` 0) in + model time to ``horizon``, from a new part at 0.""" + v, *_ = _model_solve( + part, calendar, anytime, failure, step, max_age, horizon, rate, rule + ) + return float(v[0]) diff --git a/repyability/maintenance/_integration.py b/repyability/maintenance/_integration.py index f896861f..ce8bc9a0 100644 --- a/repyability/maintenance/_integration.py +++ b/repyability/maintenance/_integration.py @@ -28,7 +28,7 @@ import math from fractions import Fraction -from typing import Dict +from typing import Dict, cast import numpy as np @@ -363,13 +363,27 @@ def integrated_policy( tail="repeat", life=None, fixed=None, + discount_rate=0.0, ): """The calendar policy between opportunities in continuous time (see the module's docstring). ``fixed`` prices a given rule instead: the age from which each kind replaces, by name (a kind left out never - does).""" + does). With ``discount_rate`` (continuous, a unit of the calendar's + time) the thresholds minimise the present value of every replacement + from a new part at time 0 (discounted value iteration over the cycle, + stopped by MacQueen's bounds, as ``_replacement._discounted_values``), + and the rule so chosen is then priced undiscounted for the long-run + figures; with ``fixed`` too, the given rule's present value is worked + out with its decisions fixed.""" sf = _survival(part) mean = _mean(part, sf) + rate = float(discount_rate) + if not calendar.opportunities and rate > 0.0: + raise NotImplementedError( + "With no opportunities and no replacement on any day there is " + "only running to failure: leave discount_rate at 0, or use " + "method='dp'." + ) if not calendar.opportunities: policy = CalendarPolicy( cost_rate=failure / mean, @@ -419,19 +433,19 @@ def integrated_policy( limits = np.array( [float(fixed.get(names[k], math.inf)) for k in kinds] ) - shapes: Dict[float, _Gap] = {} + shapes: Dict[tuple, _Gap] = {} - def gap(width): - key = round(width, 9) + def gap(width, rho=0.0): + key = (round(width, 9), rho) if key not in shapes: - shapes[key] = _Gap(width, sf, grid, failure) + shapes[key] = _Gap(width, sf, grid, failure, rho) return shapes[key] - def sweep(h, keep_values=False): + def sweep(h, keep_values=False, rho=0.0): after = h kept: list = [None] * times.size for k in range(times.size - 1, -1, -1): - shape = gap(gaps[k]) + shape = gap(gaps[k], rho) g_nodes = shape.new_unit(after, grid) w = shape.kept(g_nodes, after, grid) if keep_values: @@ -439,6 +453,12 @@ def sweep(h, keep_values=False): after = _decided(w, prices[k], grid, limits, k) return after, kept + discounted: Dict[str, object] = {} + if rate > 0.0: + discounted = _discounted( + sweep, grid, times, gaps, prices, length, rate, oldest, limits + ) + limits = np.asarray(discounted.pop("thresholds")) h = np.zeros(grid.size) limit = max(1, int(MAX_LIVES * oldest / length)) low = high = math.nan @@ -458,6 +478,8 @@ def sweep(h, keep_values=False): for k, (shape, g_nodes, after, w) in enumerate(kept): if limits is not None: thresholds[k] = limits[k] + if discounted: + upper = upper and bool(discounted["upper"]) continue thresholds[k], whole = threshold( shape, g_nodes, after, w, prices[k], grid @@ -494,8 +516,22 @@ def sweep(h, keep_values=False): "opportunities": int(times.size), "tail": tail if repeat is not None else None, "repeat": repeat, + **{ + k: v + for k, v in discounted.items() + if k not in ("npv", "upper") + }, }, life=life, + **( + {} + if not discounted + else { + "discount_rate": rate, + "npv": float(cast(float, discounted["npv"])), + "eac": rate * float(cast(float, discounted["npv"])), + } + ), ) origin = 0.0 if repeat is not None: @@ -511,6 +547,66 @@ def sweep(h, keep_values=False): return policy._bind(table, names, None, oldest) +def _discounted( + sweep, grid, times, gaps, prices, length, rate, oldest, limits=None +): + """The discounted thresholds at each opportunity of the cycle, and a + new part's present value at time 0: value iteration across the cycle, + each gap discounted at ``rate``, stopped by MacQueen's bounds (every + path through a cycle is discounted by the same ``exp(-rate * + length)``), each sweep from the last one's values less a new part's + (see ``_replacement._discounted_values``). With ``limits`` (a fixed + rule's ages, which ``sweep`` applies), the thresholds are those.""" + rho = math.exp(-rate * length) + factor = rho / (1.0 - rho) + h = np.zeros(grid.size) + v = h + limit = max(1, int(MAX_LIVES * oldest / length)) + low = high = math.nan + converged = False + sweeps = 0 + for sweeps in range(1, limit + 1): + v, _ = sweep(h, rho=rate) + change = v - h + low, high = float(change.min()), float(change.max()) + top = abs(float(v[0]) + factor * high) + if factor * (high - low) <= TOLERANCE * max(top, 1e-300): + converged = True + break + h = v - v[0] + values = v + factor * 0.5 * (low + high) + _, kept = sweep(values, keep_values=True, rho=rate) + thresholds = np.empty(times.size) + upper = True + for k, (shape, g_nodes, after, w) in enumerate(kept): + if limits is not None: + thresholds[k] = limits[k] + continue + thresholds[k], whole = threshold( + shape, g_nodes, after, w, prices[k], grid + ) + upper = upper and whole + # A new part at time 0: at the first opportunity if it falls then, + # else put in inside the cycle's last gap, which runs over time 0. + start = float(times[0]) % length + if start <= 1e-12 * length: + npv = float(values[0]) + else: + shape, g_nodes, _, _ = kept[-1] + npv = float(np.interp(length - float(times[-1]), shape.x, g_nodes)) + return { + "thresholds": thresholds, + "upper": upper, + "npv": npv, + "discounted_sweeps": sweeps, + "discounted_converged": converged, + "npv_bounds": ( + float(v[0]) + factor * low, + float(v[0]) + factor * high, + ), + } + + def threshold(shape, g_nodes, after, w, price, grid): """The youngest age at which replacing at an opportunity (at ``price``) beats keeping the part, ``W(a) = price + W(0)``, by diff --git a/repyability/maintenance/_next.py b/repyability/maintenance/_next.py index 744d5528..2d8e9ca8 100644 --- a/repyability/maintenance/_next.py +++ b/repyability/maintenance/_next.py @@ -13,9 +13,21 @@ cost(u, price) = price S(u) + failure (1 - S(u)) - g ∫₀ᵘ S, with ``S(u) = R(a + u) / R(a)``, the chance the part is working ``u`` from -now (replacing now costs its price). The time the part serves is time a -new part would otherwise serve, which ``g`` values: this is the relative -value of the renewal-reward process, a new part taken to be worth the same +now (replacing now costs its price). With a policy chosen at a continuous +discount ``r`` (its ``discount_rate``), each choice is discounted at that +rate and ``g`` is the policy's equivalent annual cost (Fox, 1966): with +``M(u) = ∫₀ᵘ exp(-r t) S(t) dt``, + + cost(u, price) = price exp(-r u) S(u) + + failure (1 - exp(-r u) S(u) - r M(u)) - g M(u), + +the present value of the choice and of the policy after it, less the +policy's present value from now (``g / r``), as the policy is the same +whenever the part is replaced. At ``r = 0`` it is the cost above. + +The time the part serves is time a new part would otherwise serve, +which ``g`` values: this is the relative value of the renewal-reward +process, a new part taken to be worth the same whenever it is fitted. With no outages and the age replacement's rate, replacing now is the best from the optimal replacement age exactly. @@ -114,7 +126,12 @@ class NextReplacement(_ResultMapping): cost_rate : float The value of a unit of the part's service, the baseline: the long-run cost a unit of time of the policy given, or of the part's - [`optimal_replacement_policy`][repyability.NonRepairable.optimal_replacement_policy]. + [`optimal_replacement_policy`][repyability.NonRepairable.optimal_replacement_policy]; + for a policy chosen at a discount, its equivalent annual cost + (``eac``). + discount_rate : float + The continuous rate a unit of time each choice is discounted at: + the policy's ``discount_rate`` (0 for one with none). """ age: float @@ -123,6 +140,7 @@ class NextReplacement(_ResultMapping): choices: List[ReplacementChoice] replace_from_age: float cost_rate: float + discount_rate: float = 0.0 def _amount(value, name: str) -> float: @@ -191,11 +209,20 @@ def _beyond(lasting, scale: float) -> float: class _Life: - """A part's life, priced: each choice's cost from an age.""" - - def __init__(self, sf, scale: float, failed: float, rate: float): + """A part's life, priced: each choice's cost from an age, valued at + ``rate`` a unit of service and discounted at ``discount`` (0: not).""" + + def __init__( + self, + sf, + scale: float, + failed: float, + rate: float, + discount: float = 0.0, + ): self.sf, self.scale = sf, scale self.failed, self.rate = failed, rate + self.discount = discount def survival(self, x: float) -> float: with np.errstate(invalid="ignore"): @@ -205,6 +232,8 @@ def keep(self, age: float, u: float, price: float) -> float: """The cost of keeping a part ``age`` old to ``u`` from now, then replacing it at ``price``.""" held = self.survival(age) + if self.discount > 0.0: + return self._discounted_keep(age, u, price, held) lasting = self.survival(age + u) / held cost = price * lasting + self.failed * (1.0 - lasting) if self.rate > 0.0: @@ -213,6 +242,24 @@ def keep(self, age: float, u: float, price: float) -> float: cost -= self.rate * served / held return cost + def _discounted_keep(self, age, u, price, held) -> float: + """``keep`` at the discount: the chance of reaching ``u`` + discounted to then, the failures before it discounted to when + they fall, and the discounted service ``M``.""" + r = self.discount + if math.isinf(u): + lasting = 0.0 + else: + lasting = math.exp(-r * u) * self.survival(age + u) / held + + def served(x): + return self.survival(x) * math.exp(-r * (x - age)) + + with np.errstate(invalid="ignore"): + m = quad(served, age, age + u, limit=200)[0] / held + failed = max(1.0 - lasting - r * m, 0.0) + return price * lasting + self.failed * failed - self.rate * m + def planned(self, age: float, price: float) -> tuple: """The best time from now for a planned replacement of a part ``age`` old at ``price``, and its cost: ``(0.0, None)`` where no @@ -224,8 +271,16 @@ def planned(self, age: float, price: float) -> tuple: times = np.linspace(0.0, later, _GRID) with np.errstate(invalid="ignore"): lasting = np.ravel(np.asarray(self.sf(age + times), float)) / held - costs = price * lasting + self.failed * (1.0 - lasting) - costs -= self.rate * cumulative_trapezoid(lasting, times, initial=0.0) + if self.discount > 0.0: + lasting = lasting * np.exp(-self.discount * times) + m = cumulative_trapezoid(lasting, times, initial=0.0) + failed = np.maximum(1.0 - lasting - self.discount * m, 0.0) + costs = price * lasting + self.failed * failed - self.rate * m + else: + costs = price * lasting + self.failed * (1.0 - lasting) + costs -= self.rate * cumulative_trapezoid( + lasting, times, initial=0.0 + ) i = int(np.argmin(costs)) if i == _GRID - 1: # Still falling where the part is all but sure to have failed: @@ -265,10 +320,12 @@ def _break_even(beaten, oldest: float) -> float: return high -def _baseline(part, policy) -> float: +def _baseline(part, policy) -> tuple: """The long-run cost a unit of time of ``policy`` (a ``CalendarPolicy`` or a ``MaintenancePolicy``), or of the part's - optimal replacement policy if none is given.""" + optimal replacement policy if none is given, and the continuous + discount rate its choices are discounted at: for a policy chosen at + a discount, its equivalent annual cost and its rate (else 0).""" from repyability.maintenance import CalendarPolicy, MaintenancePolicy if policy is None: @@ -281,7 +338,12 @@ def _baseline(part, policy) -> float: "(optimal_calendar_policy) or a MaintenancePolicy " f"(optimal_replacement_policy), not {what}; got {policy!r}." ) - return _amount(policy.cost_rate, "the cost rate of policy") + discount = float(getattr(policy, "discount_rate", 0.0) or 0.0) + if discount > 0.0: + return _amount(policy.eac, "the equivalent annual cost of policy"), ( + discount + ) + return _amount(policy.cost_rate, "the cost rate of policy"), 0.0 #: ``planned``'s default: the part's planned cost. @@ -297,11 +359,13 @@ def optimal_next_replacement( policy=None, planned=_PART, rate=None, + discount_rate=0.0, ) -> NextReplacement: """The work of ``NonRepairable.optimal_next_replacement`` (see there). ``planned`` prices a planned replacement on any day (None: no such choice) and ``rate`` gives the baseline directly, for a site's - shuts on real dates.""" + shuts on real dates, with ``discount_rate`` the continuous rate its + choices are discounted at.""" from repyability.rbd._model_utils import model_mean if isinstance(planned, str) or now_cost is None: @@ -321,9 +385,13 @@ def optimal_next_replacement( age = float(age) now = part.cp if now_cost is None else _amount(now_cost, "now_cost") coming = _coming(scheduled_outages) - rate = _baseline(part, policy) if rate is None else _amount(rate, "rate") + if rate is None: + rate, discount = _baseline(part, policy) + else: + rate = _amount(rate, "rate") + discount = _amount(discount_rate, "discount_rate") mean = model_mean(part.reliability) - life = _Life(part.reliability_function, mean, part.cu, rate) + life = _Life(part.reliability_function, mean, part.cu, rate, discount) if not life.survival(age) > 0.0: raise ValueError( f"The life gives no chance of a unit working at age {age:g}." @@ -369,4 +437,5 @@ def chosen(kind: str, time: float, price: float, at: float) -> tuple: choices, max(evens), rate, + discount, ) diff --git a/repyability/maintenance/_opportunities.py b/repyability/maintenance/_opportunities.py new file mode 100644 index 00000000..96ed56e2 --- /dev/null +++ b/repyability/maintenance/_opportunities.py @@ -0,0 +1,1217 @@ +"""Opportunities to replace a part, and the part's prices at them (UC-45 +of this package's ``README.md``). + +An [`Opportunity`][repyability.Opportunity] says when a stop or shut +happens, how long it lasts and what it takes down; it carries no price, +as it applies to every part. [`Opportunities`][repyability.Opportunities] +collects a site's (or a calendar's, in model time), and says whether a +planned replacement may be made on any other day. Each part brings its +own prices (`NonRepairable`'s ``planned_cost``, ``unplanned_cost``, +``opportunity_cost``, ``opportunity_costs`` and ``job_duration``), and a +policy lays them on the opportunities here (``resolve``): as the +model-time solvers' ``Calendar``, or the real-date solvers' site, each +opportunity with the part's price. No numerical method is touched. + +The 0.14 and 0.19 forms, which put the prices on the opportunities +(``Calendar``, ``Shutdown``, ``Shutdowns``), still work, deprecated: their +prices are taken as the part's overrides for those opportunities. +""" + +from __future__ import annotations + +import math +from collections.abc import Mapping +from dataclasses import dataclass +from typing import Any, Dict, List, Optional, Tuple + +from repyability.maintenance import _calendar, _shutdowns +from repyability.maintenance._calendar import PART, Opportunity, _price +from repyability.rbd.results import _ResultMapping +from repyability.utils import checks +from repyability.utils.deprecation import price_on_part, replaced + +#: The kinds of row a price list has. +OPPORTUNITY = "opportunity" +ANY_DAY = "any day" +FAILURE = "failure" + +#: Where a price came from. +OVERRIDE = "override" +ON_OPPORTUNITY = "opportunity" +OPPORTUNITY_COST = "opportunity_cost" +PLANNED_COST = "planned_cost" +UNPLANNED_COST = "unplanned_cost" +COLLECTION = "collection" +NOT_USED = "not used" + +#: The keyword arguments that only a site on real dates takes. +_SITE_ONLY = ("plan", "now", "readings", "unit", "horizon", "discount") + + +# ---------------------------------------------------------------- results + + +@dataclass(frozen=True) +class OpportunityPrice(_ResultMapping): + """One row of [`OpportunityPrices`][repyability.OpportunityPrices]: + the price a part pays at an opportunity, on any other day or at a + failure, and where it came from. + + Attributes + ---------- + name : str + The opportunity's name, ``"any day"`` or ``"failure"``. + kind : str + ``"opportunity"``, ``"any day"`` or ``"failure"``. + price : float + The price; ``nan`` where it is not used. + used : bool + Whether the policy may replace the part there. + source : str + Where the price came from: ``"override"`` (the part's + ``opportunity_costs``), ``"opportunity_cost"``, + ``"planned_cost"`` (an opportunity priced as any other day, as the + part has no ``opportunity_cost``), ``"unplanned_cost"``, + ``"opportunity"`` or ``"collection"`` (a deprecated price on the + opportunity or on the collection), ``"not used"``; from + ``NonRepairable.opportunity_prices``, the formula's terms. + reason : str + The same in words, and why a row is not used ("the 6 h job + doesn't fit in the 4 h weekly stop"). + """ + + name: str + kind: str + price: float + used: bool + source: str + reason: str + + +@dataclass(frozen=True) +class OpportunityPrices(_ResultMapping): + """A part's prices at each opportunity, on any other day and at a + failure, one row each: what a policy priced the opportunities at (its + ``prices``), or what + [`NonRepairable.opportunity_prices`][repyability.NonRepairable.opportunity_prices] + works out from a replacement's cost and downtime. + + Attributes + ---------- + rows : tuple of OpportunityPrice + The opportunities in order, then ``"any day"`` and ``"failure"``. + planned_cost : float or None + From ``opportunity_prices``: the part's price on any day. None + on a policy's prices. + unplanned_cost : float or None + From ``opportunity_prices``: the part's price at a failure. + opportunity_cost : float or None + From ``opportunity_prices``: the part's price at an opportunity + the job fits in. + job_duration : float or str or None + From ``opportunity_prices``: how long the replacement takes. + """ + + rows: Tuple[OpportunityPrice, ...] = () + planned_cost: Optional[float] = None + unplanned_cost: Optional[float] = None + opportunity_cost: Optional[float] = None + job_duration: Any = None + + def __repr__(self) -> str: + return ( + "OpportunityPrices(" + + "; ".join(f"{r.name}: {_money_or_not(r)}" for r in self.rows) + + ")" + ) + + def row(self, name: str) -> OpportunityPrice: + """The row named ``name``. + + Parameters + ---------- + name : str + An opportunity's name, ``"any day"`` or ``"failure"``. + + Returns + ------- + OpportunityPrice + """ + for r in self.rows: + if r.name == name: + return r + raise KeyError( + f"No price for {name!r}; the rows are " + f"{[r.name for r in self.rows]}." + ) + + def price(self, name: str) -> float: + """The price at ``name``, ``nan`` where it is not used. + + Parameters + ---------- + name : str + An opportunity's name, ``"any day"`` or ``"failure"``. + + Returns + ------- + float + """ + return self.row(name).price + + @property + def unused(self) -> Tuple[str, ...]: + """The opportunities not used, by name (the rows say why).""" + return tuple( + r.name for r in self.rows if r.kind == OPPORTUNITY and not r.used + ) + + def describe(self) -> str: + """The prices, a line each, with where each came from.""" + return "\n".join( + f"{r.name}: {_money_or_not(r)} ({r.reason})" for r in self.rows + ) + + def apply(self, part): + """Give ``part`` these prices (from + [`NonRepairable.opportunity_prices`][repyability.NonRepairable.opportunity_prices]): + its ``planned_cost`` (any day), ``unplanned_cost`` (a failure), + ``opportunity_cost`` and ``job_duration``, its per-opportunity + overrides cleared, so a policy prices every opportunity as these + rows do. The downtime cost stays here: it is the system's, not + the part's. + + Parameters + ---------- + part : NonRepairable + The part, changed in place (as + ``set_costs_planned_and_unplanned`` changes it). + + Returns + ------- + NonRepairable + ``part``. + """ + if self.planned_cost is None or self.unplanned_cost is None: + raise ValueError( + "These are a policy's prices, already the part's: only " + "NonRepairable.opportunity_prices(...) gives prices to " + "apply." + ) + part.set_costs_planned_and_unplanned( + self.planned_cost, self.unplanned_cost + ) + part._set_opportunity_prices( + opportunity_cost=self.opportunity_cost, + job_duration=self.job_duration, + opportunity_costs=None, + ) + return part + + +def _money_or_not(row: OpportunityPrice) -> str: + if not row.used or not math.isfinite(row.price): + return "not used" + return _shutdowns._money(row.price) + + +def with_prices(policy, prices: OpportunityPrices): + """``policy`` (a ``CalendarPolicy``, ``ShutdownPolicy`` or + ``RuleCost``) carrying how the opportunities were priced.""" + object.__setattr__(policy, "_prices", prices) + return policy + + +# --------------------------------------------------------- the collection + + +class Opportunities: + """A site's opportunities to replace parts (or a calendar's, in model + time), as one record: each kind of stop or shut, whether a planned + replacement may be made on any other day, and the site's time zone. + + It carries no prices: each part brings its own (`NonRepairable`'s + ``planned_cost`` on any day, ``unplanned_cost`` at a failure, + ``opportunity_cost`` at an opportunity, ``opportunity_costs`` for one + opportunity, and ``job_duration``), so one record serves every part + ([`NonRepairable.optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy]). + It is in model time or on real dates, by what its opportunities are; + a mix is refused. It replaces ``Calendar`` (model time, 0.14) and + ``Shutdowns`` (real dates, 0.19), both deprecated. + + Parameters + ---------- + opportunities : list of Opportunity + The kinds of opportunity, each with its own name. + any_day : bool, optional + Whether a planned replacement may be made on any other day, at the + part's ``planned_cost``; by default True. False: only at the + opportunities (and at failures). (A price here is deprecated: it + is taken as every part's price on any other day.) + 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 + -------- + >>> from repyability import Opportunities, Opportunity + >>> from repyability.schedule import Recurrence + >>> site = Opportunities( + ... [ + ... Opportunity("weekly stop", Recurrence.weekly("Sat"), + ... duration="8h"), + ... Opportunity("turnaround", dates=["2027-03-03"], + ... duration="21d", takes_down=["Line 2"]), + ... ], + ... time_zone="Australia/Brisbane", + ... ) + >>> site.model_time, site.names + (False, ('weekly stop', 'turnaround')) + >>> plant = Opportunities([Opportunity("stop", period=28.0)], + ... any_day=False) + >>> plant.model_time + True + """ + + 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)): + opportunities = [opportunities] + listed: List[Opportunity] = [] + for o in opportunities: + if isinstance(o, _shutdowns.Shutdown): + o = Opportunity._from_shutdown(o) + if not isinstance(o, Opportunity): + raise TypeError( + "Opportunities takes a list of Opportunity, one per " + f"kind of stop or shut; got {o!r}." + ) + listed.append(o) + names = [o.name for o in listed] + repeated = sorted({n for n in names if names.count(n) > 1}) + if repeated: + raise ValueError( + f"Opportunity names must differ; {repeated} repeat." + ) + model = [o.name for o in listed if o.model_time] + dated = [o.name for o in listed if not o.model_time] + if model and dated: + raise ValueError( + "Opportunities are all in model time (a period, or dates " + "as numbers) or all on real dates (a rule, dates, or " + f"every=); {_listed(model)} " + f"{'is' if len(model) == 1 else 'are'} in model time and " + f"{_listed(dated)} on real dates. Keep one collection per " + "clock." + ) + if model and time_zone is not None: + raise ValueError( + "time_zone is for opportunities on real dates; these are in " + "model time." + ) + zone(time_zone) + self._any_day_price: Optional[float] = None + if any_day is None: + any_day = False + if checks.is_number(any_day): + price_on_part("Opportunities(any_day=)") + self._any_day_price = _price(any_day, "any_day") + any_day = True + if not isinstance(any_day, bool): + raise TypeError( + "any_day must be True (a planned replacement on any other " + "day, at the part's planned_cost) or False; got " + f"{any_day!r}." + ) + 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 + #: The clock: "model", "dates", or None (empty, and not said). + self._clock: Optional[str] = ( + "model" + if model + else "dates" if dated or time_zone is not None else None + ) + + @classmethod + def _legacy( + cls, opportunities, *, any_day, any_day_price, failure, clock, zone + ) -> "Opportunities": + made = cls(opportunities, any_day=any_day, time_zone=zone) + made._any_day_price = any_day_price + made._failure_price = failure + made._clock = clock + return made + + # -- reading it ---------------------------------------------------- + + @property + def model_time(self) -> Optional[bool]: + """True in model time, False on real dates; None for an empty + collection with no time zone, which a policy takes as model time + unless it is given a site's arguments (``now=``, ``plan=``, ...).""" + return None if self._clock is None else self._clock == "model" + + @property + def names(self) -> Tuple[str, ...]: + """The opportunities' names, in order.""" + return tuple(o.name for o in self.opportunities) + + def __getitem__(self, name: str) -> Opportunity: + for o in self.opportunities: + if o.name == name: + return o + raise KeyError( + f"No opportunity named {name!r}; these are {list(self.names)}." + ) + + def __iter__(self): + return iter(self.opportunities) + + def __len__(self) -> int: + return len(self.opportunities) + + def __repr__(self) -> str: + return ( + f"Opportunities({list(self.opportunities)!r}, any_day=" + f"{self.any_day!r}, time_zone={self.time_zone!r})" + ) + + def __eq__(self, other) -> bool: + return ( + isinstance(other, Opportunities) + and self.to_dict() == other.to_dict() + ) + + def __hash__(self) -> int: + return hash(repr(self.to_dict())) + + def describe(self) -> str: + """The collection in a sentence.""" + other = ( + "a planned replacement on any other day" + if self.any_day + else "no planned replacement on other days" + ) + if not self.opportunities: + return f"No opportunities; {other}." + n = len(self.opportunities) + listed = _shutdowns._listed([o.describe() for o in self.opportunities]) + return ( + f"{n} {'opportunity' if n == 1 else 'opportunities'}: {listed}; " + f"{other}." + ) + + # -- on real dates ------------------------------------------------- + + def _site(self, prices: Optional[Dict[str, float]] = None, any_day=None): + """The opportunities on real dates as the site solvers take them: + each a shut at its price in ``prices`` (0 where none is given, for + what needs no price).""" + if self._clock == "model": + raise ValueError( + "These opportunities are in model time; dates, a diagram's " + "outages and a site's route are for opportunities on real " + "dates." + ) + prices = prices or {} + return _shutdowns.Shutdowns( + [o._shutdown(prices.get(o.name, 0.0)) for o in self.opportunities], + any_day=any_day, + time_zone=self.time_zone, + ) + + def dates(self, start, end, *, plan=None, readings=None): + """Every opportunity from ``start`` to ``end`` (both included), by + kind, as ``Shutdowns.dates`` gave them (real dates only). + + Parameters + ---------- + start : date or str + The first day. + end : date or str + The last day (included). + plan : DutyPlan, optional + How the equipment runs, for opportunities by use. + readings : dict, optional + The meters at ``start``, for opportunities by use. + + Returns + ------- + dict + Each kind's name and its dates, in order. + """ + return self._site().dates(start, end, plan=plan, readings=readings) + + def on_diagram(self, start, end, **kwargs) -> Dict[str, dict]: + """The opportunities as a diagram's outages (real dates only): the + spec [`RepairableRBD(shutdowns=...)`][repyability.RepairableRBD] + takes, one per kind, each lasting its ``duration``. The keyword + arguments (``unit``, ``plan``, ``readings``, ``cost``, ``scope``, + ``idle_ageing``) are as for ``Shutdowns.on_diagram``. + + Parameters + ---------- + start : date or str + The diagram's time 0 is ``start``'s midnight. + end : date or str + The last day taken (included). + **kwargs + As above. + + Returns + ------- + dict + ``{name: {"times": [...], "duration": ...}}``. + """ + return self._site().on_diagram(start, end, **kwargs) + + def route(self, part, *, where=None, **kwargs): + """How ``part``'s policy at this site will be worked out, before + working it out (real dates only), as + ``optimal_opportunity_policy`` would take it: the keyword + arguments are its site arguments (``plan``, ``method``, + ``horizon``, ``discount``, ``now``, ``readings``, ``unit``, + ``failure_timing``, ``dated_until``). + + Parameters + ---------- + part : NonRepairable + The part, with its prices. + where : str, optional + As for ``optimal_opportunity_policy``. + **kwargs + As above. + + Returns + ------- + ShutdownRoute + """ + site, _ = resolve(part, self, where=where, on_dates=True) + return site.route(part, **kwargs) + + # -- saving -------------------------------------------------------- + + def to_dict(self) -> dict: + """The collection as plain data, ready for ``json.dumps`` + (``"kind"`` ``"opportunities"``, with a ``"version"``).""" + out: Dict[str, Any] = { + "kind": "opportunities", + "version": 1, + "opportunities": [o.to_dict() for o in self.opportunities], + "any_day": self.any_day, + "time_zone": self.time_zone, + } + if self._any_day_price is not None: + out["any_day_price"] = self._any_day_price + if self._failure_price is not None: + 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 + def from_dict(cls, data: dict) -> "Opportunities": + """A collection from its ``to_dict()``, or from a saved + ``Shutdowns`` (``"kind"`` ``"shutdowns"``, its prices kept as the + deprecated prices on the opportunities). + + Parameters + ---------- + data : dict + What ``to_dict()`` gave. + + Returns + ------- + Opportunities + """ + if isinstance(data, dict) and data.get("kind") == "shutdowns": + return as_opportunities(_shutdowns.Shutdowns.from_dict(data)) + if not isinstance(data, dict) or data.get("kind") != "opportunities": + raise ValueError( + "Not saved Opportunities: its kind must be 'opportunities'; " + f"got {data!r:.80}." + ) + if data.get("version", 1) > 1: + raise ValueError( + "These Opportunities were saved by a newer RePyability " + f"(version {data['version']}): upgrade to read them." + ) + 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: + return _shutdowns._listed([repr(n) for n in names]) + + +# ------------------------------------------------- the deprecated forms + + +class Calendar(_calendar.Calendar): + """**Deprecated** (0.14's form; removed in 0.21): use + [`Opportunities`][repyability.Opportunities], with the prices on the + part. ``Calendar(opportunities, failure=, anytime=)`` still works and + gives the same numbers: each opportunity's own price (its deprecated + ``cost``) is the part's price there, ``failure`` the price at a + failure (by default the part's ``unplanned_cost``) and ``anytime`` + the price on any day (by default the part's ``planned_cost``; None, + no replacement on any day: ``Opportunities(any_day=False)``). + + Parameters + ---------- + opportunities : list of Opportunity + In model time, each with a price. + failure : float or "part", optional + The price at a failure. + anytime : float, "part" or None, optional + The price on any day. + """ + + def __init__(self, opportunities=(), failure=PART, anytime=PART): + replaced( + "Calendar", + "Opportunities (in model time, with the prices on the part: " + "planned_cost, unplanned_cost, opportunity_cost)", + "an opportunity applies to every part, so its price comes with " + "the part", + ) + super().__init__(opportunities, failure=failure, anytime=anytime) + + +class Shutdown(_shutdowns.Shutdown): + """**Deprecated** (0.19's form; removed in 0.21): use + [`Opportunity`][repyability.Opportunity] (on real dates, with the same + ``rule``, ``dates``, ``then_every``, ``every``, ``also_every``, + ``duration`` and ``at``), with the price on the part. + ``replace_cost`` is taken as the part's price at this shut. + + Parameters + ---------- + name : str + The shut's name. + rule : Recurrence, optional + When it happens. + dates : list of date or str, optional + Its fixed dates. + then_every : str, optional + The gap after the last date. + every : str, float or Usage, optional + A plain period or a use. + also_every : str, optional + A calendar limit on a use. + replace_cost : float + The price of replacing a part at this shut. + duration : str or float, optional + How long it lasts. + at : str, optional + The clock time it starts. + """ + + def __init__( + self, + name, + rule=None, + *, + dates=None, + then_every=None, + every=None, + also_every=None, + replace_cost, + duration=None, + at=None, + ): + replaced( + "Shutdown", + "Opportunity (on real dates, with the price on the part: " + "opportunity_cost, or opportunity_costs={name: price})", + "an opportunity applies to every part, so its price comes with " + "the part", + ) + super().__init__( + name, + rule, + dates=dates, + then_every=then_every, + every=every, + also_every=also_every, + replace_cost=replace_cost, + duration=duration, + at=at, + ) + + +class Shutdowns(_shutdowns.Shutdowns): + """**Deprecated** (0.19's form; removed in 0.21): use + [`Opportunities`][repyability.Opportunities] (``any_day=True`` for a + planned replacement on any other day at the part's ``planned_cost``), + with the prices on the part. ``any_day=`` is still taken as the + price on any other day, and each shut's ``replace_cost`` as the price + at it. + + Parameters + ---------- + shutdowns : list of Shutdown + The kinds of shut. + any_day : float or None, optional + The price on any other day; None: none allowed. + time_zone : str, optional + The site's IANA zone. + """ + + def __init__(self, shutdowns=(), *, any_day=None, time_zone=None): + replaced( + "Shutdowns", + "Opportunities (with the prices on the part: planned_cost on " + "any day, opportunity_cost at the opportunities)", + "an opportunity applies to every part, so its price comes with " + "the part", + ) + super().__init__(shutdowns, any_day=any_day, time_zone=time_zone) + + +# -------------------------------------------- the part's prices laid on + + +def as_opportunities(value) -> Opportunities: + """``value`` as ``Opportunities``: itself, a list of ``Opportunity``, + or a deprecated ``Calendar`` or ``Shutdowns`` (its prices kept as the + deprecated prices on its opportunities and itself).""" + if isinstance(value, Opportunities): + return value + if isinstance(value, _calendar.Calendar): + anytime = value.anytime + return Opportunities._legacy( + list(value.opportunities), + any_day=anytime is not None, + any_day_price=( + None + if anytime is None or _calendar._is_part(anytime) + else float(anytime) + ), + failure=( + None + if _calendar._is_part(value.failure) + else float(value.failure) + ), + clock="model", + zone=None, + ) + if isinstance(value, _shutdowns.Shutdowns): + return Opportunities._legacy( + [Opportunity._from_shutdown(s) for s in value.shutdowns], + any_day=value.any_day is not None, + any_day_price=value.any_day, + failure=None, + clock="dates", + zone=value.time_zone, + ) + if isinstance(value, Opportunity): + return Opportunities([value]) + if isinstance(value, (list, tuple)) and all( + isinstance(o, Opportunity) for o in value + ): + return Opportunities(value) + raise TypeError( + "Give the opportunities as Opportunities([Opportunity(...), ...]); " + f"got {value!r:.80}." + ) + + +def _overrides(part, collection: Opportunities) -> Dict[str, float]: + """The part's per-opportunity prices by name, each key checked + against the collection: a name or an ``Opportunity`` not in it is + refused, with the names it has.""" + given = getattr(part, "opportunity_costs", None) or {} + names = collection.names + have = ( + f"these opportunities are {', '.join(map(repr, names))}" + if names + else "there are no opportunities" + ) + out: Dict[str, float] = {} + for key, price in given.items(): + if isinstance(key, Opportunity): + if key not in collection.opportunities: + raise ValueError( + f"The part's opportunity_costs prices the opportunity " + f"{key.name!r}, which is not one of these: {have}." + ) + out[key.name] = float(price) + elif key in names: + out[key] = float(price) + else: + raise ValueError( + f"The part's opportunity_costs names {key!r}, which is not " + f"an opportunity here: {have}." + ) + return out + + +def _job_length(job, clock: str) -> Optional[float]: + """A part's ``job_duration`` in the opportunities' terms: hours on real + dates (text or a number of hours), the life's unit in model time (a + number).""" + if job is None: + return None + if clock == "model": + if not checks.is_number(job): + raise ValueError( + f"The part's job_duration {job!r} is text, which is for " + "opportunities on real dates; in model time give it as a " + "number in the life's unit." + ) + return float(job) + return _shutdowns._duration(job) + + +def _length_words(value: float, clock: str) -> str: + if clock == "model": + return f"{value:g}" + return f"{_shutdowns._number(value)} h" + + +def _fit(o: Opportunity, job: Optional[float], clock: str) -> Optional[str]: + """Why a job of ``job`` does not fit in ``o``; None where it fits + (or either length is not said).""" + if job is None or o.duration is None or o.duration >= job: + return None + words = ( + f"the {_length_words(job, clock)} job doesn't fit in the " + f"{_length_words(o.duration, clock)} {o.name}" + ) + if clock == "model": + words += " (in the life's unit)" + return words + + +def resolve(part, value, *, where=None, on_dates=False): + """The part's prices laid on the opportunities: the solvers' own + record (a ``Calendar`` in model time, a ``Shutdowns`` site on real + dates), each opportunity used at the part's price, and the prices + (``OpportunityPrices``) with where each came from. + + An opportunity's price is the part's override for it + (``opportunity_costs``), else a deprecated price on the opportunity, + else the part's ``opportunity_cost``, else its ``planned_cost`` (as + any other day). One that does not take ``where`` down, or that the + part's job does not fit in, is left out, and listed as not used. + ``on_dates`` says an empty collection that names no clock is on real + dates (the policy was given a site's arguments). + """ + collection = as_opportunities(value) + clock = collection._clock or ("dates" if on_dates else "model") + if where is not None and not isinstance(where, str): + raise TypeError(f"where must be a label (text); got {where!r}.") + overrides = _overrides(part, collection) + job = _job_length(getattr(part, "job_duration", None), clock) + general = getattr(part, "opportunity_cost", None) + planned = getattr(part, "cp", None) + rows: List[OpportunityPrice] = [] + kept: List[Tuple[Opportunity, float]] = [] + for o in collection.opportunities: + if ( + where is not None + and o.takes_down is not None + and (where not in o.takes_down) + ): + rows.append( + OpportunityPrice( + o.name, + OPPORTUNITY, + math.nan, + False, + NOT_USED, + f"it doesn't take {where!r} down (it takes down " + f"{', '.join(o.takes_down)})", + ) + ) + continue + why_not = _fit(o, job, clock) + if why_not is not None: + rows.append( + OpportunityPrice( + o.name, OPPORTUNITY, math.nan, False, NOT_USED, why_not + ) + ) + continue + if o.name in overrides: + price, source = overrides[o.name], OVERRIDE + reason = f"the part's opportunity_costs[{o.name!r}]" + elif o.cost is not None: + price, source = o.cost, ON_OPPORTUNITY + reason = "the price on the opportunity (deprecated)" + elif general is not None: + price, source = float(general), OPPORTUNITY_COST + reason = "the part's opportunity_cost" + elif planned is not None: + price, source = float(planned), PLANNED_COST + reason = ( + "the part's planned_cost: it has no opportunity_cost, so " + "an opportunity is priced as any other day" + ) + else: + raise ValueError( + f"Opportunity {o.name!r} has no price for this part: give " + "the part an opportunity_cost (or a planned_cost, which " + "prices an opportunity as any other day), or " + f"opportunity_costs={{{o.name!r}: price}}." + ) + rows.append( + OpportunityPrice(o.name, OPPORTUNITY, price, True, source, reason) + ) + kept.append((o, price)) + any_day: Optional[float] + if not collection.any_day: + any_day = None + rows.append( + OpportunityPrice( + ANY_DAY, + ANY_DAY, + math.nan, + False, + NOT_USED, + "not allowed: any_day=False", + ) + ) + elif collection._any_day_price is not None: + any_day = collection._any_day_price + rows.append( + OpportunityPrice( + ANY_DAY, + ANY_DAY, + any_day, + True, + COLLECTION, + "the price on any day given with the opportunities " + "(deprecated)", + ) + ) + elif planned is not None: + any_day = float(planned) + rows.append( + OpportunityPrice( + ANY_DAY, + ANY_DAY, + any_day, + True, + PLANNED_COST, + "the part's planned_cost", + ) + ) + else: + any_day = None + rows.append( + OpportunityPrice( + ANY_DAY, + ANY_DAY, + math.nan, + False, + NOT_USED, + "the part has no planned_cost", + ) + ) + if collection._failure_price is not None: + rows.append( + OpportunityPrice( + FAILURE, + FAILURE, + collection._failure_price, + True, + COLLECTION, + "the failure price given with the opportunities " + "(deprecated)", + ) + ) + elif getattr(part, "cu", None) is not None: + rows.append( + OpportunityPrice( + FAILURE, + FAILURE, + float(part.cu), + True, + UNPLANNED_COST, + "the part's unplanned_cost", + ) + ) + else: + rows.append( + OpportunityPrice( + FAILURE, + FAILURE, + math.nan, + False, + NOT_USED, + "the part has no unplanned_cost", + ) + ) + prices = OpportunityPrices(rows=tuple(rows)) + if clock == "model": + if collection._any_day_price is not None: + anytime: Any = collection._any_day_price + else: + anytime = PART if collection.any_day else None + failure: Any = ( + PART + if collection._failure_price is None + else collection._failure_price + ) + calendar = _calendar.Calendar( + [o._replaced(cost=price) for o, price in kept], + failure=failure, + anytime=anytime, + ) + return calendar, prices + site = _shutdowns.Shutdowns( + [o._shutdown(price) for o, price in kept], + any_day=any_day, + time_zone=collection.time_zone, + ) + return site, prices + + +def site_given(**given) -> bool: + """Whether a policy call gave a site's arguments (so an empty + collection naming no clock is on real dates).""" + age = given.pop("age", 0.0) + timing = given.pop("failure_timing", "half_step") + return ( + any(v is not None for v in given.values()) + or not (checks.is_number(age) and float(age) == 0.0) + or timing != "half_step" + ) + + +# -------------------------------------------------- the part's prices + + +def check_part_prices(opportunity_cost, job_duration, opportunity_costs): + """A part's opportunity prices, checked: ``opportunity_cost`` a price + or None; ``job_duration`` a number more than 0, text such as + ``"6h"``, or None (kept as given); ``opportunity_costs`` a mapping + from opportunity names (text) or ``Opportunity`` objects to prices + (kept as a dict; checked against the opportunities when a policy + runs).""" + if opportunity_cost is not None: + opportunity_cost = _price(opportunity_cost, "opportunity_cost") + if job_duration is not None: + if checks.is_number(job_duration): + if not 0.0 < float(job_duration) < math.inf: + raise ValueError( + "job_duration must be more than 0; got " + f"{job_duration!r}." + ) + job_duration = float(job_duration) + elif isinstance(job_duration, str): + _shutdowns._period_hours(job_duration, "job_duration") + else: + raise TypeError( + "job_duration must be a number (the life's unit in model " + "time, hours on real dates) or text such as '6h'; got " + f"{job_duration!r}." + ) + costs: Dict[Any, float] = {} + if opportunity_costs is not None: + if not isinstance(opportunity_costs, Mapping): + raise TypeError( + "opportunity_costs must be a dict of opportunity (or its " + f"name) to price; got {opportunity_costs!r}." + ) + for key, price in opportunity_costs.items(): + if not ( + isinstance(key, Opportunity) or (isinstance(key, str) and key) + ): + raise TypeError( + "opportunity_costs' keys must be opportunities' names " + f"or the Opportunity objects; got {key!r}." + ) + label = key.name if isinstance(key, Opportunity) else key + costs[key] = _price(price, f"opportunity_costs[{label!r}]") + return opportunity_cost, job_duration, costs + + +def opportunity_prices( + opportunities, + *, + replacement_cost, + replacement_duration, + failure_cost, + failure_duration, + downtime_cost, +) -> OpportunityPrices: + """See ``NonRepairable.opportunity_prices``.""" + collection = as_opportunities(opportunities) + text = isinstance(replacement_duration, str) or isinstance( + failure_duration, str + ) + clock = collection._clock or ("dates" if text else "model") + replacement_cost = _price(replacement_cost, "replacement_cost") + failure_cost = _price(failure_cost, "failure_cost") + downtime_cost = _price(downtime_cost, "downtime_cost") + lengths: Dict[str, float] = {} + for name, value in ( + ("replacement_duration", replacement_duration), + ("failure_duration", failure_duration), + ): + if isinstance(value, str): + if clock == "model": + raise ValueError( + f"{name} {value!r} is text, which is for opportunities " + "on real dates; in model time give it as a number in " + "the life's unit." + ) + lengths[name] = float(_shutdowns._period_hours(value, name)[0]) + elif checks.is_number(value) and 0.0 <= float(value) < math.inf: + lengths[name] = float(value) + else: + raise ValueError( + f"{name} must be a number, at least 0, or text such as " + f"'6h'; got {value!r}." + ) + job = lengths["replacement_duration"] + unit = "h" if clock == "dates" else "(the life's unit)" + rows: List[OpportunityPrice] = [] + for o in collection.opportunities: + why_not = _fit(o, job if job > 0.0 else None, clock) + if why_not is None: + rows.append( + OpportunityPrice( + o.name, + OPPORTUNITY, + replacement_cost, + True, + "replacement_cost", + "replacement_cost alone: the plant is down anyway", + ) + ) + else: + rows.append( + OpportunityPrice( + o.name, OPPORTUNITY, math.nan, False, NOT_USED, why_not + ) + ) + planned = replacement_cost + downtime_cost * job + rows.append( + OpportunityPrice( + ANY_DAY, + ANY_DAY, + planned, + collection.any_day, + "replacement_cost + downtime_cost x replacement_duration", + f"{replacement_cost:g} + {downtime_cost:g} x {job:g} {unit}" + + ("" if collection.any_day else "; not allowed: any_day=False"), + ) + ) + unplanned = failure_cost + downtime_cost * lengths["failure_duration"] + rows.append( + OpportunityPrice( + FAILURE, + FAILURE, + unplanned, + True, + "failure_cost + downtime_cost x failure_duration", + f"{failure_cost:g} + {downtime_cost:g} x " + f"{lengths['failure_duration']:g} {unit}", + ) + ) + return OpportunityPrices( + rows=tuple(rows), + planned_cost=planned, + unplanned_cost=unplanned, + opportunity_cost=replacement_cost, + job_duration=None if job == 0.0 else replacement_duration, + ) diff --git a/repyability/maintenance/_options.py b/repyability/maintenance/_options.py index a7f543b2..1a18f576 100644 --- a/repyability/maintenance/_options.py +++ b/repyability/maintenance/_options.py @@ -709,6 +709,61 @@ class AgeReplacementValue(_ResultMapping): cycle_cost: float +def _cycle(part, age: float, rate: float): + """A new part's first cycle under replacement at ``age`` (``inf``: + run to failure), discounted at ``rate``: the chance of reaching the + planned replacement, discounted to then (``kept``), of failing before + it, discounted (``failed``: with ``M`` the discounted mean time up, + ``1 - kept - rate * M``, by parts), and ``M`` itself.""" + if math.isinf(age): + kept = 0.0 + length = _discounted_length(part, 0.0, _reach(part, rate), rate) + else: + kept = math.exp(-rate * age) * float( + np.ravel(part.reliability_function(age))[0] + ) + length = _discounted_length(part, 0.0, age, rate) + failed = max(1.0 - kept - rate * length, 0.0) + return kept, failed, length + + +def _cycle_value(part, age: float, rate: float, cp: float, cu: float): + """A new part's first cycle under replacement at ``age``: its present + cost (``cp`` at ``age``, ``cu`` at a failure first, each discounted to + when it falls) and its discounted length ``M(age)``.""" + kept, failed, length = _cycle(part, age, rate) + return cu * failed + cp * kept, length + + +def cycle_eac( + part, + age: float, + rate: float, + *, + failure_cost: float, + planned_cost: float = 0.0, + downtime: float = 0.0, + repair: float = 0.0, + planned: float = 0.0, +) -> float: + """The equivalent annual cost of replacing ``part`` at ``age`` + (``inf``: running it to failure) at the continuous discount rate + ``rate`` (0: the long-run cost rate), over its renewal cycle (Fox, + 1966): the one definition, which a part alone and a diagram's + component both take. + + Every category of a unit's own: ``failure_cost`` at each failure, + ``planned_cost`` at each planned replacement, and its own + ``downtime`` per unit of time over the discounted repair time + ``repair`` and the discounted time of the planned work ``planned``, + which lengthen the cycle (0 for work in no time).""" + kept, failed, length = _cycle(part, age, rate) + cycle = failed * (failure_cost + downtime * repair) + kept * ( + planned_cost + downtime * planned + ) + return cycle / (length + failed * repair + kept * planned) + + def age_replacement_value( part, age, *, discount_rate: float = 0.0 ) -> AgeReplacementValue: @@ -720,15 +775,7 @@ def age_replacement_value( ) age = float(age) rate = _number(discount_rate, "discount_rate") - # The chance of reaching the planned replacement, discounted to then - # (kept), and of failing before it, discounted (failed): with M the - # discounted mean time up, 1 - kept - rate * M, by parts. - kept = math.exp(-rate * age) * float( - np.ravel(part.reliability_function(age))[0] - ) - length = _discounted_length(part, 0.0, age, rate) - failed = max(1.0 - kept - rate * length, 0.0) - cycle = part.cu * failed + part.cp * kept + cycle, length = _cycle_value(part, age, rate, part.cp, part.cu) if rate == 0.0: # Renewal reward: the cost of a cycle over its mean length. return AgeReplacementValue(age, rate, math.inf, cycle / length, cycle) @@ -736,3 +783,165 @@ def age_replacement_value( # discount, is 1 - rate * length. npv = cycle / (rate * length) return AgeReplacementValue(age, rate, npv, rate * npv, cycle) + + +# -- the discounted optimum (Fox, 1966) -------------------------------------- + +#: The discounted search's ages: a grid this many points a decade, over +#: ``DECADES`` decades below the oldest age that matters. +POINTS_A_DECADE = 500 +DECADES = 6 +#: Where the discounted search stops: the age by which a unit has all but +#: surely failed, or by which a cost is discounted to ``exp(-REACH)``. +REACH = 40.0 +FAILED_BY = 1e-12 + + +def discount_rate(value, name: str = "discount_rate") -> float: + """A continuous discount rate per unit of time, at least 0.""" + return _number(value, name) + + +def _discounted_rates(cp, cu, ages, R, rate): + """The equivalent annual cost of age replacement at each of ``ages`` + (increasing, from 0), ``R`` the survival there: the discounted cycle + length and failures by the cumulative trapezoidal rule. At rate 0 it + is ``_cost_rates`` (the long-run cost rate); ``inf`` at age 0.""" + disc = np.exp(-rate * ages) + kept = disc * R + length = np.concatenate( + [[0.0], np.cumsum(np.diff(ages) * (kept[1:] + kept[:-1]) / 2.0)] + ) + failed = (1.0 - R[0]) + np.concatenate( + [[0.0], np.cumsum(-np.diff(R) * (disc[1:] + disc[:-1]) / 2.0)] + ) + with np.errstate(divide="ignore", invalid="ignore"): + rates = (cu * failed + cp * kept) / length + rates[0] = np.inf + return rates + + +def _scale(part) -> float: + from repyability.rbd._model_utils import MODEL_ERRORS, model_mean + + try: + mean = float(model_mean(part.reliability)) + except MODEL_ERRORS: + mean = math.nan + if 0.0 < mean < math.inf: + return mean + return 1.0 + + +def _reach(part, rate: float) -> float: + """The oldest age that matters to a discounted cost: where the part + has all but surely failed, or where a cost is discounted to + ``exp(-REACH)``, whichever comes first.""" + sf = part.reliability_function + upper = _scale(part) + for _ in range(400): + if rate * upper >= REACH: + return REACH / rate + if float(np.ravel(sf(upper))[0]) <= FAILED_BY: + return upper + upper *= 2.0 + return upper + + +def discounted_run_to_failure(part, rate: float, cu: float) -> float: + """The equivalent annual cost of running to failure, discounted at + ``rate`` (more than 0): ``cu`` at each failure, forever. With ``M`` + the integral of ``exp(-r t) R(t)`` to infinity, ``cu (1 - r M) / M`` + (the renewal sum ``cu L / (1 - L)`` with ``L = 1 - r M``, times + ``r``).""" + upper = _reach(part, rate) + if part.model_parameterization == "standby": + ages = np.linspace(0.0, upper, 20001) + R = np.clip( + np.ravel(np.asarray(part.reliability.sf(ages), dtype=float)), + 0.0, + 1.0, + ) + kept = np.exp(-rate * ages) * R + length = float(np.sum(np.diff(ages) * (kept[1:] + kept[:-1]) / 2.0)) + return cu * max(1.0 - rate * length, 0.0) / length + return cycle_eac(part, math.inf, rate, failure_cost=cu) + + +def discounted_optimum(part, rate: float, cp: float, cu: float): + """The replacement age that minimises the equivalent annual cost of + age replacement at the continuous discount rate ``rate`` (more than + 0), and that cost: ``(inf, run-to-failure cost)`` where no age beats + running to failure (by more than one part in a million). + + The cost is scanned on a grid of ages, the discounted cycle length + and failures by the trapezoidal rule (``POINTS_A_DECADE`` a decade + over ``DECADES`` decades below the oldest age that matters, with the + model's knots), and the cheapest refined between its neighbours with + a bounded search on the cost worked out by quadrature. A + non-parametric estimate is scanned on its own grid (to its last time + point) and not refined, as the undiscounted search is. + """ + from scipy.optimize import minimize_scalar + + from repyability.rbd._mean_lifetime import model_knots + + kind = part.model_parameterization + sf = part.reliability_function + if kind not in ("parametric", "degradation", "standby"): + knots = part._knots + ages = np.union1d(np.linspace(0.0, knots[-1], 10001), knots) + R = np.ravel(np.asarray(sf(ages), dtype=float)) + rates = _discounted_rates(cp, cu, ages, R, rate) + i = int(np.nanargmin(rates)) + return float(ages[i]), float(rates[i]) + upper = _reach(part, rate) + points = POINTS_A_DECADE * DECADES + 1 + ages = upper * np.logspace(-DECADES, 0.0, points) + if kind != "standby": + knots = model_knots(part.reliability) + ages = np.union1d(ages, knots[(knots > 0.0) & (knots < upper)]) + offset = float(getattr(part.reliability, "gamma", 0) or 0) + if getattr(part.reliability, "offset", False) and 0.0 < offset < upper: + ages = np.union1d(ages, [offset]) + ages = np.concatenate([[0.0], ages]) + with np.errstate(all="ignore"): + if kind == "standby": + R = np.ravel(np.asarray(part.reliability.sf(ages), dtype=float)) + else: + R = np.ravel(np.asarray(sf(ages), dtype=float)) + R = np.clip(np.nan_to_num(R, nan=0.0), 0.0, 1.0) + rates = _discounted_rates(cp, cu, ages, R, rate) + i = int(np.nanargmin(rates)) + + def eac(t: float) -> float: + if kind == "standby": + grid = np.linspace(0.0, t, 4001) + S = np.clip( + np.ravel(np.asarray(part.reliability.sf(grid), dtype=float)), + 0.0, + 1.0, + ) + return float(_discounted_rates(cp, cu, grid, S, rate)[-1]) + with np.errstate(all="ignore"): + return cycle_eac(part, t, rate, failure_cost=cu, planned_cost=cp) + + lo, hi = float(ages[max(i - 1, 1)]), float(ages[min(i + 1, ages.size - 1)]) + best_age, best = float(ages[i]), eac(float(ages[i])) + if hi > lo: + found = minimize_scalar( + eac, + bounds=(lo, hi), + method="bounded", + options={"xatol": 1e-10 * hi}, + ) + if float(found.fun) < best: + best_age, best = float(found.x), float(found.fun) + if getattr(part.reliability, "offset", False) and 0.0 < offset < upper: + at_offset = eac(offset) + if at_offset < best: + best_age, best = offset, at_offset + rtf = discounted_run_to_failure(part, rate, cu) + if not best < rtf * (1.0 - 1e-6): + return math.inf, rtf + return best_age, best diff --git a/repyability/maintenance/_plan.py b/repyability/maintenance/_plan.py new file mode 100644 index 00000000..74e93328 --- /dev/null +++ b/repyability/maintenance/_plan.py @@ -0,0 +1,1298 @@ +"""One unit's maintenance plan (UC-63 of this package's README): its life +and repair models, its tasks, each in its own clock, and its prices, as +plain data. + +A ``RepairableRBD`` node takes a ``UnitPlan`` as it takes the spec +dict, which is the plan's shorthand: ``UnitPlan.from_spec`` reads a +spec and ``UnitPlan.spec`` writes the one the diagram's engines +read. What belongs to the system (its structure, system downtime and +value, crews, spares, the site's shutdowns and common-cause groups) stays +on the diagram; a plan names only its maintenance group and its place in +the crews' queue. The diagram checks a plan as it checks a spec, naming +the node. (A plan is a ``UnitPlan``: ``MaintenancePlan`` is the result +of ``RepairableRBD.optimal_replacement_intervals``.) +""" + +from dataclasses import dataclass, field, fields +from typing import Any, ClassVar, Dict, Hashable, Optional, Tuple + +#: A task that takes no time. +INSTANT = "instant" + + +def _put(out: dict, key: str, value, default=None) -> None: + """Write ``key`` unless ``value`` is its default (not given).""" + if value is not None and not ( + isinstance(value, str) + and isinstance(default, str) + and value == default + ): + out[key] = value + + +def _take(spec: dict, used: set, key: str, default=None): + """``spec[key]`` (``default`` if absent or None), noting it was read.""" + used.add(key) + value = spec.get(key) + return default if value is None else value + + +def _all_read(what: str, spec: dict, used: set) -> None: + """Refuse a spec with a key no field of the plan holds: it would be + dropped quietly.""" + left = sorted( + str(key) for key in set(spec) - used if spec[key] is not None + ) + if left: + raise ValueError( + f"A {what} spec has key(s) {left} that a UnitPlan does " + "not hold; check their spelling against the spec's keys " + "(RepairableRBD.COMPONENT_SPEC_KEYS, PREVENTIVE_KEYS, " + "INSPECTION_KEYS)." + ) + + +@dataclass(frozen=True) +class Restoration: + """How much of its age a preventive task takes away (a task that + renews the unit, the default, has none). + + Give a Kijima factor (``q`` with ``model`` ``"kijima1"`` or + ``"kijima2"``: 0 renews, 1 leaves the unit as old as it was, above 1 + leaves it older), a virtual age to restore to (``to_age``), or a + fitted surpyval ``GeneralizedRenewal`` (``process``). With + ``replace_every`` ``N``, every ``N``-th task replaces the unit, at + ``replacement_cost`` (the task's own cost if None). The rules are in + [Maintaining a system](../guide/system-maintenance.md), "Planned + maintenance that restores partly". + + Parameters + ---------- + q : float, optional + Kijima's restoration factor, 0 or more: 0 renews the unit, 1 + leaves it as old as it was, above 1 leaves it older. Not given with + ``to_age`` or ``process``. + model : str, optional + Kijima's virtual-age model for ``q``: ``"kijima2"`` (the default, + the factor applied to the whole virtual age) or ``"kijima1"`` + (to the age gained since the last action). + to_age : float, optional + A virtual age, 0 or more and in the plan's unit of time, that + each task leaves the unit at, whatever its age before. + process : surpyval GeneralizedRenewal, optional + A fitted renewal process whose Kijima model and factor each task + takes. + replace_every : int, optional + Every ``replace_every``-th task since the unit was last renewed + replaces it as new instead. + replacement_cost : float or distribution, optional + The price of such a replacement, in money; by default the task's + own ``cost``. + """ + + q: Optional[float] = None + model: str = "kijima2" + to_age: Optional[float] = None + process: Any = None + replace_every: Optional[int] = None + replacement_cost: Any = None + + def __post_init__(self): + given = [ + name + for name in ("q", "to_age", "process") + if getattr(self, name) is not None + ] + if len(given) > 1: + raise ValueError( + "A Restoration takes one of q (a Kijima factor), to_age " + f"(a virtual age) and process (a fitted model), got {given}." + ) + + def spec(self) -> dict: + """The keys of a ``"preventive"`` spec this restoration is.""" + out: dict = {} + if self.to_age is not None: + out["restore_to"] = self.to_age + elif self.process is not None: + out["restoration"] = self.process + elif self.q is not None: + out["restoration"] = {"model": self.model, "q": self.q} + _put(out, "replace_every", self.replace_every) + _put(out, "replacement_cost", self.replacement_cost) + return out + + @classmethod + def _read(cls, spec: dict, used: set) -> Optional["Restoration"]: + given = _take(spec, used, "restoration") + kwargs: Dict[str, Any] = { + "to_age": _take(spec, used, "restore_to"), + "replace_every": _take(spec, used, "replace_every"), + "replacement_cost": _take(spec, used, "replacement_cost"), + } + if isinstance(given, dict): + kwargs.update(model=given.get("model"), q=given.get("q")) + elif given is not None: + kwargs["process"] = given + if all(value is None for value in kwargs.values()): + return None + return cls(**kwargs) + + +@dataclass(frozen=True) +class _Task: + """A preventive task: what each kind shares.""" + + #: The spec's ``"policy"`` for this kind, and the one it is by default. + POLICY: ClassVar[str] = "age" + DEFAULT_POLICY: ClassVar[str] = "age" + #: The fields written as the spec's keys of the same name. + _PLAIN: ClassVar[Tuple[str, ...]] = () + + def spec(self) -> dict: + """The ``"preventive"`` spec this task is.""" + out: dict = {} + if self.POLICY != self.DEFAULT_POLICY: + out["policy"] = self.POLICY + for name in self._PLAIN: + _put(out, name, getattr(self, name), INSTANT) + restoration = getattr(self, "restoration", None) + if restoration is not None: + out.update(restoration.spec()) + return out + + @classmethod + def _read(cls, spec: dict, used: set): + kwargs = { + name: _take( + spec, used, name, INSTANT if name == "duration" else None + ) + for name in cls._PLAIN + } + if any(f.name == "restoration" for f in fields(cls)): + kwargs["restoration"] = Restoration._read(spec, used) + return cls(**kwargs) + + +_COMMON = ("cost", "duration", "basis") + + +@dataclass(frozen=True) +class AgePolicy(_Task): + """Replace (or restore) the unit at age ``interval`` since it was + last renewed, or at a failure, whichever comes first. + + ``cost`` is each task's price (a number, or a distribution drawn each + time), ``duration`` its time (a model, or ``"instant"``), and + ``opportunity`` the age from which a stop of the unit's maintenance + group renews it early. ``basis="operating"`` counts the times in + operating hours (put on the clock through the unit's duty). The + spec's keys are in the [preventive maintenance + guide](../guide/system-maintenance.md#preventive-maintenance). + + Parameters + ---------- + interval : float + The age at which the unit is replaced, in the plan's unit of time, + more than 0 (``inf``: never). + cost : float or distribution, optional + The price of each task, in money: a number, or a distribution of it + (anything with ``qf`` and ``mean``, such as a fitted surpyval + model) drawn afresh each time. None prices nothing. + duration : model, float or "instant", optional + How long each task takes, in the plan's unit of time: a + time-to-maintain model or a fixed time, the unit down meanwhile (a + planned outage); ``"instant"`` (the default) renews it in place. + opportunity : float, optional + An age, from 0 to ``interval``, from which a stop of the unit's + maintenance group (the plan's ``group``) renews it early, as the + task would; None takes no opportunity. + restoration : Restoration, optional + How much of the unit's age each task takes away; None (the + default) renews it as new. + basis : str, optional + What the task's times are counted in: ``"calendar"`` (None, the + default) or ``"operating"``, the unit's running hours, put on the + calendar through its ``duty`` (see [Operating part of the + time](../guide/repairable.md#operating-part-of-the-time)). + """ + + interval: Any = None + cost: Any = None + duration: Any = INSTANT + opportunity: Optional[float] = None + restoration: Optional[Restoration] = None + basis: Optional[str] = None + + POLICY: ClassVar[str] = "age" + _PLAIN: ClassVar[Tuple[str, ...]] = ("interval", "opportunity") + _COMMON + + +@dataclass(frozen=True) +class BlockPolicy(_Task): + """Replace (or restore) the unit every ``interval`` whatever its age, + or at each of the given ``times`` (from 0) and no more. A + replacement due while the unit is down is skipped. + + Parameters + ---------- + interval : float, optional + The time between replacements, in the plan's unit of time (at + ``interval``, ``2 * interval``, ...); not given with ``times``. + times : sequence of float, optional + The times of the replacements, increasing, from 0 on the + diagram's clock, and none after the last: a plan valued over a + horizon (see [Replacement at given + times](../guide/system-maintenance.md#replacement-at-given-times)). + cost : float or distribution, optional + The price of each task, in money: a number, or a distribution of it + (anything with ``qf`` and ``mean``, such as a fitted surpyval + model) drawn afresh each time. None prices nothing. + duration : model, float or "instant", optional + How long each task takes, in the plan's unit of time: a + time-to-maintain model or a fixed time, the unit down meanwhile (a + planned outage); ``"instant"`` (the default) renews it in place. + restoration : Restoration, optional + How much of the unit's age each task takes away; None (the + default) renews it as new. + basis : str, optional + What the task's times are counted in: ``"calendar"`` (None, the + default) or ``"operating"``, the unit's running hours, put on the + calendar through its ``duty`` (see [Operating part of the + time](../guide/repairable.md#operating-part-of-the-time)). + """ + + interval: Any = None + times: Optional[Tuple[float, ...]] = None + cost: Any = None + duration: Any = INSTANT + restoration: Optional[Restoration] = None + basis: Optional[str] = None + + POLICY: ClassVar[str] = "block" + _PLAIN: ClassVar[Tuple[str, ...]] = ("interval",) + _COMMON + + def spec(self) -> dict: + """The ``"preventive"`` spec this task is (``"replace_at"`` for + given ``times``).""" + out = super().spec() + if self.times is not None: + # A plan's times are block replacement by default. + out.pop("policy", None) + out["replace_at"] = self.times + return out + + @classmethod + def _read(cls, spec: dict, used: set): + task = super()._read(spec, used) + times = _take(spec, used, "replace_at") + if times is None: + return task + from dataclasses import replace + + return replace(task, times=times) + + +@dataclass(frozen=True) +class ConditionPolicy(_Task): + """Inspect the unit every ``interval`` and replace (or restore) it + when its chance of failing by the next inspection is above + ``threshold``, or, for a degradation process, its measured ``level`` + is reached; each inspection costs ``inspection_cost``. See + [Replacement on + condition](../guide/system-maintenance.md#replacement-on-condition). + + Parameters + ---------- + interval : float + The time between inspections, in the plan's unit of time, more + than 0; inspections are done while the unit is up, in no time. + threshold : float, optional + A probability: the unit is replaced when its chance of + failing before the next inspection, given its age, is above it. + Not given with ``level``. + level : float, optional + For a life that is a degradation process: the measured level, in + the process's units, at or past which the unit is replaced + (simulated only). Not given with ``threshold``. + inspection_cost : float or distribution, optional + The price of each inspection, in money (a number, or a + distribution drawn afresh each time). + cost : float or distribution, optional + The price of each replacement, in money: a number, or a + distribution of it (anything with ``qf`` and ``mean``, such as a + fitted surpyval model) drawn afresh each time. None prices + nothing. + duration : model, float or "instant", optional + How long each task takes, in the plan's unit of time: a + time-to-maintain model or a fixed time, the unit down meanwhile (a + planned outage); ``"instant"`` (the default) renews it in place. + restoration : Restoration, optional + How much of the unit's age each task takes away; None (the + default) renews it as new. + basis : str, optional + What the task's times are counted in: ``"calendar"`` (None, the + default) or ``"operating"``, the unit's running hours, put on the + calendar through its ``duty`` (see [Operating part of the + time](../guide/repairable.md#operating-part-of-the-time)). + """ + + interval: Any = None + threshold: Optional[float] = None + level: Optional[float] = None + inspection_cost: Any = None + cost: Any = None + duration: Any = INSTANT + restoration: Optional[Restoration] = None + basis: Optional[str] = None + + POLICY: ClassVar[str] = "condition" + _PLAIN: ClassVar[Tuple[str, ...]] = ( + "interval", + "threshold", + "level", + "inspection_cost", + ) + _COMMON + + +@dataclass(frozen=True) +class CalendarReplacement(_Task): + """Replace the unit on a calendar ``policy``'s thresholds: a + ``CalendarPolicy`` (``NonRepairable.optimal_calendar_policy``) or a + site's ``ShutdownPolicy``, whose prices are charged; ``opportunity`` + as for ``AgePolicy``. See [Replacement on a calendar + policy](../guide/system-maintenance.md#replacement-on-a-calendar-policy). + + Parameters + ---------- + policy : CalendarPolicy or ShutdownPolicy + The calendar policy whose thresholds say when the unit is + replaced: at the first time its age reaches one. Its prices are + charged, so the task takes no ``cost``. + duration : model, float or "instant", optional + How long each task takes, in the plan's unit of time: a + time-to-maintain model or a fixed time, the unit down meanwhile (a + planned outage); ``"instant"`` (the default) replaces it in place. + opportunity : float, optional + An age, from which a stop of the unit's + maintenance group (the plan's ``group``) renews it early, as the + task would; None takes no opportunity. + basis : str, optional + What the task's times are counted in: ``"calendar"`` (None, the + default) or ``"operating"``, the unit's running hours, put on the + calendar through its ``duty`` (see [Operating part of the + time](../guide/repairable.md#operating-part-of-the-time)). + """ + + policy: Any = None + duration: Any = INSTANT + opportunity: Optional[float] = None + basis: Optional[str] = None + + POLICY: ClassVar[str] = "calendar" + _PLAIN: ClassVar[Tuple[str, ...]] = ("duration", "opportunity", "basis") + + def spec(self) -> dict: + """The ``"preventive"`` spec this task is (its policy under + ``"calendar"``).""" + out = super().spec() + _put(out, "calendar", self.policy) + return out + + @classmethod + def _read(cls, spec: dict, used: set): + task = super()._read(spec, used) + from dataclasses import replace + + return replace(task, policy=_take(spec, used, "calendar")) + + +@dataclass(frozen=True) +class AtShutdown(_Task): + """Renew the unit at each of the site's shutdowns named ``shutdown`` + (a name, or a list of names), taking the shut's time; with + ``older_than``, only if it is that old. ``policy="condition"`` + inspects it there instead, replacing it above ``threshold``. See + [Shutdowns](../guide/system-maintenance.md#shutdowns). + + Parameters + ---------- + shutdown : str or list of str + The name (or names) of the diagram's shutdowns at whose shuts the + task is done; it takes the shut's time. + policy : str, optional + ``"block"`` (the default): renewed at every shut (with + ``older_than``, only if that old). ``"condition"``: inspected at + every shut and replaced above ``threshold``. + older_than : float, optional + Renewed at a shut only if its age then is at least this, in the + plan's unit of time. + threshold : float, optional + Under ``"condition"``: the probability of failing + before the next shut, given its age, above which it is replaced. + inspection_cost : float or distribution, optional + The price of each inspection (under ``"condition"``), in money + (a number, or a distribution drawn afresh each time). + cost : float or distribution, optional + The price of each renewal, in money: a number, or a distribution of it + (anything with ``qf`` and ``mean``, such as a fitted surpyval + model) drawn afresh each time. None prices nothing. + restoration : Restoration, optional + How much of the unit's age each task takes away; None (the + default) renews it as new. + basis : str, optional + What the task's times are counted in: ``"calendar"`` (None, the + default) or ``"operating"``, the unit's running hours, put on the + calendar through its ``duty`` (see [Operating part of the + time](../guide/repairable.md#operating-part-of-the-time)). + """ + + shutdown: Any = None + policy: str = "block" + older_than: Optional[float] = None + threshold: Optional[float] = None + inspection_cost: Any = None + cost: Any = None + restoration: Optional[Restoration] = None + basis: Optional[str] = None + + POLICY: ClassVar[str] = "block" + DEFAULT_POLICY: ClassVar[str] = "block" + _PLAIN: ClassVar[Tuple[str, ...]] = ( + "shutdown", + "older_than", + "threshold", + "inspection_cost", + "cost", + "basis", + ) + + def spec(self) -> dict: + """The ``"preventive"`` spec this task is (with its + ``"shutdown"``).""" + out = super().spec() + if self.policy != self.DEFAULT_POLICY: + out = {"policy": self.policy, **out} + return out + + @classmethod + def _read(cls, spec: dict, used: set): + task = super()._read(spec, used) + from dataclasses import replace + + return replace(task, policy=_take(spec, used, "policy", "block")) + + +@dataclass(frozen=True) +class Inspection: + """Test the unit every ``interval`` (or at the site's ``shutdown``), + finding a hidden failure; the first at ``offset``, each finding one + with probability ``coverage`` and every ``full_test`` all of them, + each taking ``duration`` and costing ``cost``. The spec's keys are in + [Hidden failures and + inspection](../guide/system-maintenance.md#hidden-failures-and-inspection). + + Parameters + ---------- + interval : float, optional + The time between tests, in the plan's unit of time, more than 0; + not given with ``shutdown``. + cost : float or distribution, optional + The price of each test, in money: a number, or a distribution of it + (anything with ``qf`` and ``mean``, such as a fitted surpyval + model) drawn afresh each time. None prices nothing. + duration : model, float or "instant", optional + How long each test takes, in the plan's unit of time: a model or a + fixed time, the unit off line meanwhile; ``"instant"`` (the + default) takes no time. + offset : float, optional + The time of the first test, from 0 to less than ``interval`` + (tests at ``offset``, ``offset + interval``, ...); by default the + first is at ``interval``. + coverage : float, optional + The chance in [0, 1] that a test finds a failure (by default 1); a + failure a test misses stays hidden until a full test. + full_test : float, optional + With a ``coverage`` below 1: the time between full tests, which + find every failure, a whole multiple of ``interval``. + shutdown : str or list of str, optional + The name (or names) of the diagram's shutdowns at whose shuts the + unit is tested, in place of an ``interval``. + basis : str, optional + What the test's times (``interval``, ``offset``, ``full_test``) + are counted in: ``"calendar"`` (None, the default) or + ``"operating"``, the unit's running hours, put on the calendar + through its ``duty`` (see [Operating part of the + time](../guide/repairable.md#operating-part-of-the-time)). + """ + + interval: Any = None + cost: Any = None + duration: Any = INSTANT + offset: Optional[float] = None + coverage: Optional[float] = None + full_test: Optional[float] = None + shutdown: Any = None + basis: Optional[str] = None + + def spec(self) -> dict: + """The ``"inspection"`` spec this task is.""" + out: dict = {} + for f in fields(self): + _put(out, f.name, getattr(self, f.name), INSTANT) + return out + + @classmethod + def _read(cls, spec: dict, used: set) -> "Inspection": + return cls( + **{ + f.name: _take( + spec, + used, + f.name, + INSTANT if f.name == "duration" else None, + ) + for f in fields(cls) + } + ) + + +@dataclass(frozen=True) +class Upgrade: + """From time ``at`` (from 0) the unit has another ``life``: the unit + in service is replaced by one of it, in no time, for the capital + ``cost``. + + Parameters + ---------- + at : float + When the upgrade is made, from 0 on the diagram's clock, in the + plan's unit of time. + life : model + The new unit's time-to-failure model (as the plan's ``life``). + cost : float, optional + The capital cost of the upgrade, in money, charged at ``at``. + """ + + at: Any = None + life: Any = None + cost: Any = None + + def spec(self) -> dict: + """The ``"upgrade"`` spec this task is.""" + out: dict = {"at": self.at, "reliability": self.life} + _put(out, "cost", self.cost) + return out + + @classmethod + def _read(cls, spec: dict, used: set) -> "Upgrade": + return cls( + at=_take(spec, used, "at"), + life=_take(spec, used, "reliability"), + cost=_take(spec, used, "cost"), + ) + + +@dataclass(frozen=True) +class ImperfectRepair: + """A repair that restores the unit only partly: Kijima's ``model`` + (``"kijima1"`` or ``"kijima2"``) with factor ``q`` in [0, 1], or a + fitted renewal ``process`` (G1, ARA, ARI) repairing by its own rule. + With ``replace_after`` ``N``, the ``N``-th failure since the unit was + renewed replaces it. See [Imperfect + repair](../guide/repairable.md#imperfect-repair). + + Parameters + ---------- + model : str, optional + Kijima's virtual-age model: ``"kijima1"`` (the default, the + factor applied to the age gained since the last repair) or + ``"kijima2"`` (to the whole virtual age). + q : float, optional + The restoration factor in [0, 1]: 0 renews the unit at each + repair, 1 leaves it as old as it was (minimal repair). + process : surpyval renewal model, optional + A fitted G1, ARA or ARI renewal process repairing by its own rule, + in place of ``model`` and ``q``. + replace_after : int, optional + The failure, counted since the unit was renewed, at which it is + replaced rather than repaired. + """ + + model: str = "kijima1" + q: Optional[float] = None + process: Any = None + replace_after: Optional[int] = None + + def spec(self) -> dict: + """The spec's ``"repair"`` and ``"replace_after"``.""" + out: dict = {} + if self.process is not None: + out["repair"] = {"model": "process", "process": self.process} + elif self.q is not None: + out["repair"] = {"model": self.model, "q": self.q} + _put(out, "replace_after", self.replace_after) + return out + + +@dataclass(frozen=True) +class Prices: + """The unit's own prices: each ``repair``, each ``replace`` (a + failure that uses a spare; each a number or a distribution), its own + ``downtime`` per unit of time down, and its ``acquisition``, the + one-off cost of buying it. A task's price is the task's ``cost``. + The [costs guide](../guide/costs.md) says which price is charged when. + + Parameters + ---------- + repair : float or distribution, optional + The price of each repair (each failure), in money: a number, or a + distribution drawn afresh each time. + replace : float or distribution, optional + The price of each replacement on failure (one that uses a spare), + in money: a number, or a distribution drawn afresh each time. + downtime : float, optional + The price per unit of time the unit is down, in money per the + plan's unit of time, whether or not the system is. + acquisition : float, optional + The one-off cost of buying the unit, in money. + """ + + repair: Any = None + replace: Any = None + downtime: Any = None + acquisition: Any = None + + #: The spec's key for each price. + KEYS: ClassVar[Dict[str, str]] = { + "repair": "repair_cost", + "replace": "replace_cost", + "downtime": "downtime_cost", + "acquisition": "acquisition_cost", + } + + +#: The task classes a plan takes, by the spec key each is under. +PREVENTIVE_TASKS = ( + AgePolicy, + BlockPolicy, + ConditionPolicy, + CalendarReplacement, + AtShutdown, +) +_POLICIES = { + "age": AgePolicy, + "block": BlockPolicy, + "condition": ConditionPolicy, + "calendar": CalendarReplacement, +} + + +#: The plan's fields written as the spec's keys of the same name. +_OWN_KEYS = ( + "priority", + "group", + "standby", + "duty", + "covariates", + "salvage", + "escalation", + "retire_at", +) + + +def _kind(task) -> str: + if isinstance(task, PREVENTIVE_TASKS): + return "preventive" + if isinstance(task, Inspection): + return "inspection" + if isinstance(task, Upgrade): + return "upgrade" + names = ", ".join( + cls.__name__ for cls in PREVENTIVE_TASKS + (Inspection, Upgrade) + ) + raise TypeError( + f"A UnitPlan's task must be one of {names} " + f"(repyability.maintenance), got {task!r}." + ) + + +@dataclass(frozen=True) +class UnitPlan: + """One unit's maintenance plan: its ``life`` and ``repair`` (time to + repair) models, its ``tasks`` and its ``prices``. + + A ``RepairableRBD`` node takes a plan as it takes a spec dict (the + plan's shorthand: ``from_spec`` and ``spec``), so every analysis takes + it. A plan holds at most one preventive task (bind it to several + shutdowns with ``AtShutdown(shutdown=[...])``), one ``Inspection`` and + one ``Upgrade``. ``imperfect_repair`` makes repairs partial; + ``priority`` (the crews' queue, higher first), ``group`` (its + maintenance group's name), ``standby`` (a dict, making the node a + standby group of such units), ``duty`` (the share of the time it + operates, for a life in operating hours) and ``covariates`` (a + surpyval ``StepSchedule``) are as in the spec. + + Three terms are the unit's own money, which a valuation + (``expected_npv``) takes as it takes its arguments of the same names + for the node: ``salvage``, what the unit is worth at the end (a + number, or a function of the age of the unit in service, taking an + array of ages; negative for a cost of disposal); ``escalation``, the + growth rate per unit time of every price of the unit (continuous, of + either sign); and ``retire_at``, when the unit is retired, nothing + earned or spent after it (a plan valued alone, or the only unit of a + diagram). + + A plan is valued alone through the diagram of its one node + (``diagram()``, the node named ``UnitPlan.NODE``): ``expected_npv``, + ``cash_flows``, ``npv_distribution``, ``plan_vs_actual``, + ``expected_cost``, ``expected_cost_rate``, ``events_by_period``, + ``failures_by_period`` and the optimisers are that diagram's, so a plan + alone and a diagram holding it give the same values by the same code. + Each takes ``calendar``, a ``schedule.CalendarContext`` whose ``duty`` + names the node ``"unit"``: the diagram on that calendar. + + Parameters + ---------- + life : model + The unit's time-to-failure model, in the plan's unit of time: a + fitted surpyval model, or any model with a life's functions (a + ``NonRepairableRBD`` included), as a spec's ``"reliability"``. + repair : model, float or "instant", optional + The unit's time-to-repair model, as a spec's + ``"repairability"``; ``"instant"`` repairs it in no time. + tasks : sequence, optional + Its tasks: at most one preventive task (``AgePolicy``, + ``BlockPolicy``, ``ConditionPolicy``, ``CalendarReplacement`` or + ``AtShutdown``), one ``Inspection`` and one ``Upgrade``. + prices : Prices or dict, optional + The unit's own prices (a dict is read as the fields of a + ``Prices``); by default none. + imperfect_repair : ImperfectRepair, optional + Makes each repair partial; by default a repair renews the unit. + priority : float, optional + Its place in the repair crews' queue: higher first. + group : hashable, optional + The name of its maintenance group, whose stops it shares. + standby : dict, optional + Makes the node a standby group of such units, as a spec's + ``"standby"``. + duty : float, optional + The share of the time it operates, in (0, 1], for a life in + operating hours. + covariates : surpyval StepSchedule, optional + The covariates of a regression life over time. + salvage : float or callable, optional + What the unit is worth at the end, in money: a number, or a + function of the age of the unit in service (taking an array of + ages); negative for a cost of disposal. + escalation : float, optional + The continuous growth rate per unit of time of every price of the + unit, of either sign. + retire_at : float, optional + When the unit is retired, in the plan's unit of time from 0; + nothing is earned or spent after it. + + Examples + -------- + >>> import surpyval as surv + >>> from repyability.maintenance import AgePolicy, UnitPlan, Prices + >>> plan = UnitPlan( + ... surv.Weibull.from_params([1000.0, 2.5]), + ... surv.Exponential.from_params([0.1]), + ... tasks=(AgePolicy(interval=4000.0, cost=20.0),), + ... prices=Prices(repair=400.0), + ... ) + >>> sorted(plan.spec()) + ['preventive', 'reliability', 'repair_cost', 'repairability'] + >>> UnitPlan.from_spec(plan.spec()) == plan + True + """ + + life: Any + repair: Any = None + tasks: Tuple[Any, ...] = () + prices: Prices = field(default_factory=Prices) + imperfect_repair: Optional[ImperfectRepair] = None + priority: Optional[float] = None + group: Optional[Hashable] = None + standby: Optional[dict] = None + duty: Optional[float] = None + covariates: Any = None + salvage: Any = None + escalation: Optional[float] = None + retire_at: Optional[float] = None + + #: The node a plan valued alone is in its one-node diagram + #: (``diagram()``): what its results' tables name. + NODE: ClassVar[str] = "unit" + + def __post_init__(self): + if self.life is None: + raise ValueError( + "A UnitPlan needs the unit's life: a fitted model " + "of its time to failure (such as a surpyval distribution)." + ) + tasks = self.tasks + if not isinstance(tasks, (tuple, list)): + tasks = (tasks,) + object.__setattr__(self, "tasks", tuple(tasks)) + if isinstance(self.prices, dict): + object.__setattr__(self, "prices", Prices(**self.prices)) + elif not isinstance(self.prices, Prices): + raise TypeError( + "A UnitPlan's prices are a Prices (or a dict of its " + f"fields: {', '.join(Prices.KEYS)}), got {self.prices!r}." + ) + if not ( + self.imperfect_repair is None + or isinstance(self.imperfect_repair, ImperfectRepair) + ): + raise TypeError( + "A UnitPlan's imperfect_repair is an ImperfectRepair, " + f"got {self.imperfect_repair!r}." + ) + seen: Dict[str, Any] = {} + for task in self.tasks: + kind = _kind(task) + if kind in seen: + more = ( + " A task at several shutdowns is one task: " + "AtShutdown(shutdown=[...])." + if kind == "preventive" + else "" + ) + raise ValueError( + f"A UnitPlan holds one {kind} task, got " + f"{seen[kind]!r} and {task!r}.{more}" + ) + seen[kind] = task + + def task(self, kind: str): + """The plan's ``"preventive"``, ``"inspection"`` or ``"upgrade"`` + task, or None. + + Parameters + ---------- + kind : str + ``"preventive"``, ``"inspection"`` or ``"upgrade"``. + """ + from repyability.utils.checks import one_of + + one_of("kind", kind, ("preventive", "inspection", "upgrade")) + return next((t for t in self.tasks if _kind(t) == kind), None) + + def spec(self) -> dict: + """The spec dict this plan is, as a ``RepairableRBD`` node reads + it: keys at their defaults left out.""" + out: dict = {"reliability": self.life} + if self.repair is not None: + out["repairability"] = self.repair + for name, key in Prices.KEYS.items(): + _put(out, key, getattr(self.prices, name)) + for task in self.tasks: + out[_kind(task)] = task.spec() + if self.imperfect_repair is not None: + out.update(self.imperfect_repair.spec()) + for key in _OWN_KEYS: + _put(out, key, getattr(self, key)) + return out + + @classmethod + def from_spec(cls, spec: dict) -> "UnitPlan": + """The plan a spec dict states (the spec a ``RepairableRBD`` node + takes); a key no field holds is refused. + + Parameters + ---------- + spec : dict + A spec dict with a ``"reliability"``, as a ``RepairableRBD`` + node takes it. + """ + if not isinstance(spec, dict) or "reliability" not in spec: + raise ValueError( + "A spec is a dict with a 'reliability' (and a " + f"'repairability'), got {spec!r}." + ) + used: set = set() + tasks = [] + preventive = _take(spec, used, "preventive") + if preventive is not None: + if not isinstance(preventive, dict): + raise ValueError( + f"A 'preventive' spec is a dict, got {preventive!r}." + ) + inner: set = set() + if preventive.get("shutdown") is not None: + kind: Any = AtShutdown + else: + policy = preventive.get("policy") + if policy is None: + policy = ( + "block" + if preventive.get("replace_at") is not None + else "age" + ) + if policy not in _POLICIES: + raise ValueError( + "A 'preventive' spec's policy is 'age', 'block', " + f"'condition' or 'calendar', got {policy!r}." + ) + kind = _POLICIES[policy] + inner.add("policy") + tasks.append(kind._read(preventive, inner)) + _all_read("'preventive'", preventive, inner) + inspection = _take(spec, used, "inspection") + if inspection is not None: + inner = set() + tasks.append(Inspection._read(inspection, inner)) + _all_read("'inspection'", inspection, inner) + upgrade = _take(spec, used, "upgrade") + if upgrade is not None: + inner = set() + tasks.append(Upgrade._read(upgrade, inner)) + _all_read("'upgrade'", upgrade, inner) + repair = _take(spec, used, "repair") + replace_after = _take(spec, used, "replace_after") + imperfect = None + if repair is not None or replace_after is not None: + repair = repair or {} + imperfect = ( + ImperfectRepair(process=repair.get("process")) + if repair.get("model") == "process" + else ImperfectRepair( + model=repair.get("model", "kijima1"), q=repair.get("q") + ) + ) + if replace_after is not None: + from dataclasses import replace + + imperfect = replace(imperfect, replace_after=replace_after) + plan = cls( + life=_take(spec, used, "reliability"), + repair=_take(spec, used, "repairability"), + tasks=tuple(tasks), + prices=Prices( + **{ + name: _take(spec, used, key) + for name, key in Prices.KEYS.items() + } + ), + imperfect_repair=imperfect, + **{key: _take(spec, used, key) for key in _OWN_KEYS}, + ) + _all_read("component", spec, used) + return plan + + def to_dict(self) -> dict: + """The plan as JSON-ready data (as a diagram saves a node's spec); + ``from_dict`` loads it.""" + from repyability.rbd.serialisation import _serialise_component + + return { + "kind": "unit_plan", + "spec": _serialise_component(self.spec()), + } + + @classmethod + def from_dict(cls, data: dict) -> "UnitPlan": + """The plan ``to_dict`` saved. + + Parameters + ---------- + data : dict + What ``to_dict`` returned. + """ + from repyability.rbd.serialisation import _deserialise_component + + if not isinstance(data, dict) or data.get("kind") != "unit_plan": + raise ValueError( + "Not a saved UnitPlan (a dict of kind " + f"'unit_plan', from UnitPlan.to_dict): {data!r}." + ) + return cls.from_spec(_deserialise_component(data["spec"])) + + # -- the plan valued alone (UC-65 of this package's README) ------------ + + def diagram(self, calendar=None): + """The ``RepairableRBD`` of this plan's one node (named + ``UnitPlan.NODE``), on ``calendar`` if given (a + ``schedule.CalendarContext``; its ``duty`` names the node + ``"unit"``): what every valuation of the plan alone asks. + + Parameters + ---------- + calendar : CalendarContext, optional + The calendar the plan's diagram runs on (its ``duty`` names + the node ``"unit"``); by default none. + """ + from repyability.rbd.repairable_rbd import RepairableRBD + + node = self.NODE + rbd = RepairableRBD([("input", node), (node, "output")], {node: self}) + if calendar is None: + return rbd + from repyability.schedule._calendar import CalendarContext + + if not isinstance(calendar, CalendarContext): + raise TypeError( + "calendar must be a schedule.CalendarContext (its duty " + f"naming the node {node!r}); got {calendar!r}." + ) + return calendar.diagram(rbd) + + def analysis_routes(self, calendar=None) -> dict: + """How each valuation of the plan alone is worked out (exact, + numerical, simulated or refused, with the reason), without + running anything: its diagram's routes, by the plan's method. + + Parameters + ---------- + calendar : CalendarContext, optional + The calendar the plan's diagram runs on (its ``duty`` names + the node ``"unit"``); by default none. + """ + routes = self.diagram(calendar).analysis_routes() + return { + mine: routes[theirs] + for mine, theirs in _PLAN_ROUTES.items() + if theirs in routes + } + + def expected_npv(self, horizon, *, calendar=None, **kwargs): + """The plan's expected net present value over ``horizon``: + ``RepairableRBD.expected_npv`` of its one-node diagram (the same + arguments), its salvage, escalation and retirement taken from + the plan where the arguments leave them out. + + Parameters + ---------- + horizon : float + The length of time valued, in the plan's unit of time. + calendar : CalendarContext, optional + The calendar the plan's diagram runs on (its ``duty`` names + the node ``"unit"``); by default none. + **kwargs + As for ``RepairableRBD.expected_npv``. + + Examples + -------- + >>> import math + >>> import surpyval as surv + >>> from repyability.maintenance import AgePolicy, Prices, UnitPlan + >>> pump = UnitPlan( + ... surv.Weibull.from_params([20000.0, 2.5]), + ... surv.Exponential.from_params([1 / 24]), + ... tasks=(AgePolicy(interval=12000.0, cost=1500.0),), + ... prices=Prices(repair=6000.0, acquisition=40000.0), + ... salvage=5000.0, + ... ) + >>> r = math.log(1.07) / 8760 + >>> result = pump.expected_npv(8 * 8760.0, discount_rate=r) + >>> round(result.npv), round(result.salvage) + (-48719, 2910) + """ + return self.diagram(calendar).expected_npv(horizon, **kwargs) + + def cash_flows(self, horizon, *, calendar=None, **kwargs): + """The plan's expected cash flows by period and category: the + table of ``expected_npv`` (the same arguments; ``periods`` sets + the periods). + + Parameters + ---------- + horizon : float + The length of time valued, in the plan's unit of time. + calendar : CalendarContext, optional + The calendar the plan's diagram runs on (its ``duty`` names + the node ``"unit"``); by default none. + **kwargs + As for ``expected_npv``. + """ + return self.expected_npv( + horizon, calendar=calendar, **kwargs + ).cash_flows + + def npv_distribution(self, horizon, *, calendar=None, **kwargs): + """The plan's NPV in each of many simulated runs: + ``RepairableRBD.npv_distribution`` of its one-node diagram. + + Parameters + ---------- + horizon : float + The length of time valued, in the plan's unit of time. + calendar : CalendarContext, optional + The calendar the plan's diagram runs on (its ``duty`` names + the node ``"unit"``); by default none. + **kwargs + As for ``RepairableRBD.npv_distribution``. + """ + return self.diagram(calendar).npv_distribution(horizon, **kwargs) + + def plan_vs_actual( + self, timeline, now, horizon, *, calendar=None, **kwargs + ): + """The plan against what happened to the unit: its ``Timeline`` + (outage log) to ``now``, as ``RepairableRBD.plan_vs_actual`` of + its one-node diagram; a ``state`` is the unit's ``NodeState``. + + Parameters + ---------- + timeline : Timeline + The unit's outage log up to ``now``. + now : float + The time of the last record, in the plan's unit of time. + horizon : float + The length of time valued from 0, in the plan's unit of time. + calendar : CalendarContext, optional + The calendar the plan's diagram runs on (its ``duty`` names + the node ``"unit"``); by default none. + **kwargs + As for ``RepairableRBD.plan_vs_actual``; a ``state`` or + ``start_state`` is the unit's own ``NodeState``. + """ + state = kwargs.pop("state", None) + if state is not None: + kwargs["state"] = {self.NODE: state} + start = kwargs.pop("start_state", None) + if start is not None: + kwargs["start_state"] = {self.NODE: start} + return self.diagram(calendar).plan_vs_actual( + {self.NODE: timeline}, now, horizon, **kwargs + ) + + def expected_cost(self, t, *, calendar=None, **kwargs): + """The plan's expected cost to ``t``: + ``RepairableRBD.expected_cost`` of its one-node diagram. + + Parameters + ---------- + t : float + The time to which costs are counted, in the plan's unit of + time. + calendar : CalendarContext, optional + The calendar the plan's diagram runs on (its ``duty`` names + the node ``"unit"``); by default none. + **kwargs + As for ``RepairableRBD.expected_cost``. + """ + return self.diagram(calendar).expected_cost(t, **kwargs) + + def expected_cost_rate(self, *, calendar=None) -> float: + """The plan's long-run expected cost per unit time: + ``RepairableRBD.expected_cost_rate`` of its one-node diagram. + + Parameters + ---------- + calendar : CalendarContext, optional + The calendar the plan's diagram runs on (its ``duty`` names + the node ``"unit"``); by default none. + """ + return self.diagram(calendar).expected_cost_rate() + + def events_by_period(self, usage, period: str = "month", **kwargs): + """The plan's expected events (and on request costs) in each + calendar period: ``schedule.events_by_period`` of its one-node + diagram; ``usage`` a ``UsageForecast`` or a ``CalendarContext`` + (giving the node ``"unit"`` its duty plan). + + Parameters + ---------- + usage : UsageForecast or CalendarContext + The calendar and the unit's duty plan (a ``CalendarContext``'s + ``duty`` names the node ``"unit"``). + period : str, optional + The calendar period counted in: ``"month"`` (the default), as + ``schedule.events_by_period`` takes. + **kwargs + As for ``schedule.events_by_period``. + """ + from repyability.schedule import events_by_period + + return events_by_period(self.diagram(), usage, period, **kwargs) + + def failures_by_period(self, usage, period: str = "month", **kwargs): + """The plan's expected failures (with the other events) in each + calendar period, as ``events_by_period``: a unit in a plan is + worked out by the diagram's engine, its tasks and repairs taking + their time, on the calendar its duty plan gives. + + Parameters + ---------- + usage : UsageForecast or CalendarContext + As for ``events_by_period``. + period : str, optional + As for ``events_by_period``. + **kwargs + As for ``events_by_period``. + """ + return self.events_by_period(usage, period, **kwargs) + + def optimal_replacement_interval(self, *, calendar=None, **kwargs): + """The plan's best age-replacement interval: + ``RepairableRBD.optimal_replacement_intervals`` of its one-node + diagram (the same arguments, but ``nodes``). + + Parameters + ---------- + calendar : CalendarContext, optional + The calendar the plan's diagram runs on (its ``duty`` names + the node ``"unit"``); by default none. + **kwargs + As for ``RepairableRBD.optimal_replacement_intervals``. + """ + return self.diagram(calendar).optimal_replacement_intervals(**kwargs) + + def least_spend_for_downtime( + self, horizon, limit, *, calendar=None, **kwargs + ): + """The least spend that keeps a bad run's downtime under + ``limit``: ``RepairableRBD.least_spend_for_downtime`` of its + one-node diagram (the same arguments; a lever names the node + ``"unit"``). + + Parameters + ---------- + horizon : float + The length of time valued. + limit : float + The downtime a bad run must stay under. + calendar : CalendarContext, optional + The calendar the diagram runs on, as for ``diagram``. + **kwargs + As for ``RepairableRBD.least_spend_for_downtime``. + """ + return self.diagram(calendar).least_spend_for_downtime( + horizon, limit, **kwargs + ) + + def optimal_inspection_interval(self, *, calendar=None, **kwargs): + """The plan's best proof-test interval: + ``RepairableRBD.optimal_inspection_intervals`` of its one-node + diagram (the same arguments, but ``nodes``). + + Parameters + ---------- + calendar : CalendarContext, optional + The calendar the plan's diagram runs on (its ``duty`` names + the node ``"unit"``); by default none. + **kwargs + As for ``RepairableRBD.optimal_inspection_intervals``. + """ + return self.diagram(calendar).optimal_inspection_intervals(**kwargs) + + +#: Each valuation of a plan alone, by the route of its diagram's method. +_PLAN_ROUTES = { + "expected_npv": "expected_npv", + "cash_flows": "expected_npv", + "npv_distribution": "npv_distribution", + "plan_vs_actual": "plan_vs_actual", + "expected_cost": "expected_cost", + "expected_cost_rate": "expected_cost_rate", + "events_by_period": "expected_events_by_window", + "failures_by_period": "expected_events_by_window", + "optimal_replacement_interval": "optimal_replacement_intervals", + "optimal_inspection_interval": "optimal_inspection_intervals", + "least_spend_for_downtime": "least_spend_for_downtime", +} diff --git a/repyability/maintenance/_repair_or_replace.py b/repyability/maintenance/_repair_or_replace.py index 74fb397c..a15ce2f9 100644 --- a/repyability/maintenance/_repair_or_replace.py +++ b/repyability/maintenance/_repair_or_replace.py @@ -31,6 +31,7 @@ from scipy.optimize import brentq, minimize_scalar from scipy.special import roots_hermitenorm, roots_legendre +from repyability.rbd._streams import shared_seed from repyability.rbd.results import _ResultMapping from repyability.utils import checks from repyability.utils.deprecation import refuse_removed_names @@ -1222,7 +1223,9 @@ def unit_decision( mc_samples : int, optional The number of parameter draws for the bands, default 500. seed : int, optional - Seeds the draws, for reproducible bands. + Seeds the draws, for reproducible bands. By default one is + drawn from numpy's global RNG (``np.random.seed`` makes it + repeatable). Returns ------- @@ -1261,10 +1264,11 @@ def unit_decision( _DEFAULT_DRAWS if mc_samples is None else mc_samples, "mc_samples" ) seed = checks.seed(seed) - if uncertainty and seed is None: + if uncertainty: # One seed for the unit's draws and the fleet's, so that they - # are the same draws. - seed = int(np.random.default_rng().integers(2**32)) + # are the same draws (drawn from numpy's global RNG if not + # given). + seed = shared_seed(seed) failed = bool(just_failed) rule, g, _, fleet_age, _, fleet_k, _, notes = self._best(kmax) engine = self._engine @@ -1361,7 +1365,9 @@ def unit_decisions( mc_samples : int, optional The number of parameter draws for the bands, default 500. seed : int, optional - Seeds the draws; every unit's bands use the same draws. + Seeds the draws; every unit's bands use the same draws. By + default one is drawn from numpy's global RNG + (``np.random.seed`` makes it repeatable). Returns ------- @@ -1398,8 +1404,8 @@ def unit_decisions( "ages must be a mapping of each unit's age by its name, got " f"{type(ages).__name__}." ) - if seed is None and uncertainty: - seed = int(np.random.default_rng().integers(2**32)) + if uncertainty: + seed = shared_seed(seed) return { name: self.unit_decision( age, diff --git a/repyability/maintenance/_replacement.py b/repyability/maintenance/_replacement.py index 8573a2f5..90857d3c 100644 --- a/repyability/maintenance/_replacement.py +++ b/repyability/maintenance/_replacement.py @@ -23,6 +23,13 @@ a solve over a window from it (deterministic, cached). - **A given rule** (``_evaluate``): its cost rate, by the same iteration with the decisions fixed, to price naive policies. +- **Discounted, over a periodic calendar** (``_discounted_values``): value + iteration over one cycle, each step discounted by ``exp(-r step)``, + stopped by MacQueen's bounds (every path through a cycle is discounted + by the same ``exp(-r L)``, so the fixed point lies within a known band + of the last sweep). The policy minimises the present value of every + replacement from a new part at time 0, and ``r`` times it is the + equivalent annual cost (Fox, 1966). A failure is replaced by the next step, so the grid's cost rate is low by about ``step / 2`` of each failure's time over the mean cycle: O(step). @@ -306,6 +313,84 @@ def _relative_values( ) +@dataclass +class _Discounted: + """Discounted value iteration's result over one cycle.""" + + values: np.ndarray + low: float + high: float + first: np.ndarray + upper: bool + sweeps: int + converged: bool + + +def _discounted_values( + costs: np.ndarray, + ages: _Ages, + failure: float, + rate: float, + fixed: Optional[np.ndarray] = None, +) -> _Discounted: + """The present value, by age, of a part at the start of a periodic + calendar of ``costs`` (one cycle of steps), every replacement from + then on discounted continuously at ``rate`` a unit of time: value + iteration over the cycle, each step discounted by ``exp(-rate * + step)``. + + Every path through a cycle is discounted by the same ``rho = exp(-rate + * L)``, so a sweep ``T`` takes ``v + c`` to ``T v + rho c``, and after + a sweep from ``h`` the fixed point lies between ``T h + rho / (1 - + rho) * min(T h - h)`` and the same with the max (MacQueen's bounds). + Like relative value iteration, each sweep starts from the last one's + values less a new part's (``h[0] = 0``), which keeps them small: the + values themselves (about the cost rate over ``rate``) would swamp the + differences the bounds are made of. The sweeps stop once the band is + within ``TOLERANCE`` of the value, and the value is its middle; the + decisions, which a constant added to every value does not change, + converge as relative value iteration's do. ``low`` and ``high`` bound + a new part's value. ``fixed`` prices a given rule instead (each + step's first replacing age index, -1 for none), as + ``_relative_values`` does undiscounted.""" + beta = math.exp(-rate * ages.step) + rho = math.exp(-rate * ages.step * costs.size) + factor = rho / (1.0 - rho) + h = np.zeros(ages.size + 1) + limit = max(1, int(MAX_LIVES * (ages.size + 1) / costs.size)) + low = high = math.nan + v = h + first = np.full(costs.size, -1, dtype=np.int64) + upper = True + converged = False + sweep = 0 + for sweep in range(1, limit + 1): + v, first, upper = _sweep(h, costs, ages.p, failure, beta, fixed) + change = v - h + low, high = float(change.min()), float(change.max()) + top = abs(float(v[0]) + factor * high) + if factor * (high - low) <= TOLERANCE * max(top, 1e-300): + converged = True + break + h = v - v[0] + if not converged: + warnings.warn( + f"The discounted values did not settle in {limit} sweeps of " + f"the cycle: a new part's lies between " + f"{v[0] + factor * low:.6g} and {v[0] + factor * high:.6g}.", + stacklevel=outside_level(), + ) + return _Discounted( + v + factor * 0.5 * (low + high), + float(v[0]) + factor * low, + float(v[0]) + factor * high, + first, + upper, + sweep, + converged, + ) + + def _window(grid: _Grid, start: int, n: int, ages: _Ages, failure: float): """A finite-horizon solve over ``n`` steps from grid index ``start``: the cost to go of a new part at each step, each step's first @@ -497,7 +582,7 @@ class PlannedReplacement(_ResultMapping): class CalendarPolicy(_ResultMapping): """The long-run optimal replacement policy of a part over a calendar of opportunities. Returned by - [`NonRepairable.optimal_calendar_policy`][repyability.NonRepairable.optimal_calendar_policy]. + [`NonRepairable.optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy]. At each opportunity the policy replaces the part if it is at least a threshold age, which depends on the time: a shut shortly before a @@ -560,6 +645,19 @@ class CalendarPolicy(_ResultMapping): diagrams save a model), which a [`RepairableRBD`][repyability.RepairableRBD] component given the policy must have; None where the life does not save. + discount_rate : float + The continuous discount rate per unit of the calendar's time the + policy was chosen at (0: none, the long-run average). Discounted, + the policy minimises ``npv``, and ``cost_rate``, the rates by kind + and the schedule's chances are still the long-run (undiscounted) + figures of the policy chosen. + npv : float + The present value at time 0 of every replacement, forever, from a + new part put in then; ``inf`` with no discounting. + eac : float + The equivalent annual cost, ``discount_rate * npv``: the steady + cost a unit of time worth the same. With no discounting, + ``cost_rate``. Examples -------- @@ -568,17 +666,20 @@ class CalendarPolicy(_ResultMapping): them, and 20 at a failure: >>> import surpyval as surv - >>> from repyability import Calendar, NonRepairable, Opportunity - >>> bearing = NonRepairable(surv.Weibull.from_params([1000.0, 2.5])) - >>> calendar = Calendar( + >>> from repyability import NonRepairable, Opportunities, Opportunity + >>> bearing = NonRepairable( + ... surv.Weibull.from_params([1000.0, 2.5]), + ... unplanned_cost=20.0, + ... opportunity_costs={"quarterly": 3.0, "annual": 1.0}, + ... ) + >>> shuts = Opportunities( ... [ - ... Opportunity("quarterly", 3.0, period=91.0), - ... Opportunity("annual", 1.0, period=364.0), + ... Opportunity("quarterly", period=91.0), + ... Opportunity("annual", period=364.0), ... ], - ... failure=20.0, - ... anytime=None, + ... any_day=False, ... ) - >>> policy = bearing.optimal_calendar_policy(calendar) + >>> policy = bearing.optimal_opportunity_policy(shuts) >>> policy.method, policy.basis, policy.period ('dp', 'exact', 364.0) >>> round(policy.cost_rate * 364, 3) @@ -609,6 +710,36 @@ class CalendarPolicy(_ResultMapping): threshold_only: bool settings: Dict[str, Any] = field(default_factory=dict) life: Optional[dict] = None + discount_rate: float = 0.0 + npv: float = math.inf + eac: Optional[float] = None + + @property + def prices(self): + """How the opportunities were priced for the part + ([`OpportunityPrices`][repyability.OpportunityPrices]): each + opportunity's price and where it came from, any other day's and a + failure's, and the opportunities not used and why. None where + the policy was not worked out from opportunities.""" + return self.__dict__.get("_prices") + + def to_dict(self) -> dict: + """The result as plain data, ready for ``json.dumps``, with its + ``prices`` where it has them. + + Returns + ------- + dict + The fields, as plain data. + """ + out = super().to_dict() + if self.prices is not None: + out["prices"] = self.prices.to_dict() + return out + + def __post_init__(self): + if self.eac is None: + object.__setattr__(self, "eac", self.cost_rate) def _bind(self, table, names, grid=None, oldest=None) -> "CalendarPolicy": object.__setattr__(self, "_table", table) @@ -807,13 +938,25 @@ def optimal_calendar_policy( tail="repeat", mc_samples=64, seed=None, + discount_rate=0.0, + horizon=None, ) -> CalendarPolicy: """The work of ``NonRepairable.optimal_calendar_policy`` (see - there).""" + there). ``horizon`` (a model time) takes the lowest net present cost + to it instead of the long run (``_horizon.model_horizon_policy``).""" + from repyability.maintenance._horizon import ( + model_horizon_policy, + ready_model_text, + ) + from repyability.maintenance._options import ( + discount_rate as _discount_rate, + ) + if not isinstance(calendar, Calendar): raise TypeError(f"calendar must be a Calendar; got {calendar!r}.") checks.one_of("method", method, METHODS) checks.one_of("tail", tail, TAILS) + rate = _discount_rate(discount_rate) if max_age is not None and not ( checks.is_number(max_age) and 0.0 < float(max_age) < math.inf ): @@ -835,6 +978,27 @@ def optimal_calendar_policy( ) dated = not calendar.periodic life = _saved_life(part) + if horizon is not None: + end = _horizon_time(horizon) + if method not in ("auto", "dp"): + raise ValueError( + "A horizon is its own route, a backward sweep on the grid " + "over every opportunity as it falls: give horizon= with " + f"method='auto' (or 'dp'), not method={method!r}." + ) + return model_horizon_policy( + part, + calendar, + anytime, + failure, + _resolve_step(step, calendar, part), + None if max_age is None else float(max_age), + end, + rate, + life, + ) + if rate > 0.0: + _require_discountable(calendar, method, rate, part) if method == "integration": from repyability.maintenance._integration import integrated_policy @@ -845,7 +1009,13 @@ def optimal_calendar_policy( f"{anytime:g}): use method='dp', or anytime=None." ) return integrated_policy( - part, calendar, failure, max_age=max_age, tail=tail, life=life + part, + calendar, + failure, + max_age=max_age, + tail=tail, + life=life, + discount_rate=rate, ) step = _resolve_step(step, calendar, part) ages = _Ages(part, step, None if max_age is None else float(max_age)) @@ -853,19 +1023,35 @@ def optimal_calendar_policy( names = grid.names settle = _settle(grid, ages) short = grid.cycle is not None and grid.cycle <= MAX_CYCLE + if rate > 0.0: + if not short: + raise NotImplementedError( + f"{_long_cycle_words(grid)}, too long to discount over " + "exactly. Give " + + ready_model_text(rate, ages.span, _cycle_time(grid)) + + ": the lowest net present cost to then, on every " + "opportunity as it falls; or give opportunities whose " + "periods share a shorter cycle." + ) + return _cycle_policy(grid, ages, failure, names, life, rate) if method == "auto": method = "sampling" if (not dated and not short) else "dp" if method == "sampling": - warnings.warn( - f"The calendar repeats only after {grid.cycle:,} steps of " - f"the grid, more than {MAX_CYCLE:,}, so the cost rate is " - f"sampled over mc_samples ({mc_samples}) windows of it, " - "each an exact solve that may take a second or more: " - "mc_samples sets the cost, and cost_rate_se says how close " - "the rate is; the rates by kind are estimates with no " - "standard error. method='dp' differences one long horizon " - "instead.", - stacklevel=outside_level(), + from repyability.utils.deprecation import refuses_from + + refuses_from( + f"{_long_cycle_words(grid)}, too long to work out exactly, " + "so method='auto' samples the cost rate over mc_samples " + f"({mc_samples}) windows of it, each an exact solve that may " + "take a second or more (cost_rate_se says how close the rate " + "is; the rates by kind are estimates with no standard " + "error).", + "give " + + ready_model_text( + 0.0, ages.span, _cycle_time(grid), step=grid.step + ) + + ", the lowest total cost to then, worked out exactly; or " + "method='sampling' for this estimate.", ) if method == "sampling": if dated: @@ -906,15 +1092,87 @@ def _saved_life(part) -> Optional[dict]: return None -def _cycle_policy(grid, ages, failure, names, life) -> CalendarPolicy: +def _horizon_time(horizon) -> float: + """A horizon in model time, checked: a number more than 0.""" + if not (checks.is_number(horizon) and 0.0 < float(horizon) < math.inf): + raise ValueError( + "horizon must be a time in the calendar's own time (a number " + f"more than 0) for opportunities in model time; got {horizon!r}." + ) + return float(horizon) + + +def _span(part) -> float: + """The age the part outlives with a chance of ``SPAN``.""" + sf = _survival(part) + return _age_where(sf, SPAN, _mean(part, sf)) + + +def _cycle_time(grid: _Grid) -> Optional[float]: + return None if grid.cycle is None else grid.cycle * grid.step + + +def _long_cycle_words(grid: _Grid) -> str: + return ( + f"The calendar repeats only after {grid.cycle:,} steps of the grid " + f"({_cycle_time(grid):,.6g} in its time), more than {MAX_CYCLE:,}" + ) + + +def _require_discountable(calendar, method, rate: float, part) -> None: + """Refuse, with a ready horizon to give instead, a calendar or method + whose long run is not discounted exactly here.""" + from repyability.maintenance._horizon import ready_model_text + + end = None if calendar.periodic else calendar.plan_end + ready = ready_model_text(rate, _span(part), end=end) + if method == "sampling": + raise NotImplementedError( + "method='sampling' estimates a long-run average from sampled " + "windows, not a present value from now, so it takes no " + f"discount_rate. Give {ready}: the lowest net present cost to " + "then; or method='dp' (or 'auto') where the calendar repeats on " + "a short cycle; or leave discount_rate at 0." + ) + if not calendar.periodic: + raise NotImplementedError( + "A calendar of given dates does not repeat, so there is no long " + f"run to discount over exactly. Give {ready}: the lowest net " + "present cost to then, on the dates as given and nothing " + "assumed after them; or leave discount_rate at 0 (the long-run " + "average, the plan repeated past its last date)." + ) + + +def _cycle_policy( + grid, ages, failure, names, life, rate: float = 0.0 +) -> CalendarPolicy: + """A periodic calendar of a short cycle: relative value iteration over + it, or with a discount ``rate`` (continuous, a unit of the calendar's + time) discounted value iteration, the policy chosen then priced + undiscounted too (its long-run cost rate and rates by kind).""" costs, kinds = grid.prices(0, grid.cycle) - cycle = _relative_values(costs, ages, failure) + discounted = None + if rate > 0.0: + discounted = _discounted_values(costs, ages, failure, rate) + cycle = _relative_values(costs, ages, failure, fixed=discounted.first) + cycle.first, cycle.upper = discounted.first, discounted.upper + else: + cycle = _relative_values(costs, ages, failure) _warn_not_threshold(cycle.upper) replaced, failures = _stationary(cycle.first, ages) length = grid.cycle * grid.step rates, spent = _summary( names, grid.anytime, kinds, costs, replaced, failures, failure, length ) + extra: Dict[str, Any] = {} + if discounted is not None: + npv = float(discounted.values[0]) + extra = { + "discount_rate": rate, + "npv": npv, + "eac": rate * npv, + } policy = CalendarPolicy( cost_rate=cycle.rate, cost_rate_se=None, @@ -932,8 +1190,18 @@ def _cycle_policy(grid, ages, failure, names, life) -> CalendarPolicy: "cost_rate_bounds": (cycle.low, cycle.high), "cycle_steps": grid.cycle, "max_age": ages.size * ages.step, + **( + {} + if discounted is None + else { + "discounted_sweeps": discounted.sweeps, + "discounted_converged": discounted.converged, + "npv_bounds": (discounted.low, discounted.high), + } + ), }, life=life, + **extra, ) table = _CycleTable(cycle.first, kinds, replaced) return policy._bind(table, names, grid, ages.size * ages.step) @@ -1196,9 +1464,31 @@ def _rule_prices(grid: _Grid, rule: dict, start: int, n: int): def calendar_policy_cost( - part, calendar, rule, *, step=None, max_age=None, tail="repeat" + part, + calendar, + rule, + *, + step=None, + max_age=None, + tail="repeat", + discount_rate=0.0, + horizon=None, ) -> float: - """The work of ``NonRepairable.calendar_policy_cost`` (see there).""" + """The work of ``NonRepairable.calendar_policy_cost`` (see there): + the rule's long-run cost rate; with ``discount_rate``, its equivalent + cost a unit of time over the discounted long run (a periodic + calendar of a short cycle: discounted value iteration with the + decisions fixed); with ``horizon``, its net present cost to then (the + plain total at rate 0).""" + from repyability.maintenance._horizon import ( + model_horizon_rule_cost, + ready_model_text, + ) + from repyability.maintenance._options import ( + discount_rate as _discount_rate, + ) + + rate = _discount_rate(discount_rate) if not isinstance(calendar, Calendar): raise TypeError(f"calendar must be a Calendar; got {calendar!r}.") checks.one_of("tail", tail, TAILS) @@ -1227,11 +1517,47 @@ def calendar_policy_cost( "allow (its anytime is None)." ) step = _resolve_step(step, calendar, part) + if horizon is not None: + return model_horizon_rule_cost( + part, + calendar, + anytime, + failure, + step, + None if max_age is None else float(max_age), + rule, + _horizon_time(horizon), + rate, + ) ages = _Ages(part, step, None if max_age is None else float(max_age)) dated = not calendar.periodic grid = _Grid(calendar, anytime, step, tail="repeat" if dated else None) - if grid.cycle is not None and grid.cycle <= MAX_CYCLE: - costs, first = _rule_prices(grid, rule, grid.cycle_start, grid.cycle) + short = grid.cycle is not None and grid.cycle <= MAX_CYCLE + if rate > 0.0: + if dated or not short: + what = ( + "A calendar of given dates does not repeat" + if dated + else f"{_long_cycle_words(grid)}" + ) + ready = ready_model_text( + rate, + ages.span, + end=calendar.plan_end if dated else None, + ) + raise NotImplementedError( + f"{what}, so a rule's discounted long run is not priced " + f"exactly. Give {ready}: the rule's net present cost to " + "then; or leave discount_rate at 0." + ) + cycle = cast(int, grid.cycle) + costs, first = _rule_prices(grid, rule, 0, cycle) + values = _discounted_values(costs, ages, failure, rate, fixed=first) + return rate * float(values.values[0]) + if short: + costs, first = _rule_prices( + grid, rule, grid.cycle_start, cast(int, grid.cycle) + ) return _relative_values(costs, ages, failure, fixed=first).rate settle = _settle(grid, ages) span = max(settle, 1) diff --git a/repyability/maintenance/_shutdowns.py b/repyability/maintenance/_shutdowns.py index 22aa9914..4eb6318b 100644 --- a/repyability/maintenance/_shutdowns.py +++ b/repyability/maintenance/_shutdowns.py @@ -251,6 +251,87 @@ def _gap_words(n: int, unit: str) -> str: return f"{n} {unit[:-1] if n == 1 else unit}" +def check_when( + label: str, + name: str, + *, + rule=None, + dates=None, + then_every=None, + every=None, + also_every=None, + at=None, +): + """When a shut on real dates happens, checked: one of a ``rule``, + ``dates`` or ``every``, with what goes with each. ``label`` starts + each message (``"Shutdown 'weekly stop'"``), ``name`` names a bad + date. Returns the dates (in + order, once each), ``every`` (a number as a float) and ``at`` (a + clock time), as kept.""" + from repyability.schedule import Recurrence, Usage + from repyability.schedule._meters import clock + + given = [ + k + for k, v in (("rule", rule), ("dates", dates), ("every", every)) + if v is not None + ] + if len(given) != 1: + raise ValueError( + f"{label}: give when it happens one way: a " + "rule (a Recurrence), dates, or every= (a period such as " + "'30 days', or a Usage)." + ) + if rule is not None and not isinstance(rule, Recurrence): + raise TypeError( + f"{label}: rule must be a Recurrence " + f"(Recurrence.weekly('Sat'), ...); got {rule!r}." + ) + if dates is not None: + if isinstance(dates, (str, date)) or not hasattr(dates, "__iter__"): + raise TypeError( + f"{label}: dates must be a list of dates; got {dates!r}." + ) + days = sorted({_iso_date(d, f"A date of {name!r}") for d in dates}) + if not days: + raise ValueError(f"{label}: dates must have at least one.") + dates = tuple(days) + if then_every is not None: + if dates is None: + raise ValueError( + f"{label}: then_every is the gap after " + "the last of its dates: give dates= too." + ) + _gap(then_every, f"{label}: then_every") + if every is not None: + if isinstance(every, Usage): + pass + elif checks.is_number(every): + if not 0.0 < float(every) < math.inf: + raise ValueError( + f"{label}: every must be more than 0; got {every!r}." + ) + every = float(every) + else: + _period_hours(every, f"{label}: every") + if also_every is not None: + if not isinstance(every, Usage): + raise ValueError( + f"{label}: also_every is a calendar limit " + "on a shut by use (every=Usage(...)), whichever comes " + "first." + ) + _period_hours(also_every, f"{label}: also_every") + if at is not None: + if isinstance(every, Usage): + raise ValueError( + f"{label}: a shut by use falls when the " + "meter gets there, so it takes no clock time (at=)." + ) + at = clock(at, "at") + return dates, every, at + + # ---------------------------------------------------------------- records @@ -279,7 +360,7 @@ class Shutdown: dates : list of date or str, optional Its fixed dates, instead of a rule. A policy uses them as dated (never averaged): see - [`NonRepairable.optimal_calendar_policy`][repyability.NonRepairable.optimal_calendar_policy]. + [`NonRepairable.optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy]. then_every : str, optional With ``dates``: the gap at which the kind recurs after its last date (``"4 years"``, ``"18 months"``, ``"6 weeks"``, ``"90 @@ -302,7 +383,7 @@ class Shutdown: Examples -------- - >>> from repyability import Shutdown + >>> from repyability.maintenance._shutdowns import Shutdown >>> from repyability.schedule import Recurrence >>> Shutdown("weekly stop", Recurrence.weekly("Sat"), replace_cost=3.0, ... duration="8h").describe() @@ -323,9 +404,6 @@ class Shutdown: at: Optional[time] = None def __post_init__(self): - from repyability.schedule import Recurrence, Usage - from repyability.schedule._meters import clock - if not isinstance(self.name, str) or not self.name.strip(): raise TypeError(f"A shut's name must be text; got {self.name!r}.") if self.name in (ANYTIME, "failure", "any other day"): @@ -334,71 +412,19 @@ def __post_init__(self): "replacement on any other day, or a failure): give the shut " "another name." ) - given = [ - k - for k, v in ( - ("rule", self.rule), - ("dates", self.dates), - ("every", self.every), - ) - if v is not None - ] - if len(given) != 1: - raise ValueError( - f"Shutdown {self.name!r}: give when it happens one way: a " - "rule (a Recurrence), dates, or every= (a period such as " - "'30 days', or a Usage)." - ) - if self.rule is not None and not isinstance(self.rule, Recurrence): - raise TypeError( - f"Shutdown {self.name!r}: rule must be a Recurrence " - f"(Recurrence.weekly('Sat'), ...); got {self.rule!r}." - ) - if self.dates is not None: - if isinstance(self.dates, (str, date)) or not hasattr( - self.dates, "__iter__" - ): - raise TypeError( - f"Shutdown {self.name!r}: dates must be a list of dates; " - f"got {self.dates!r}." - ) - days = sorted( - {_iso_date(d, f"A date of {self.name!r}") for d in self.dates} - ) - if not days: - raise ValueError( - f"Shutdown {self.name!r}: dates must have at least one." - ) - object.__setattr__(self, "dates", tuple(days)) - if self.then_every is not None: - if self.dates is None: - raise ValueError( - f"Shutdown {self.name!r}: then_every is the gap after " - "the last of its dates: give dates= too." - ) - _gap(self.then_every, f"Shutdown {self.name!r}: then_every") - if self.every is not None: - if isinstance(self.every, Usage): - pass - elif checks.is_number(self.every): - if not 0.0 < float(self.every) < math.inf: - raise ValueError( - f"Shutdown {self.name!r}: every must be more than 0; " - f"got {self.every!r}." - ) - object.__setattr__(self, "every", float(self.every)) - else: - _period_hours(self.every, f"Shutdown {self.name!r}: every") - if self.also_every is not None: - if not isinstance(self.every, Usage): - raise ValueError( - f"Shutdown {self.name!r}: also_every is a calendar limit " - "on a shut by use (every=Usage(...)), whichever comes " - "first." - ) - _period_hours( - self.also_every, f"Shutdown {self.name!r}: also_every" - ) + dates, every, at = check_when( + f"Shutdown {self.name!r}", + self.name, + rule=self.rule, + dates=self.dates, + then_every=self.then_every, + every=self.every, + also_every=self.also_every, + at=self.at, + ) + object.__setattr__(self, "dates", dates) + object.__setattr__(self, "every", every) + object.__setattr__(self, "at", at) if not ( checks.is_number(self.replace_cost) and 0.0 <= float(self.replace_cost) < math.inf @@ -409,13 +435,6 @@ def __post_init__(self): ) object.__setattr__(self, "replace_cost", float(self.replace_cost)) object.__setattr__(self, "duration", _duration(self.duration)) - if self.at is not None: - if isinstance(self.every, Usage): - raise ValueError( - f"Shutdown {self.name!r}: a shut by use falls when the " - "meter gets there, so it takes no clock time (at=)." - ) - object.__setattr__(self, "at", clock(self.at, "at")) def __init__( self, @@ -560,7 +579,7 @@ class Shutdowns: site's time zone. The same record gives a part's replacement policy its cheap moments - ([`NonRepairable.optimal_calendar_policy`][repyability.NonRepairable.optimal_calendar_policy]) + ([`NonRepairable.optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy]) and a diagram its outages (``on_diagram``). A failure is not priced here: it costs the part's own ``unplanned_cost`` everywhere. @@ -577,7 +596,7 @@ class Shutdowns: Examples -------- - >>> from repyability import Shutdown, Shutdowns + >>> from repyability.maintenance._shutdowns import Shutdown, Shutdowns >>> from repyability.schedule import Recurrence >>> site = Shutdowns( ... [ @@ -734,31 +753,31 @@ def route( The part. plan : optional As for - [`NonRepairable.optimal_calendar_policy`][repyability.NonRepairable.optimal_calendar_policy]. + [`NonRepairable.optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy]. method : optional As for - [`NonRepairable.optimal_calendar_policy`][repyability.NonRepairable.optimal_calendar_policy]. + [`NonRepairable.optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy]. horizon : optional As for - [`NonRepairable.optimal_calendar_policy`][repyability.NonRepairable.optimal_calendar_policy]. + [`NonRepairable.optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy]. discount : optional As for - [`NonRepairable.optimal_calendar_policy`][repyability.NonRepairable.optimal_calendar_policy]. + [`NonRepairable.optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy]. now : optional As for - [`NonRepairable.optimal_calendar_policy`][repyability.NonRepairable.optimal_calendar_policy]. + [`NonRepairable.optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy]. readings : optional As for - [`NonRepairable.optimal_calendar_policy`][repyability.NonRepairable.optimal_calendar_policy]. + [`NonRepairable.optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy]. unit : optional As for - [`NonRepairable.optimal_calendar_policy`][repyability.NonRepairable.optimal_calendar_policy]. + [`NonRepairable.optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy]. failure_timing : optional As for - [`NonRepairable.optimal_calendar_policy`][repyability.NonRepairable.optimal_calendar_policy]. + [`NonRepairable.optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy]. dated_until : optional As for - [`NonRepairable.optimal_calendar_policy`][repyability.NonRepairable.optimal_calendar_policy]. + [`NonRepairable.optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy]. Returns ------- @@ -926,7 +945,7 @@ def from_dict(cls, data: dict) -> "Shutdowns": @dataclass(frozen=True) class ShutdownRoute(_ResultMapping): """How a policy at a site will be worked out: returned by - [`Shutdowns.route`][repyability.Shutdowns.route]. + [`Opportunities.route`][repyability.Opportunities.route]. Attributes ---------- @@ -1803,12 +1822,10 @@ def _decide( ) site = layout.site part = layout.part - if horizon is not None or discount is not None: - if horizon is None: - raise ValueError( - "discount= goes with horizon=: give the last day the costs " - "count to as well." - ) + long_discount = None + if horizon is None and discount is not None: + long_discount = _long_run_discount(layout, discount, method) + elif horizon is not None: if discount is None: raise ValueError( "horizon= needs discount= too: the yearly rate future costs " @@ -1910,10 +1927,26 @@ def _decide( failure_timing=failure_timing, refuse=refuse, dated_until=dated_until, + discount=long_discount, ) if dated is not None: return dated if not site.shutdowns: + if long_discount is not None: + return _Decision( + "exact", + "No shuts: this is plain age replacement, at the age with " + "the least equivalent annual cost at " + f"{_percent(long_discount)} a year (Fox, 1966; one " + "discounted integral of the part's survival an age).", + "closed form", + 0.01, + cycle=None, + discount=long_discount, + failure_timing=None, + why="there are no shuts, so this is plain age replacement", + how="by Fox's formula (closed form)", + ) return _Decision( "exact", "No shuts: this is plain age replacement (exact long-run " @@ -1952,11 +1985,21 @@ def _decide( else: patterns[kind.name] = pattern if broken: + from repyability.maintenance._horizon import ready_site_text + + ready = ready_site_text(layout, long_discount) choice = ( "Choose method='averaged' (assumes shuts fall evenly within their " - "usual gaps) or give horizon= and discount= (lowest net present " - "cost on the real dates)." + f"usual gaps) or give {ready}: the lowest total cost on the real " + "dates to then, worked out exactly." ) + if long_discount is not None: + choice = ( + "A discounted long run needs shuts that repeat, so that the " + f"same cycle comes round again. Give {ready}: the lowest net " + "present cost on the real dates to then, and its equivalent " + "annual cost; or leave discount= out for method='averaged'." + ) reason = ( "These shuts don't repeat on a fixed cycle in the part's clock: " f"{_listed(broken)}." @@ -1965,7 +2008,8 @@ def _decide( raise ValueError( f"{reason} So there is no repeating cycle to " f"{'be exact over' if method == 'exact' else 'sample'}: use " - "method='averaged' or a horizon (horizon= and discount=)." + f"method='averaged', or give {ready}, the lowest cost on the " + "real dates to then." ) if refuse: raise ValueError(f"{reason} {choice}") @@ -2019,22 +2063,25 @@ def _decide( "failure_timing='half_step' (the default), which gives the same " "to about 1e-7." ) - how = ( - "by quadrature (the part's life integrated across each gap between " - "shuts, failures timed at the instant they happen)" - if failure_timing == "exact" - else "on a grid of steps sized from the life, each failure's " - "replacement counted half a step old" - ) + how = how_words(failure_timing) + lead = "Exact long-run average" + if long_discount is not None: + lead = ( + "Lowest equivalent annual cost at " + f"{_percent(long_discount)} a year, discounted over the long run " + "(the present value of every replacement from now on, forever, " + "by discounted value iteration over the cycle)" + ) if short: return _Decision( "exact", - f"Exact long-run average: {repeat}, so nothing about shut timing " + f"{lead}: {repeat}, so nothing about shut timing " f"is assumed; worked out {how}.", solver, seconds, patterns=patterns, cycle=cycle, + discount=long_discount, failure_timing=failure_timing, why=f"{repeat}, so nothing about shut timing is assumed", how=how, @@ -2046,29 +2093,107 @@ def _decide( if method == "exact": return _Decision( "exact_long_cycle", - f"Exact long-run average over a long cycle ({repeat}), worked out " + f"{lead} over a long cycle ({repeat}), worked out " f"{how}: {_seconds_text(seconds)}.", solver, seconds, patterns=patterns, cycle=cycle, + discount=long_discount, failure_timing=failure_timing, why=f"over a long cycle: {repeat}", how=how, ) + from repyability.maintenance._horizon import ready_site_text + + pace = layout.pace() + ready = ready_site_text( + layout, long_discount, None if not pace else cycle / pace, step + ) choice = ( f"{long_text} Choose method='exact' (the same calculation, " - f"{_seconds_text(seconds)}) or method='sampling' (an estimate with " - "its " - "standard error, as many samples as you ask for)." + f"{_seconds_text(seconds)}), method='sampling' (an estimate with " + "its standard error, as many samples as you ask for), or give " + f"{ready}: the lowest total cost on the real dates to then." ) + if long_discount is not None: + choice = ( + f"{long_text} Discounted, choose method='exact' (the same " + f"calculation, {_seconds_text(seconds)}), or give {ready}: the " + "lowest net present cost on the real dates to then; sampling " + "gives a long-run average, not a present value." + ) if refuse: raise ValueError(choice) return _Decision( - "long_cycle", choice, None, None, patterns=patterns, cycle=cycle + "long_cycle", + choice, + None, + None, + patterns=patterns, + cycle=cycle, + discount=long_discount, + ) + + +def how_words(failure_timing) -> str: + """How the exact routes work a cycle out, in words.""" + if failure_timing == "exact": + return ( + "by quadrature (the part's life integrated across each gap " + "between shuts, failures timed at the instant they happen)" + ) + return ( + "on a grid of steps sized from the life, each failure's " + "replacement counted half a step old" ) +def _percent(rate: float) -> str: + """A yearly rate in words: ``7%``, ``2.5%``.""" + return f"{100.0 * rate:.4g}%" + + +def _long_run_discount(layout: _Layout, discount, method) -> Optional[float]: + """The yearly discount of a discounted long run (``discount=`` with no + horizon), checked: None for 0 (the long-run average). Refused where + the long run is not discounted exactly: the averaged and sampled + routes (long-run averages), a duty plan (a clock that does not keep a + steady pace with the calendar) and a clock with no pace in time.""" + if not (checks.is_number(discount) and 0.0 <= float(discount) < 10.0): + raise ValueError( + "discount must be a yearly rate such as 0.07 (7%), at least " + f"0; got {discount!r}." + ) + rate = float(discount) + if rate == 0.0: + return None + from repyability.maintenance._horizon import ready_site_text + + if method in ("averaged", "sampling"): + raise ValueError( + f"method={method!r} gives a long-run average, which is not " + "discounted: leave method out (or give method='exact') with " + f"discount=, or give {ready_site_text(layout, rate)}: the " + "lowest net present cost on the real dates to then." + ) + if layout.plan is not None: + raise ValueError( + "A discounted long run needs the part's clock to keep a steady " + "pace with the calendar, and a duty plan's does not. Give " + f"{ready_site_text(layout, rate)}: the lowest net present cost " + "on the real dates to then, through the plan, and its " + "equivalent annual cost; or leave discount= out." + ) + if layout.pace() is None: + raise ValueError( + f"The part's clock ({layout.unit}) has no pace in time, so a " + "yearly discount is no rate on it: give a duty plan with " + "horizon= and discount=, or leave discount= out." + ) + return rate + + def _exact_step( patterns: Dict[str, _Pattern], cycle: float, mean: float ) -> float: diff --git a/repyability/maintenance/_site_policy.py b/repyability/maintenance/_site_policy.py index 1dcacc38..757b1fce 100644 --- a/repyability/maintenance/_site_policy.py +++ b/repyability/maintenance/_site_policy.py @@ -148,7 +148,7 @@ def __str__(self) -> str: class RuleCost(_ResultMapping): """What a given rule costs at a site, and how that was worked out: returned by - [`NonRepairable.calendar_policy_cost`][repyability.NonRepairable.calendar_policy_cost] + [`NonRepairable.opportunity_policy_cost`][repyability.NonRepairable.opportunity_policy_cost] with a site, and listed by [`ShutdownPolicy.compare`][repyability.ShutdownPolicy.compare]. @@ -178,11 +178,21 @@ class RuleCost(_ResultMapping): the horizon, for a horizon; per unit of the part's clock where it has no pace). cost_rate : float - The long-run cost a unit of the part's clock (routes 1-3). + The long-run cost a unit of the part's clock (routes 1-3), + undiscounted. dated_cost : float or None For a dated window: the expected cost of a new part and its successors to the window's end (``cost`` is the long run's after - it). + it); with a discount, its present value. + npv : float or None + With a discount: the present value now of every replacement under + the rule, from a new part put in now: forever, over a discounted + long run (``cost`` is then its equivalent annual cost, ``measure`` + ``"equivalent annual cost"``); to the horizon, for a horizon. + eac : float or None + The equivalent annual cost, the steady cost a year worth ``npv``: + over a discounted long run, ``cost``; for a horizon, its net + present cost spread over its years (at 0%, the total over them). """ name: str @@ -197,14 +207,39 @@ class RuleCost(_ResultMapping): replacements_by_kind: Dict[str, float] cost_rate: Optional[float] dated_cost: Optional[float] = None + npv: Optional[float] = None + eac: Optional[float] = None + + @property + def prices(self): + """How the opportunities were priced for the part + ([`OpportunityPrices`][repyability.OpportunityPrices]): each + opportunity's price and where it came from, any other day's and a + failure's, and the opportunities not used and why. None where + the policy was not worked out from opportunities.""" + return self.__dict__.get("_prices") + + def to_dict(self) -> dict: + """The result as plain data, ready for ``json.dumps``, with its + ``prices`` where it has them. + + Returns + ------- + dict + The fields, as plain data. + """ + out = super().to_dict() + if self.prices is not None: + out["prices"] = self.prices.to_dict() + return out @dataclass(frozen=True) class ShutdownPolicy(_ResultMapping): """The best replacement rule for a part at a site whose shuts are on real dates, what it costs, and how that was worked out. Returned by - [`NonRepairable.optimal_calendar_policy`][repyability.NonRepairable.optimal_calendar_policy] - given a [`Shutdowns`][repyability.Shutdowns]. + [`NonRepairable.optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy] + given [`Opportunities`][repyability.Opportunities] on real dates. Attributes ---------- @@ -257,6 +292,25 @@ class ShutdownPolicy(_ResultMapping): For ``"dated_then_long_run"``: the long run's route. long_run_solver : str or None For ``"dated_then_long_run"``: the long run's solver. + discount : float or None + The yearly discount rate of a discounted long run (``discount=`` + with no horizon; None otherwise, and for a horizon, whose rate is + in its text). ``cost`` is then the equivalent annual cost + (``measure`` ``"equivalent annual cost"``): the present value of + every replacement from now on, forever, spread as a steady cost a + year, ``ln(1 + discount)`` times it; ``cost_rate`` and the rates + by kind stay the long-run (undiscounted) figures of the rule + chosen. + npv : float or None + With ``discount``: the present value now of every replacement, + forever, from a new part put in now (None for a dated window, + whose ``dated_cost`` is the present value to its end). + eac : float or None + The equivalent annual cost: over a discounted long run, ``cost``; + for a horizon, its net present cost spread as a steady cost a + year over the years to it (``ln(1 + d)`` times it over ``1 - (1 + + d)^-years`` at the yearly rate ``d``; at 0%, the total over the + years). None for a long-run average. """ # Bound after construction (``_bind``), not fields: how the dates are @@ -285,6 +339,32 @@ class ShutdownPolicy(_ResultMapping): dated_cost: Optional[float] = None long_run_route: Optional[str] = None long_run_solver: Optional[str] = None + discount: Optional[float] = None + npv: Optional[float] = None + eac: Optional[float] = None + + @property + def prices(self): + """How the opportunities were priced for the part + ([`OpportunityPrices`][repyability.OpportunityPrices]): each + opportunity's price and where it came from, any other day's and a + failure's, and the opportunities not used and why. None where + the policy was not worked out from opportunities.""" + return self.__dict__.get("_prices") + + def to_dict(self) -> dict: + """The result as plain data, ready for ``json.dumps``, with its + ``prices`` where it has them. + + Returns + ------- + dict + The fields, as plain data. + """ + out = super().to_dict() + if self.prices is not None: + out["prices"] = self.prices.to_dict() + return out def _bind(self, engine, layout, decision) -> "ShutdownPolicy": object.__setattr__(self, "_engine", engine) @@ -366,12 +446,23 @@ def schedule( def compare(self) -> List[RuleCost]: """The same site under simpler rules, priced the same way, for context: run to failure, age replacement on any day (where the - site allows one), and every shut of each kind.""" + site allows one; at the age with the least equivalent annual cost + for a discounted long run), and every shut of each kind. A + discounted long run prices each rule's discounted long run + exactly (its equivalent annual cost), as the policy's own.""" layout = self._layout part = layout.part rules: List[Tuple[str, Dict[str, float]]] = [("run to failure", {})] + decision = self._decision if layout.site.any_day is not None: - best = _age_replacement(part, layout.site.any_day) + discount = ( + None if decision.route == "horizon" else decision.discount + ) + best = _age_replacement( + part, + layout.site.any_day, + model_rate(layout, discount) if discount else 0.0, + ) rules.append( ( f"age replacement on any day at {_number(best)}", @@ -537,7 +628,7 @@ def _expanded(layout: _Layout, patterns) -> Calendar: for i, offset in enumerate(offsets): name = kind.name if len(offsets) == 1 else f"{kind.name}{_PART}{i}" opportunities.append( - Opportunity( + Opportunity._at_price( name, kind.price, period=pattern.period, offset=offset ) ) @@ -561,10 +652,13 @@ def _exact(layout: _Layout, decision: _Decision, mc_samples, seed): calendar = _expanded(layout, decision.patterns) failure, anytime = calendar._prices(part) life = R._saved_life(part) + rate = model_rate(layout, decision.discount) if decision.failure_timing == "exact" and decision.route != "sampling": _warn_slow(decision) try: - return integrated_policy(part, calendar, failure, life=life) + return integrated_policy( + part, calendar, failure, life=life, discount_rate=rate + ) except NotImplementedError as error: raise ValueError( f"failure_timing='exact' is refused here ({error}): use " @@ -609,7 +703,19 @@ def _exact(layout: _Layout, decision: _Decision, mc_samples, seed): f"exactly takes {_seconds_text(decision.seconds or 0.0)}.", stacklevel=outside_level(), ) - return R._cycle_policy(grid, ages, failure, grid.names, life) + return R._cycle_policy(grid, ages, failure, grid.names, life, rate) + + +def model_rate(layout: _Layout, discount: Optional[float]) -> float: + """A yearly discount as a continuous rate a unit of the part's clock, + which keeps a steady pace with the calendar (``_shutdowns. + _long_run_discount`` refuses one that does not): ``ln(1 + discount)`` + over the units a year. 0 for none.""" + if not discount: + return 0.0 + pace = layout.pace() + assert pace is not None + return math.log1p(float(discount)) / pace def _warn_slow(decision: _Decision) -> None: @@ -933,20 +1039,45 @@ def _averaged_model(layout: _Layout) -> _Averaged: return _Averaged(part, kinds, layout.site.any_day, part.cu) -def _age_replacement(part, price: float) -> float: - """The best age to replace the part on any day at ``price``.""" +def _age_replacement(part, price: float, rate: float = 0.0) -> float: + """The best age to replace the part on any day at ``price``: of the + long-run cost rate, or with a continuous discount ``rate`` a unit of + its clock, of the equivalent annual cost (Fox, 1966).""" + if rate > 0.0: + from repyability.maintenance._options import discounted_optimum + + best, _ = discounted_optimum(part, rate, float(price), float(part.cu)) + return float(best) model = _Averaged(part, [], price, part.cu) _, a0, _ = model.optimise() return math.inf if a0 is None else float(a0) +def _age_replacement_eac(part, price: float, age: float, rate: float): + """The equivalent annual cost (a unit of the part's clock) of + replacing the part on any day at ``price`` once ``age`` old, at the + continuous discount ``rate`` (Fox, 1966); running to failure for an + ``age`` of ``inf``.""" + from repyability.maintenance._options import ( + _cycle_value, + discounted_run_to_failure, + ) + + if not math.isfinite(age): + return discounted_run_to_failure(part, rate, float(part.cu)) + if age <= 0.0: + return math.inf + cycle, length = _cycle_value(part, age, rate, float(price), part.cu) + return cycle / length + + # ------------------------------------------------------------ grid helpers def _dated_calendar(layout: _Layout, end: float) -> Calendar: times = _KindTimes(layout).upto(end) opportunities = [ - Opportunity(k.name, k.price, dates=tuple(times[k.name])) + Opportunity._at_price(k.name, k.price, dates=tuple(times[k.name])) for k in layout.kinds if times[k.name].size ] @@ -954,11 +1085,14 @@ def _dated_calendar(layout: _Layout, end: float) -> Calendar: class _FixedTable: - """Fixed thresholds by grid index (from 0, none past the end).""" + """Fixed thresholds by grid index (from 0, none past the end), and + the chance of a planned replacement at each from a new part at 0 + where it is known (``chance``; else 0).""" - def __init__(self, first, kinds): + def __init__(self, first, kinds, chance=None): self.first, self.kinds = np.asarray(first), np.asarray(kinds) self.horizon = max(int(self.first.size), 1) + self.chance = None if chance is None else np.asarray(chance, float) def at(self, index): index = np.asarray(index, np.int64) @@ -970,7 +1104,11 @@ def at(self, index): return first, kinds def chances(self, n): - return np.zeros(n) + out = np.zeros(n) + if self.chance is not None: + m = min(n, self.chance.size) + out[:m] = self.chance[:m] + return out def _dated_grid_policy(layout: _Layout, rule: Dict[str, float], end: float): @@ -1040,6 +1178,10 @@ def _dated_grid_policy(layout: _Layout, rule: Dict[str, float], end: float): # --------------------------------------------------------- building results +#: The measure of a discounted long run's figure. +EAC = "equivalent annual cost" + + def _measure(layout: _Layout) -> Tuple[Optional[float], str]: pace = layout.pace() if pace is None: @@ -1049,7 +1191,7 @@ def _measure(layout: _Layout) -> Tuple[Optional[float], str]: def _figure(measure: str, cost: float, se: Optional[float]) -> str: - if measure == "cost per year": + if measure in ("cost per year", EAC): money = _money(round(cost, 2)) if cost >= 0.01 else f"${cost:.3g}" text = f"{money} a year" else: @@ -1132,6 +1274,7 @@ def _policy_for( inner = _exact(layout, decision, mc_samples, seed) engine: Any = _InnerEngine(inner, layout) rate = float(inner.cost_rate) + eac, npv = float(cast(float, inner.eac)), float(inner.npv) se = inner.cost_rate_se rates = _merged(inner.replacement_rates) thresholds = _inner_thresholds(inner, names) @@ -1144,6 +1287,20 @@ def _policy_for( else: model = _averaged_model(layout) a, a0, rate = model.optimise() + eac, npv = rate, math.inf + if decision.discount: + # No shuts (a discounted long run refuses the averaged route): + # age replacement on any day at the least equivalent annual + # cost, its long-run figures those of the age chosen. + from repyability.maintenance._options import discounted_optimum + + r = model_rate(layout, decision.discount) + best, eac = discounted_optimum( + part, r, float(cast(float, site.any_day)), float(part.cu) + ) + a0 = None if math.isinf(best) else best + rate = model.rate(a, a0) + npv = eac / r length, by_kind, anyday, failed = model.evaluate(a, a0) thresholds = { name: (float(a[k]), float(a[k])) for k, name in enumerate(names) @@ -1183,6 +1340,23 @@ def _policy_for( "usual gaps" ), }[decision.route] + discounted: Dict[str, Any] = {} + if decision.discount: + from repyability.maintenance._shutdowns import _percent + + measure = EAC + cost = eac * scale + statement = ( + f"Lowest equivalent annual cost at {_percent(decision.discount)} " + "a year, discounted over the long run" + ) + discounted = { + "discount": float(decision.discount), + "npv": npv, + "eac": float(eac * scale), + } + settings = dict(settings) + settings["long_run_cost_per_year"] = rate * scale figure = _figure(measure, cost, cost_se) if decision.route == "sampling": figure += f" ({int(mc_samples)} samples)" @@ -1214,6 +1388,7 @@ def _policy_for( notes=tuple(notes), settings=settings, life=life, + **discounted, )._bind(engine, layout, decision) @@ -1248,7 +1423,9 @@ def _named_rule(layout: _Layout, rule) -> Dict[str, float]: def _rule_cost(layout, decision, rule, name, settings) -> RuleCost: - """A fixed rule priced by the decision's route.""" + """A fixed rule priced by the decision's route: with a discount and + no horizon, its discounted long run exactly (the routes that repeat + exactly, as the policy is chosen there).""" pace, measure = _measure(layout) names = list(layout.site.names) if decision.route == "dated_then_long_run": @@ -1285,10 +1462,40 @@ def _rule_cost(layout, decision, rule, name, settings) -> RuleCost: rates["failure"] = failed / length se = None solver, timing = "closed form", None + eac = None + if decision.discount: + # No shuts (the averaged route refuses a discount): Fox's + # formula for the age on any day. + eac = _age_replacement_eac( + layout.part, + float(layout.site.any_day or 0.0), + math.inf if a0 is None else float(a0), + model_rate(layout, decision.discount), + ) else: - rate, se, rates = _grid_rule_rate(layout, decision, rule, settings) + rate, se, rates, eac = _grid_rule_rate( + layout, decision, rule, settings + ) solver, timing = decision.solver, decision.failure_timing scale = pace if pace is not None else 1.0 + if eac is not None: + r = model_rate(layout, decision.discount) + figure = float(eac * scale) + return RuleCost( + name=name, + rule=dict(rule), + cost=figure, + measure=EAC, + cost_se=None, + route=decision.route, + route_text=f"{name}: {_figure(EAC, figure, None)}", + solver=solver or "", + failure_timing=timing, + replacements_by_kind={k: v * scale for k, v in rates.items()}, + cost_rate=float(rate), + npv=float(eac / r), + eac=figure, + ) scaled_se = None if se is None else se * scale return RuleCost( name=name, @@ -1308,9 +1515,13 @@ def _rule_cost(layout, decision, rule, name, settings) -> RuleCost: def _grid_rule_rate(layout, decision, rule, settings): """A fixed rule's long-run rate on the exact routes: relative value iteration with the decisions fixed over the cycle (quadrature with - them fixed for ``failure_timing="exact"``), or sampled windows.""" + them fixed for ``failure_timing="exact"``), or sampled windows; with + a discount, also its equivalent annual cost a unit of the part's + clock (discounted value iteration with the decisions fixed; None + without).""" from repyability.maintenance import _replacement as R + rate = model_rate(layout, decision.discount) part = layout.part calendar = _expanded(layout, decision.patterns) failure, anytime = calendar._prices(part) @@ -1326,16 +1537,29 @@ def _grid_rule_rate(layout, decision, rule, settings): from repyability.maintenance._integration import integrated_policy inner = integrated_policy( - part, calendar, failure, life=None, fixed=expanded + part, + calendar, + failure, + life=None, + fixed=expanded, + discount_rate=rate, + ) + return ( + inner.cost_rate, + None, + _merged(inner.replacement_rates), + float(cast(float, inner.eac)) if rate > 0.0 else None, ) - return inner.cost_rate, None, _merged(inner.replacement_rates) step = R._resolve_step(None, calendar, part) ages = R._Ages(part, step, None) with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) grid = R._Grid(calendar, anytime, step) if decision.route == "sampling": - return _sampled_rule_rate(grid, ages, failure, expanded, settings) + return ( + *_sampled_rule_rate(grid, ages, failure, expanded, settings), + None, + ) cycle_steps = cast(int, grid.cycle) costs, first = R._rule_prices(grid, expanded, 0, cycle_steps) cycle = R._relative_values(costs, ages, failure, fixed=first) @@ -1353,7 +1577,11 @@ def _grid_rule_rate(layout, decision, rule, settings): failure, cycle_steps * step, ) - return cycle.rate, None, _merged(rates) + eac = None + if rate > 0.0: + values = R._discounted_values(costs, ages, failure, rate, fixed=first) + eac = rate * float(values.values[0]) + return cycle.rate, None, _merged(rates), eac def _rule_kinds(grid, rule, n): @@ -1541,6 +1769,10 @@ class NextReplacementOnDates(_ResultMapping): unit of the part's clock). valued_by : str Where that figure comes from, in words. + discount_rate : float + The continuous rate a unit of the part's clock each choice's cost + is discounted at: the policy's (its yearly rate at the clock's + pace, a duty plan's average), 0 for a policy with none. """ best: str @@ -1549,34 +1781,71 @@ class NextReplacementOnDates(_ResultMapping): age: float cost_rate: float valued_by: str + discount_rate: float = 0.0 -def _baseline_rate(policy: ShutdownPolicy) -> Tuple[float, str]: - """The policy's figure a unit of the part's clock, and its words.""" +def _baseline_rate(policy: ShutdownPolicy) -> Tuple[float, float, str]: + """The policy's figure a unit of the part's clock, the continuous + discount rate a unit of it its choices are discounted at (0 for + none), and its words.""" layout = policy._layout pace = layout.pace() or 1.0 + if policy.discount is not None: + r = _rate_of(layout, policy.discount) + return ( + float(policy.cost) / pace, + r, + ( + "the equivalent annual cost of the policy's discounted long " + f"run ({policy.route} route), each choice discounted at " + f"{_percent_text(policy.discount)} a year" + ), + ) if policy.route == "dated_then_long_run": - return float(cast(float, policy.cost_rate)), ( - "the long-run cost of the recurring shuts after the dated window " - f"({policy.long_run_route} route)" + return ( + float(cast(float, policy.cost_rate)), + 0.0, + ( + "the long-run cost of the recurring shuts after the dated " + f"window ({policy.long_run_route} route)" + ), ) if policy.route != "horizon": - return float(cast(float, policy.cost_rate)), ( - f"the policy's long-run cost ({policy.route} route)" + return ( + float(cast(float, policy.cost_rate)), + 0.0, + (f"the policy's long-run cost ({policy.route} route)"), ) discount = float(policy._decision.discount) - end = policy._decision.horizon - years = (end - layout.origin).total_seconds() / 3600.0 / (24 * 365.25) - if discount > 0: - yearly = policy.cost * discount / (1.0 - (1.0 + discount) ** -years) - else: - yearly = policy.cost / years - return yearly / pace, ( + words = ( "the policy's net present cost spread evenly over the years to its " - "horizon" + "horizon (its equivalent annual cost)" + ) + if discount > 0: + words += ( + f", each choice discounted at {_percent_text(discount)} a year" + ) + return ( + float(cast(float, policy.eac)) / pace, + _rate_of(layout, discount), + words, ) +def _percent_text(rate: float) -> str: + from repyability.maintenance._shutdowns import _percent + + return _percent(float(rate)) + + +def _rate_of(layout: _Layout, discount: float) -> float: + """A yearly discount as a continuous rate a unit of the part's clock, + at its average pace (a duty plan's over 28 years): 0 for none.""" + if not discount: + return 0.0 + return math.log1p(float(discount)) / (layout.pace() or 1.0) + + def next_on_dates( part, age, @@ -1623,7 +1892,7 @@ def next_on_dates( "policy's day, or work the policy out from this one." ) age = quantity(age, layout.unit, "age") - rate, valued_by = _baseline_rate(policy) + rate, discount_rate, valued_by = _baseline_rate(policy) mean = model_mean(part.reliability) held = float(np.ravel(part.reliability_function(age))[0]) if not held > 0.0: @@ -1666,6 +1935,7 @@ def lasting(u): scheduled_outages=outages, planned=site.any_day, rate=rate, + discount_rate=discount_rate, ) options = [] shut_index = 0 @@ -1729,7 +1999,7 @@ def lasting(u): ) best = min(options, key=lambda c: (c.cost, c.time)) return NextReplacementOnDates( - str(best), best, options, float(age), rate, valued_by + str(best), best, options, float(age), rate, valued_by, discount_rate ) diff --git a/repyability/non_repairable.py b/repyability/non_repairable.py index 10d604f2..8f6b8f48 100644 --- a/repyability/non_repairable.py +++ b/repyability/non_repairable.py @@ -172,6 +172,22 @@ class NonRepairable: What a replacement at a failure costs, at least 0, by name (``cu``): with ``planned_cost``, more than it. Either may be given alone: ``failures`` needs only this one. By default None: not given. + opportunity_cost : float, optional + What a planned replacement at an opportunity (a stop or shut, + [`Opportunity`][repyability.Opportunity]) costs, at least 0. By + default None: an opportunity is priced as any other day, at + ``planned_cost``. + job_duration : float or str, optional + How long replacing the part takes: an opportunity shorter than it + is not used for this part (the policy's ``prices`` say so). On + real dates text (``"6h"``) or a number of hours; in model time a + number in the life's unit. By default None: every opportunity is + used. + opportunity_costs : dict, optional + Prices at particular opportunities, overriding + ``opportunity_cost``: keyed by the opportunity's name or the + ``Opportunity`` itself. A policy refuses a key that names no + opportunity of its collection, listing the names it has. Attributes ---------- @@ -233,6 +249,9 @@ def __init__( *, planned_cost=None, unplanned_cost=None, + opportunity_cost=None, + job_duration=None, + opportunity_costs=None, ): # A Bayesian fit is its posterior predictive. # A life at a usage rate is the distribution it is in hours. @@ -283,7 +302,8 @@ def __init__( elif by_functions(reliability): # Any other surpyval model with a life's functions (#93): a # Royston-Parmar fit, a regression at a unit's covariates - # (regression.at(Z)), a destructive degradation model. Its + # (regression.at(Z)), a destructive degradation model; or a + # NonRepairableRBD, a subassembly replaced whole. Its # survival is a smooth curve, as a distribution's. self.model_parameterization = "parametric" self.reliability_function = reliability.sf @@ -321,7 +341,8 @@ def __init__( "mean: a distribution, a MixtureModel, a Bayesian fit, a " "Royston-Parmar fit, a regression at one unit's covariates " "with regression.at(Z), a degradation process), a surpyval " - "non-parametric estimate or a StandbyModel; got a " + "non-parametric estimate, a StandbyModel or a " + "NonRepairableRBD (a subassembly replaced whole); got a " f"{type(reliability).__name__}" + _why_not(reliability) ) @@ -338,6 +359,29 @@ def __init__( ) self.__next_event_type = FAILURE self._set_costs(planned_cost, unplanned_cost) + self._set_opportunity_prices( + opportunity_cost=opportunity_cost, + job_duration=job_duration, + opportunity_costs=opportunity_costs, + ) + + def _set_opportunity_prices( + self, *, opportunity_cost, job_duration, opportunity_costs + ) -> None: + """Keep the part's prices at opportunities, checked (the keys of + ``opportunity_costs`` are checked against the opportunities when a + policy runs).""" + from repyability.maintenance._opportunities import ( + check_part_prices, + ) + + ( + self.opportunity_cost, + self.job_duration, + self.opportunity_costs, + ) = check_part_prices( + opportunity_cost, job_duration, opportunity_costs + ) def _set_costs(self, planned, unplanned) -> None: """Keep the costs given to the constructor (``cp``, ``cu``): each @@ -377,6 +421,8 @@ def __repr__(self) -> str: parts.append(f"planned_cost={self.cp:g}") if hasattr(self, "cu"): parts.append(f"unplanned_cost={self.cu:g}") + if getattr(self, "opportunity_cost", None) is not None: + parts.append(f"opportunity_cost={self.opportunity_cost:g}") return f"NonRepairable({', '.join(parts)})" def failures(self, t, age: float = 0.0) -> FailureForecast: @@ -458,6 +504,35 @@ def shaped(values): None if cost is None else shaped(cost), ) + def _failures_error(self, horizon: float, age: float = 0.0) -> float: + """How far ``failures``' expected count may be from the true one + anywhere in ``[0, horizon]``, from its age: the renewal count's + later units are worked out at a grid's points and taken linearly + between them, which is off by at most ``h**2 / 8`` times the + count's curvature, the largest second difference of the grid's + counts over 8. 0 where the count has no such grid (the first + unit's failures are its life's own CDF, exactly).""" + from repyability.rbd import _curves + from repyability.rbd.node_state import NodeState + from repyability.rbd.repairable_rbd import RepairableRBD + + if not horizon > 0.0: + return 0.0 + unit = RepairableRBD([("s", "unit"), ("unit", "t")], {"unit": self}) + states = _curves._states(unit, {"unit": NodeState(age=age)}, set()) + curves = _curves._availability_curves( + unit, float(horizon), set(), counts=True, state=states + ) + events = getattr(curves.get("unit"), "unit_events", None) + later = getattr(events, "later", None) + if events is None or later is None or len(later) < 3: + return 0.0 + times = np.asarray(events.times, dtype=float) + # The cells up to the horizon, with the one it falls in. + stop = int(np.searchsorted(times, horizon, side="left")) + 2 + curvature = np.abs(np.diff(np.asarray(later, dtype=float)[:stop], 2)) + return float(curvature.max()) / 8.0 if curvature.size else 0.0 + def set_costs_planned_and_unplanned(self, cp, cu): """Set the planned and unplanned replacement costs. @@ -744,8 +819,9 @@ def failure_frequency(self) -> float: def _cost_rate_with_log_x(self, x): return self._cost_rate(np.exp(x)) - def find_optimal_replacement(self): - """The replacement age that minimises the long-run cost rate. + def find_optimal_replacement(self, *, discount_rate=0.0): + """The replacement age that minimises the long-run cost rate, or, + with a discount rate, the equivalent annual cost. Minimises the age-replacement cost rate (see ``cost_rate``) ``(cp * R(t) + cu * (1 - R(t))) / integral_0^t R(u) du`` over the @@ -788,6 +864,38 @@ def find_optimal_replacement(self): stopped on the flattening curve. A replacement age must save more than one part in a million to count. + **With a discount rate** money spent later is worth less now, so + the age is chosen to make the present value of every replacement, + forever, the least (Fox, 1966); ``discount_rate`` times that value + is the equivalent annual cost (EAC), a steady cost per unit time + worth the same. With ``r`` the rate, ``R`` the reliability and + ``M(t)`` the integral of ``exp(-r u) R(u)`` from 0 to ``t``:: + + EAC(t) = [cu * (1 - exp(-r t) R(t) - r M(t)) + + cp * exp(-r t) R(t)] / M(t) + + which is the cost rate above at ``r = 0``. Discounting puts off + the planned replacement's cost, so for a part that wears out the + best age is usually older than undiscounted. The cost is scanned + on a grid of ages (the trapezoidal rule) up to where the part has + all but surely failed or a cost is discounted to ``exp(-40)``, and + the cheapest age refined by a bounded search on the cost by + quadrature (a non-parametric estimate: its own grid, as above). + An exponential life, or a Weibull of shape ``<= 1``, still returns + ``inf`` at once; a limited failure population is searched, as + running to failure is no longer free when the failures to come + are discounted. ``inf`` is returned where no age beats running to + failure, whose EAC is ``cu * (1 - r M) / M`` with ``M`` the + integral to infinity. + + Parameters + ---------- + discount_rate : float, optional + The continuous discount rate per unit of the lifetime model's + time, by default 0 (undiscounted, the long-run cost rate). For + a yearly rate of 7% with a life in hours, ``math.log(1.07) / + 8760``. + Returns ------- float @@ -816,7 +924,25 @@ def find_optimal_replacement(self): >>> unit.set_costs_planned_and_unplanned(cp=1, cu=5) >>> unit.find_optimal_replacement() inf + + Discounted at 10% a year, with the life in hours, the best age is + a little older: + + >>> import math + >>> unit = NonRepairable(surv.Weibull.from_params([1000, 2.5])) + >>> unit.set_costs_planned_and_unplanned(cp=1, cu=5) + >>> a_year = math.log(1.10) / 8760 + >>> best = unit.find_optimal_replacement(discount_rate=a_year) + >>> round(float(best), 1) + 493.4 """ + from repyability.maintenance._options import ( + discount_rate as _discount_rate, + ) + + rate = _discount_rate(discount_rate) + if rate > 0.0: + return self._discounted_optimum(rate)[0] if self.model_parameterization == "parametric": if never_fails(self.reliability) > 0.0: # Some units never fail: in the long run one of them is in @@ -880,6 +1006,40 @@ def find_optimal_replacement(self): optimal = float(ages[int(np.nanargmin(rates))]) return optimal + def _memoryless(self) -> bool: + """Whether the life is one preventive replacement never improves, + discounted or not: an exponential, or a Weibull of shape at most + 1, with no offset, zero-inflation or limited failure + population.""" + if self.model_parameterization != "parametric": + return False + model = self.reliability + if ( + getattr(model, "offset", False) + or getattr(model, "zi", False) + or getattr(model, "lfp", False) + ): + return False + if is_exponential(model): + return True + return distribution_name(model) == "Weibull" and model.params[1] <= 1 + + def _discounted_optimum(self, rate: float): + """The age-replacement age with the least equivalent annual cost at + ``rate`` (more than 0), and that cost (see + ``find_optimal_replacement``).""" + from repyability.maintenance._options import ( + discounted_optimum, + discounted_run_to_failure, + ) + + if self._memoryless(): + if self.cu is None: + return np.inf, np.nan + return np.inf, discounted_run_to_failure(self, rate, self.cu) + self._require_costs() + return discounted_optimum(self, rate, self.cp, self.cu) + def _run_to_failure_rate(self) -> float: """The long-run cost rate with no preventive replacement, ``cu / MTTF``: 0 when some units never fail (a limited failure @@ -927,7 +1087,9 @@ def _optimal_standby_replacement(self) -> float: ) return float(refined.x) - def optimal_replacement_policy(self) -> MaintenancePolicy: + def optimal_replacement_policy( + self, *, discount_rate=0.0 + ) -> MaintenancePolicy: """The optimal age-replacement policy as a typed result. Finds the replacement age with ``find_optimal_replacement()`` (see @@ -937,11 +1099,26 @@ def optimal_replacement_policy(self) -> MaintenancePolicy: interval is ``inf`` and the cost rate is the run-to-failure rate ``cu / MTTF``, or 0 when some units never fail. + With a discount rate the age is the one with the least equivalent + annual cost (EAC; Fox, 1966): the present value of every + replacement, forever, spread as a steady cost per unit time. The + result then carries that present value (``npv``) and ``eac``, and + ``cost_rate`` is still the undiscounted long-run cost rate of the + age chosen (of running to failure, where ``interval`` is ``inf``). + + Parameters + ---------- + discount_rate : float, optional + The continuous discount rate per unit of the lifetime model's + time, by default 0 (undiscounted). For a yearly rate of 7% + with a life in hours, ``math.log(1.07) / 8760``. + Returns ------- MaintenancePolicy ``interval`` is the cost-optimal replacement age and - ``cost_rate`` the long-run cost per unit time under it. + ``cost_rate`` the long-run cost per unit time under it; with a + discount rate, ``discount_rate``, ``npv`` and ``eac`` too. Raises ------ @@ -966,14 +1143,40 @@ def optimal_replacement_policy(self) -> MaintenancePolicy: >>> policy = unit.optimal_replacement_policy() >>> policy.interval, round(policy.cost_rate, 4) (inf, 0.05) + + Discounted at 10% a year, the life in hours: + + >>> import math + >>> unit = NonRepairable(surv.Weibull.from_params([1000, 2.5])) + >>> unit.set_costs_planned_and_unplanned(cp=1, cu=5) + >>> rate = math.log(1.1) / 8760 + >>> policy = unit.optimal_replacement_policy(discount_rate=rate) + >>> round(policy.interval, 1), round(policy.eac * 8760, 2) + (493.4, 30.27) """ + from repyability.maintenance._options import ( + discount_rate as _discount_rate, + ) + self._require_costs() - interval = self.find_optimal_replacement() + discount = _discount_rate(discount_rate) + if discount > 0.0: + interval, eac = self._discounted_optimum(discount) + else: + interval = self.find_optimal_replacement() if np.isinf(interval): rate = self._run_to_failure_rate() else: rate = float(self._cost_rate(interval)) - return MaintenancePolicy(interval=float(interval), cost_rate=rate) + if discount == 0.0: + return MaintenancePolicy(interval=float(interval), cost_rate=rate) + return MaintenancePolicy( + interval=float(interval), + cost_rate=rate, + discount_rate=discount, + npv=float(eac) / discount, + eac=float(eac), + ) def optimal_next_replacement( self, @@ -999,10 +1202,14 @@ def optimal_next_replacement( until the part is replaced (at the failure price if it fails first), less the time the part serves until then, valued at the baseline: the long-run cost a unit of time of how the position is - run, ``policy.cost_rate``. By default that is the age + run, ``policy.cost_rate``. A policy chosen at a discount values it + at its equivalent annual cost instead, and each choice is + discounted at the policy's rate (its present value and the + policy's after it, Fox, 1966; ``discount_rate`` on the result). + By default that is the age replacement's (``optimal_replacement_policy().cost_rate``); where cheap shuts keep coming, give the calendar's policy - ([`optimal_calendar_policy`][repyability.NonRepairable.optimal_calendar_policy]), + ([`optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy]), whose rate is lower, so a part is kept longer. The cheapest choice is the best. With no outages and the default baseline, replacing now is the best from the optimal replacement age. @@ -1029,26 +1236,29 @@ def optimal_next_replacement( The policy whose ``cost_rate`` is the baseline, by default ``optimal_replacement_policy()`` (with a site, the site's policy, worked out by its route). - site : Shutdowns, optional - On real dates: the site's shuts. The choices are then now, - each of the next two shuts of each kind, a planned replacement - on any other day (where the site allows one) and running to - failure, on the real dates, with the time beyond valued at the - policy's figure (its cost a year, or for a horizon its net - present cost spread evenly over its years). ``age`` may be - text in the part's unit (``"3,100 h"``). + site : Opportunities, optional + On real dates: the site's opportunities, priced for this part + as + [`optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy] + prices them (a deprecated ``Shutdowns`` too). The choices are + then now, each of the next two shuts of each kind, a planned + replacement on any other day (where the site allows one) and + running to failure, on the real dates, with the time beyond + valued at the policy's figure (its cost a year, or for a + horizon its net present cost spread evenly over its years). + ``age`` may be text in the part's unit (``"3,100 h"``). plan : optional As for - [`optimal_calendar_policy`][repyability.NonRepairable.optimal_calendar_policy]. + [`optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy]. now : optional As for - [`optimal_calendar_policy`][repyability.NonRepairable.optimal_calendar_policy]. + [`optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy]. readings : optional As for - [`optimal_calendar_policy`][repyability.NonRepairable.optimal_calendar_policy]. + [`optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy]. unit : optional As for - [`optimal_calendar_policy`][repyability.NonRepairable.optimal_calendar_policy]. + [`optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy]. Returns ------- @@ -1095,9 +1305,15 @@ def optimal_next_replacement( policy values a day of service at 0.990 rather than 1.117, and replacing now beats the outage in 150 days from a younger age: - >>> from repyability import Calendar, Opportunity - >>> shuts = bearing.optimal_calendar_policy( - ... Calendar([Opportunity("shut", 100.0, period=180.0)]) + >>> from repyability import Opportunities, Opportunity + >>> at_shuts = NonRepairable( + ... surv.Weibull.from_params([365.0, 2.0]), + ... planned_cost=150.0, + ... unplanned_cost=400.0, + ... opportunity_cost=100.0, + ... ) + >>> shuts = at_shuts.optimal_opportunity_policy( + ... Opportunities([Opportunity("shut", period=180.0)]) ... ) >>> found = bearing.optimal_next_replacement( ... 200.0, @@ -1117,6 +1333,9 @@ def optimal_next_replacement( "With a site, the shuts and the price on any other day " "come from it: give no now_cost or scheduled_outages." ) + from repyability.maintenance._opportunities import resolve + + site, _ = resolve(self, site, on_dates=True) return next_on_dates( self, age, @@ -1432,7 +1651,7 @@ def cost_of_waiting_for_visit( ... planned_cost=150.0, ... unplanned_cost=400.0, ... ) - >>> weekly = Opportunity("weekly", 0.0, period=7.0) + >>> weekly = Opportunity("weekly", period=7.0) >>> result = bearing.cost_of_waiting_for_visit(200.0, 10.0, weekly) >>> result.done_in, round(result.added_failure_probability, 4) (14.0, 0.0123) @@ -1714,7 +1933,7 @@ def cost_distribution( block replacement (``resets=False``), as [`renewal_forecast`][repyability.NonRepairable.renewal_forecast] takes it, or a calendar policy (``calendar``, from - [`optimal_calendar_policy`][repyability.NonRepairable.optimal_calendar_policy]: + [`optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy]: at each opportunity, replace the part if it is at least that time's threshold age, at that opportunity's price); replacements take no time. Numerical by default (to the ``precision`` @@ -1985,10 +2204,11 @@ def cost_by_window( seed=seed, ) - def optimal_calendar_policy( + def optimal_opportunity_policy( self, - calendar, + opportunities, *, + where=None, plan=None, now=None, readings=None, @@ -2003,19 +2223,35 @@ def optimal_calendar_policy( mc_samples=64, seed=None, dated_until=None, + discount_rate=0.0, ): - """The long-run optimal replacement policy over a calendar of - opportunities: shuts at their own prices, a planned replacement on - any day at a dearer one (or none), and a failure at the dearest. - - **A site's shuts on real dates.** Given a - [`Shutdowns`][repyability.Shutdowns] (the site's shuts as rules, - dates, plain periods or uses, each with its price, and the price on - any other day), it returns a + """The long-run optimal replacement policy of this part over + opportunities to replace it: stops and shuts at the part's price + there, a planned replacement on any day at a dearer one (or none), + and a failure at the dearest. + + **The prices are the part's** (one + [`Opportunities`][repyability.Opportunities] serves every part): at + an opportunity, the part's ``opportunity_costs`` for it (by name or + object; a key naming no opportunity here is refused), else its + ``opportunity_cost``, else its ``planned_cost`` (an opportunity + priced as any other day); on any day (where the opportunities + allow it, ``any_day=True``) its ``planned_cost``; at a failure its + ``unplanned_cost``. An opportunity shorter than the part's + ``job_duration``, or (with ``where=``) one that does not take that + label down, is not used. The policy's ``prices`` + ([`OpportunityPrices`][repyability.OpportunityPrices]) give each + price and where it came from, and each opportunity not used and + why. (The deprecated ``Calendar`` and ``Shutdowns``, with prices on + the opportunities, are taken as before: those prices are the + part's for those opportunities.) + + **Opportunities on real dates.** Given opportunities on real dates + (rules, dates, plain periods or uses), it returns a [`ShutdownPolicy`][repyability.ShutdownPolicy], worked out by the route the shuts allow, which the result names in words (``route``, ``route_text``; - [`Shutdowns.route`][repyability.Shutdowns.route] says it + [`Opportunities.route`][repyability.Opportunities.route] says it beforehand): 1. **exact**: the shuts repeat in the part's own clock on a short @@ -2031,7 +2267,7 @@ def optimal_calendar_policy( 4. ``horizon=`` and ``discount=``: the lowest net present cost on the real dates to the horizon. - **Fixed dates** (a ``Shutdown`` with ``dates=``, such as + **Fixed dates** (an ``Opportunity`` with ``dates=``, such as turnarounds) are never averaged. Without a horizon the policy is ``"dated_then_long_run"``: a dated window from now to the last fixed date (or to ``dated_until``), in which every shut, the @@ -2051,8 +2287,8 @@ def optimal_calendar_policy( ``SlowSolverWarning`` where it takes over about 5 s). The guide's [shutdown policies](../guide/maintenance.md) has the examples. - **A calendar in model time** (a [`Calendar`][repyability.Calendar]) - is worked out as before, returning a + **Opportunities in model time** (periods, or dates as numbers) + are worked out on the part's model time, returning a [`CalendarPolicy`][repyability.CalendarPolicy]: Age replacement @@ -2084,7 +2320,23 @@ def optimal_calendar_policy( the seed; the threshold at a time is a solve over a window from it (deterministic). - ``"auto"``: ``"dp"``, or ``"sampling"`` for a periodic calendar - whose cycle is too long to sweep, with a warning that says so. + whose cycle is too long to sweep, with a ``FutureWarning``: from + 0.21 that refuses, naming a ready ``horizon=`` (exact by + default, simulation on request: give ``horizon=`` or + ``method="sampling"``). + + **Exact by default; refused where it can't be; a horizon never + refused.** Without ``horizon=`` the answer is the exact repeating + cycle's, with or without a discount. Where that can't be worked + out exactly (a cycle too long to sweep, given dates, shuts that + drift on real dates, a duty plan's clock), it is refused, and the + refusal names a ready horizon worked out from the inputs: with a + discount, the time past which costs count for under one part in a + billion; with none, the full cycle and three of the part's life + spans. ``horizon=`` (a model time here, a date on real dates) + sweeps backward from it over every opportunity as it falls: the + lowest net present cost to then (``npv``) and its equivalent + annual cost (``eac``), or with no discount the total to then. The grid's step is not an argument: it is a numerical setting, sized from the models (never in absolute time), not a choice of @@ -2095,18 +2347,24 @@ def optimal_calendar_policy( of days, as dates turned into model time give) is laid at the grid time nearest it, with a warning. - A calendar with given dates (a plan) is extended past its last - date by ``tail``: ``"repeat"`` repeats the plan (from 0 to its - last date and its mean gap), ``"anytime"`` leaves only replacement + Without a horizon, a calendar with given dates (a plan) is + extended past its last date by ``tail``: ``"repeat"`` repeats the + plan (from 0 to its last date and its mean gap), ``"anytime"`` + leaves only replacement on any day. Both are solved, and the policy says the first time they differ (``determined_until``); its cost rate is the repeated plan's. Parameters ---------- - calendar : Shutdowns or Calendar - The site's shuts, or opportunities in model time (whose - ``"part"`` prices are this part's planned and unplanned costs). + opportunities : Opportunities + The opportunities, on real dates or in model time (a list of + ``Opportunity`` is taken as ``Opportunities`` of them; the + deprecated ``Calendar`` and ``Shutdowns`` too). + where : str, optional + A label (a line, a unit): only the opportunities that take it + down are used, those with no ``takes_down`` taking the whole + site down. By default None: every opportunity. plan : DutyPlan, optional With a site: how the equipment runs, turning dates into the part's clock; without, the part's clock is calendar time. @@ -2127,7 +2385,23 @@ def optimal_calendar_policy( (as None), ``"dp"``, ``"integration"`` or ``"sampling"``. horizon, discount : optional With a site: the last day costs count to, and the yearly - discount rate (required with a horizon; 0 for the plain total). + discount rate as a fraction (0.07 for 7% a year; required with + a horizon, 0 for the plain total). With opportunities in model + time, ``horizon`` is a time in their own time (a number), with + ``discount_rate`` (0 for the plain total), and the policy is + the lowest net present cost to it (``basis="horizon"``). + ``discount`` without a horizon discounts the long run: the + policy minimises the present value of every replacement from + now on, forever, and + ``cost`` is its equivalent annual cost (EAC), the steady cost + a year worth the same, ``ln(1 + discount)`` times the present + value. A dated window is then discounted to its end, and the + recurring shuts' discounted long run values everything after + it. Only the routes that repeat exactly are discounted (the + exact routes, the dated window, and plain age replacement on + any day), with no duty plan (whose clock does not keep a steady + pace with the calendar); the others are refused with what to + give instead. failure_timing : str, optional With a site: ``"half_step"`` (the default) or ``"exact"``. dated_until : date or str, optional @@ -2149,6 +2423,21 @@ def optimal_calendar_policy( methods take none. seed : int, optional Seeds the sampled times; the other methods draw nothing. + discount_rate : float, optional + With a calendar in model time: the continuous discount rate + per unit of the calendar's time, by default 0 (the long-run + average). Given, the thresholds minimise the present value at + time 0 of every replacement from a new part, forever (Fox, + 1966; discounted value iteration over the cycle), and the + policy carries that value (``npv``) and ``discount_rate`` times + it, the equivalent annual cost (``eac``); ``cost_rate`` stays + the long-run (undiscounted) cost rate of the policy chosen. For + a yearly rate of 7% with a calendar in days, + ``math.log(1.07) / 365.25``. A periodic calendar of a short + cycle only (``"dp"`` or ``"integration"``): a long cycle, a + plan of given dates and ``"sampling"`` are refused with what to + give instead (a ready ``horizon=`` among it). A site takes + ``discount`` (a yearly rate) instead. Returns ------- @@ -2176,54 +2465,96 @@ def optimal_calendar_policy( planned cost, it is age replacement: >>> import surpyval as surv - >>> from repyability import Calendar, NonRepairable + >>> from repyability import NonRepairable, Opportunities >>> unit = NonRepairable( ... surv.Weibull.from_params([1000, 2.5]), ... planned_cost=1.0, ... unplanned_cost=5.0, ... ) - >>> policy = unit.optimal_calendar_policy(Calendar()) + >>> policy = unit.optimal_opportunity_policy(Opportunities()) >>> round(policy.cost_rate, 6) 0.003462 >>> round(policy.next_replacement(age=0.0).time, 1) 493.3 >>> round(unit.optimal_replacement_policy().interval, 1) 493.0 + + One record of stops for two parts, each with its own prices: + + >>> from repyability import Opportunity + >>> stops = Opportunities([Opportunity("stop", period=28.0)]) + >>> seal = NonRepairable( + ... surv.Weibull.from_params([1000, 2.5]), + ... planned_cost=4.0, unplanned_cost=20.0, opportunity_cost=3.0, + ... ) + >>> policy = seal.optimal_opportunity_policy(stops) + >>> policy.prices.price("stop"), policy.prices.row("stop").source + (3.0, 'opportunity_cost') """ + from repyability.maintenance._opportunities import ( + resolve, + site_given, + with_prices, + ) from repyability.maintenance._replacement import ( optimal_calendar_policy, ) from repyability.maintenance._shutdowns import Shutdowns from repyability.maintenance._site_policy import find_policy - if isinstance(calendar, Shutdowns): - if max_age is not None or tail != "repeat": - raise ValueError( - "max_age and tail are for a Calendar in model time; a " - "site's shuts take neither." - ) - return find_policy( - self, - calendar, + calendar, prices = resolve( + self, + opportunities, + where=where, + on_dates=site_given( plan=plan, now=now, readings=readings, - age=age, unit=unit, - method=method, - horizon=horizon, + horizon=None if is_number(horizon) else horizon, discount=discount, - failure_timing=failure_timing, - mc_samples=mc_samples, - seed=seed, dated_until=dated_until, + age=age, + failure_timing=failure_timing, + ), + ) + if isinstance(calendar, Shutdowns): + if max_age is not None or tail != "repeat": + raise ValueError( + "max_age and tail are for a Calendar in model time; a " + "site's shuts take neither." + ) + if discount_rate != 0.0: + raise ValueError( + "discount_rate is for a Calendar in model time (a " + "continuous rate a unit of its time); a site takes " + "discount=, a yearly rate such as 0.07." + ) + return with_prices( + find_policy( + self, + calendar, + plan=plan, + now=now, + readings=readings, + age=age, + unit=unit, + method=method, + horizon=horizon, + discount=discount, + failure_timing=failure_timing, + mc_samples=mc_samples, + seed=seed, + dated_until=dated_until, + ), + prices, ) + _model_horizon(horizon) _calendar_only( plan=plan, now=now, readings=readings, unit=unit, - horizon=horizon, discount=discount, dated_until=dated_until, ) @@ -2237,21 +2568,118 @@ def optimal_calendar_policy( "failure_timing is for a site's shuts (Shutdowns); a Calendar " "takes method='dp' or 'integration'." ) - return optimal_calendar_policy( - self, + return with_prices( + optimal_calendar_policy( + self, + calendar, + max_age=max_age, + method="auto" if method is None else method, + tail=tail, + mc_samples=mc_samples, + seed=seed, + discount_rate=discount_rate, + horizon=horizon, + ), + prices, + ) + + def optimal_calendar_policy( + self, + calendar, + *, + plan=None, + now=None, + readings=None, + age=0.0, + unit=None, + method=None, + horizon=None, + discount=None, + failure_timing="half_step", + max_age=None, + tail="repeat", + mc_samples=64, + seed=None, + dated_until=None, + discount_rate=0.0, + ): + """**Deprecated** (removed in 0.21): renamed + [`optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy], + which takes the same arguments and gives the same policy. + + Parameters + ---------- + calendar : Opportunities, Calendar or Shutdowns + The opportunities. + plan : optional + As for ``optimal_opportunity_policy``. + now : optional + As for ``optimal_opportunity_policy``. + readings : optional + As for ``optimal_opportunity_policy``. + age : optional + As for ``optimal_opportunity_policy``. + unit : optional + As for ``optimal_opportunity_policy``. + method : optional + As for ``optimal_opportunity_policy``. + horizon : optional + As for ``optimal_opportunity_policy``. + discount : optional + As for ``optimal_opportunity_policy``. + failure_timing : optional + As for ``optimal_opportunity_policy``. + max_age : optional + As for ``optimal_opportunity_policy``. + tail : optional + As for ``optimal_opportunity_policy``. + mc_samples : optional + As for ``optimal_opportunity_policy``. + seed : optional + As for ``optimal_opportunity_policy``. + dated_until : optional + As for ``optimal_opportunity_policy``. + discount_rate : optional + As for ``optimal_opportunity_policy``. + + Returns + ------- + ShutdownPolicy or CalendarPolicy + As ``optimal_opportunity_policy`` returns. + """ + from repyability.utils.deprecation import replaced + + replaced( + "NonRepairable.optimal_calendar_policy", + "NonRepairable.optimal_opportunity_policy", + "the opportunities are one record for every part, on real " + "dates or in model time", + ) + return self.optimal_opportunity_policy( calendar, + plan=plan, + now=now, + readings=readings, + age=age, + unit=unit, + method=method, + horizon=horizon, + discount=discount, + failure_timing=failure_timing, max_age=max_age, - method="auto" if method is None else method, tail=tail, mc_samples=mc_samples, seed=seed, + dated_until=dated_until, + discount_rate=discount_rate, ) - def calendar_policy_cost( + def opportunity_policy_cost( self, - calendar, + opportunities, rule, *, + where=None, max_age=None, plan=None, now=None, @@ -2264,21 +2692,31 @@ def calendar_policy_cost( mc_samples=64, seed=None, dated_until=None, + discount_rate=0.0, ): """The long-run average cost a unit of time of a given replacement rule over a calendar of opportunities: to price simple policies against - [`optimal_calendar_policy`][repyability.NonRepairable.optimal_calendar_policy]. + [`optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy]. - Given a site ([`Shutdowns`][repyability.Shutdowns]), the rule - names the site's kinds of shut (and ``"any other day"``), it is + The prices are the part's, laid on the opportunities as + [`optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy] + lays them (``where`` as there). On real dates, the rule + names the kinds of opportunity (and ``"any other day"``), it is priced by the same route as the policy would be (``plan``, ``now``, ``readings``, ``unit``, ``method``, ``horizon``, ``discount``, ``failure_timing``, ``dated_until`` as there), and a [`RuleCost`][repyability.RuleCost] comes back: the cost, its - measure, the route and words, and the replacements by kind. Given - a [`Calendar`][repyability.Calendar] it returns the rate, a float, - as before. + measure, the route and words, and the replacements by kind. With + ``discount=`` and no horizon, the rule's discounted long run is + priced exactly where the shuts repeat (its equivalent annual cost, + as the policy's own is worked out, with the decisions fixed), and + refused with a ready horizon where they don't. Given opportunities + in model time it returns a float: the rate; with + ``discount_rate``, the equivalent cost a unit of time of the + rule's discounted long run (a periodic calendar of a short cycle; + otherwise refused with a ready ``horizon=``); with ``horizon`` (a + model time), the rule's net present cost to it. The rule gives, for each kind of replacement it uses (an opportunity's name, or ``"anytime"`` for any day), the age from @@ -2290,98 +2728,137 @@ def calendar_policy_cost( Parameters ---------- - calendar : Calendar - The opportunities and prices. + opportunities : Opportunities + The opportunities. rule : dict The age, at least 0 (``inf`` for never), from which each kind replaces: ``{"annual": 0.0}`` replaces at every annual shut, ``{"anytime": 493.0}`` at age 493 on any day, ``{}`` runs to failure. + where : str, optional + As for ``optimal_opportunity_policy``. max_age : float, optional The oldest age on the grid, as for ``optimal_calendar_policy``. plan : optional With a site: as for - [`optimal_calendar_policy`][repyability.NonRepairable.optimal_calendar_policy]. + [`optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy]. now : optional With a site: as for - [`optimal_calendar_policy`][repyability.NonRepairable.optimal_calendar_policy]. + [`optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy]. readings : optional With a site: as for - [`optimal_calendar_policy`][repyability.NonRepairable.optimal_calendar_policy]. + [`optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy]. unit : optional With a site: as for - [`optimal_calendar_policy`][repyability.NonRepairable.optimal_calendar_policy]. + [`optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy]. method : optional With a site: as for - [`optimal_calendar_policy`][repyability.NonRepairable.optimal_calendar_policy]. + [`optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy]. horizon : optional With a site: as for - [`optimal_calendar_policy`][repyability.NonRepairable.optimal_calendar_policy]. + [`optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy]. discount : optional With a site: as for - [`optimal_calendar_policy`][repyability.NonRepairable.optimal_calendar_policy]. + [`optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy]. failure_timing : optional With a site: as for - [`optimal_calendar_policy`][repyability.NonRepairable.optimal_calendar_policy]. + [`optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy]. mc_samples : optional With a site: as for - [`optimal_calendar_policy`][repyability.NonRepairable.optimal_calendar_policy]. + [`optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy]. seed : optional With a site: as for - [`optimal_calendar_policy`][repyability.NonRepairable.optimal_calendar_policy]. + [`optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy]. dated_until : optional With a site: as for - [`optimal_calendar_policy`][repyability.NonRepairable.optimal_calendar_policy]. + [`optimal_opportunity_policy`][repyability.NonRepairable.optimal_opportunity_policy]. + discount_rate : float, optional + With opportunities in model time: the continuous discount rate + a unit of their time, by default 0. Returns ------- - float - The rule's long-run cost a unit of time. + float or RuleCost + In model time the rule's long-run cost a unit of time (its + EAC with ``discount_rate``, its net present cost with + ``horizon``); on real dates a ``RuleCost``. Examples -------- >>> import surpyval as surv - >>> from repyability import Calendar, NonRepairable + >>> from repyability import NonRepairable, Opportunities >>> unit = NonRepairable( ... surv.Weibull.from_params([1000, 2.5]), ... planned_cost=1.0, ... unplanned_cost=5.0, ... ) - >>> rate = unit.calendar_policy_cost(Calendar(), {"anytime": 493.0}) + >>> rate = unit.opportunity_policy_cost( + ... Opportunities(), {"anytime": 493.0} + ... ) >>> round(rate, 6) 0.003462 """ + from repyability.maintenance._opportunities import ( + resolve, + site_given, + with_prices, + ) from repyability.maintenance._replacement import ( calendar_policy_cost, ) from repyability.maintenance._shutdowns import Shutdowns from repyability.maintenance._site_policy import price_rule - if isinstance(calendar, Shutdowns): - if max_age is not None: - raise ValueError("max_age is for a Calendar in model time.") - return price_rule( - self, - calendar, - rule, + calendar, prices = resolve( + self, + opportunities, + where=where, + on_dates=site_given( plan=plan, now=now, readings=readings, unit=unit, - method=method, - horizon=horizon, + horizon=None if is_number(horizon) else horizon, discount=discount, - failure_timing=failure_timing, - mc_samples=mc_samples, - seed=seed, dated_until=dated_until, + failure_timing=failure_timing, + method=method, + ), + ) + if isinstance(calendar, Shutdowns): + if max_age is not None: + raise ValueError("max_age is for a Calendar in model time.") + if discount_rate != 0.0: + raise ValueError( + "discount_rate is for opportunities in model time (a " + "continuous rate a unit of their time); a site takes " + "discount=, a yearly rate such as 0.07." + ) + return with_prices( + price_rule( + self, + calendar, + rule, + plan=plan, + now=now, + readings=readings, + unit=unit, + method=method, + horizon=horizon, + discount=discount, + failure_timing=failure_timing, + mc_samples=mc_samples, + seed=seed, + dated_until=dated_until, + ), + prices, ) + _model_horizon(horizon) _calendar_only( plan=plan, now=now, readings=readings, unit=unit, - horizon=horizon, discount=discount, method=method, dated_until=dated_until, @@ -2390,7 +2867,188 @@ def calendar_policy_cost( raise ValueError( "failure_timing is for a site's shuts (Shutdowns)." ) - return calendar_policy_cost(self, calendar, rule, max_age=max_age) + return calendar_policy_cost( + self, + calendar, + rule, + max_age=max_age, + discount_rate=discount_rate, + horizon=horizon, + ) + + def calendar_policy_cost( + self, + calendar, + rule, + *, + max_age=None, + plan=None, + now=None, + readings=None, + unit=None, + method=None, + horizon=None, + discount=None, + failure_timing="half_step", + mc_samples=64, + seed=None, + dated_until=None, + discount_rate=0.0, + ): + """**Deprecated** (removed in 0.21): renamed + [`opportunity_policy_cost`][repyability.NonRepairable.opportunity_policy_cost], + which takes the same arguments and gives the same cost. + + Parameters + ---------- + calendar : Opportunities, Calendar or Shutdowns + The opportunities. + rule : dict + As for ``opportunity_policy_cost``. + max_age : optional + As for ``opportunity_policy_cost``. + plan : optional + As for ``opportunity_policy_cost``. + now : optional + As for ``opportunity_policy_cost``. + readings : optional + As for ``opportunity_policy_cost``. + unit : optional + As for ``opportunity_policy_cost``. + method : optional + As for ``opportunity_policy_cost``. + horizon : optional + As for ``opportunity_policy_cost``. + discount : optional + As for ``opportunity_policy_cost``. + failure_timing : optional + As for ``opportunity_policy_cost``. + mc_samples : optional + As for ``opportunity_policy_cost``. + seed : optional + As for ``opportunity_policy_cost``. + dated_until : optional + As for ``opportunity_policy_cost``. + discount_rate : optional + As for ``opportunity_policy_cost``. + + Returns + ------- + float or RuleCost + As ``opportunity_policy_cost`` returns. + """ + from repyability.utils.deprecation import replaced + + replaced( + "NonRepairable.calendar_policy_cost", + "NonRepairable.opportunity_policy_cost", + "the opportunities are one record for every part, on real " + "dates or in model time", + ) + return self.opportunity_policy_cost( + calendar, + rule, + max_age=max_age, + plan=plan, + now=now, + readings=readings, + unit=unit, + method=method, + horizon=horizon, + discount=discount, + failure_timing=failure_timing, + mc_samples=mc_samples, + seed=seed, + dated_until=dated_until, + discount_rate=discount_rate, + ) + + @staticmethod + def opportunity_prices( + opportunities, + *, + replacement_cost, + replacement_duration, + failure_cost, + failure_duration, + downtime_cost, + ): + """A part's prices worked out from what a replacement costs and how + long the plant is down for it: one row per opportunity, then any + other day and a failure, each with its price and why. + + - At an opportunity the job fits in: ``replacement_cost`` (the + plant is down anyway). + - On any other day: ``replacement_cost + downtime_cost * + replacement_duration``. + - At a failure: ``failure_cost + downtime_cost * + failure_duration``. + - At an opportunity shorter than ``replacement_duration``: not + used. + + ``downtime_cost`` is the system's (what an hour of the plant down + costs), so it is not kept on the part: the result's ``apply(part)`` + gives the part the prices it works out (``planned_cost``, + ``unplanned_cost``, ``opportunity_cost`` and ``job_duration``). + + Parameters + ---------- + opportunities : Opportunities + The opportunities. + replacement_cost : float + What the replacement itself costs (parts and labour). + replacement_duration : float or str + How long it takes: on real dates text (``"6h"``) or hours, the + downtime cost a unit of it being an hour's; in model time a + number in the life's unit. + failure_cost : float + What a replacement at a failure costs itself. + failure_duration : float or str + How long the plant is down at a failure, as + ``replacement_duration``. + downtime_cost : float + What the plant down costs a unit of duration. + + Returns + ------- + OpportunityPrices + The rows, and the part's prices to ``apply``. + + Examples + -------- + >>> from repyability import NonRepairable, Opportunities, Opportunity + >>> from repyability.schedule import Recurrence + >>> site = Opportunities([ + ... Opportunity("weekly stop", Recurrence.weekly("Sat"), + ... duration="8h"), + ... Opportunity("shift change", Recurrence.weekly("Mon"), + ... duration="4h"), + ... ]) + >>> prices = NonRepairable.opportunity_prices( + ... site, replacement_cost=1_200, replacement_duration="6h", + ... failure_cost=4_200, failure_duration="18h", + ... downtime_cost=2_500, + ... ) + >>> print(prices.describe()) # doctest: +NORMALIZE_WHITESPACE + weekly stop: $1,200 (replacement_cost alone: the plant is down + anyway) + shift change: not used (the 6 h job doesn't fit in the 4 h shift + change) + any day: $16,200 (1200 + 2500 x 6 h) + failure: $49,200 (4200 + 2500 x 18 h) + """ + from repyability.maintenance._opportunities import ( + opportunity_prices, + ) + + return opportunity_prices( + opportunities, + replacement_cost=replacement_cost, + replacement_duration=replacement_duration, + failure_cost=failure_cost, + failure_duration=failure_duration, + downtime_cost=downtime_cost, + ) def reset(self): """Restart the event sequence with a working, as-new unit. @@ -2458,6 +3116,17 @@ def next_event(self): return self.time_to_replace.random(1).item(), True +def _model_horizon(horizon) -> None: + """Refuse a horizon on real dates given with opportunities in model + time, which take one in their own time.""" + if horizon is not None and not is_number(horizon): + raise ValueError( + "These opportunities are in model time, so a horizon is a time " + f"in their own time (a number, such as 36500); got {horizon!r}. " + "A date is for opportunities on real dates." + ) + + def _calendar_only(**given) -> None: """Refuse a site's options given with a ``Calendar`` in model time.""" named = sorted(k for k, v in given.items() if v is not None) diff --git a/repyability/rbd/_block_replacement.py b/repyability/rbd/_block_replacement.py index bb99457f..bfe875bc 100644 --- a/repyability/rbd/_block_replacement.py +++ b/repyability/rbd/_block_replacement.py @@ -44,6 +44,9 @@ #: Grid steps per block interval: at least, at most, and per interquartile #: range of the lives. _MIN_STEPS, _MAX_STEPS, _STEPS_PER_SPREAD = 2_000, 20_000, 40 +#: The most grid steps of a plan's last stretch, after its last time (see +#: ``plan_availability``). +_MAX_LAST_STEPS = 80_000 #: The longest grid, in steps, for the repairs and replacements that carry a #: unit from one block interval into the next. _MAX_GRID = 4_000_000 @@ -252,12 +255,14 @@ def _grid( node, starts: bool = False, life_checked: bool = True, + steps: Optional[int] = None, ) -> _Grid: """The grid and renewal functions of a unit under block replacement (see ``block_cycle`` for the arguments; ``starts``: with the renewal function of the units put into service, for replacement on condition; ``life_checked=False``: the life is a degradation - process, which ``_level_replacement`` checks itself).""" + process, which ``_level_replacement`` checks itself; ``steps``: the + grid's steps over the interval, by default ``_steps``).""" from scipy.signal import fftconvolve if life_checked: @@ -265,7 +270,8 @@ def _grid( fix = _Duration(repair, "repair", node) replace = _Duration(duration, "replacement", node) T = float(interval) - steps = _steps(life, T) + if steps is None: + steps = _steps(life, T) h = T / steps grid = h * np.arange(steps + 1) @@ -521,6 +527,166 @@ def _head_start(head: BlockHead, g: _Grid): return carried, C, float(head.up) +def _onto(P: np.ndarray, C: np.ndarray, g: _Grid, onto: _Grid): + """``P`` and ``C`` (a CDF and its integral on ``g.rho``, as ``_carry`` + gives them) on the points ``onto.rho`` of the next interval's grid, + where its step differs: linear between ``g``'s points (for ``C``, that + is its masses at those points, each then spread over the two nearest + points of the new grid, so that its mean is kept), and past them as + ``_carry`` extends them, ``P`` constant.""" + if onto is g: + return P, C + x, end = onto.rho, float(g.rho[-1]) + return ( + np.interp(x, g.rho, P), + np.interp(x, g.rho, C) + P[-1] * np.maximum(x - end, 0.0), + ) + + +def _followed(grids, head: Optional[BlockHead]): + """A unit followed from one block time to the next (see + ``block_availability``), each interval on its own grid of ``grids`` + (one grid again and again, on a period; one for each stretch between + the times of a plan, ``plan_availability``): for each interval, its + grid, the smooth part of the unit's availability on it, the + probability that it is replaced at the interval's start, and its + expected failures by each grid point.""" + from scipy.signal import fftconvolve + + starts: dict = {} + previous = None + P = C = density = np.empty(0) + for g in grids: + steps, h = g.steps, g.h + if id(g) not in starts: + # A replacement that starts at the interval's start: the CDF + # of when the unit is back in service, and its integral. + starts[id(g)] = ( + g.replace.cdf(g.rho), + g.rho - g.replace.in_progress(g.rho), + ) + start_P, start_C = starts[id(g)] + if previous is None and head is None: + # The first interval: put into service new at 0. + P = np.ones(g.length + 1) + C = g.rho.copy() + other = np.zeros(g.length + 1) + replaced = 1.0 + else: + if previous is None: + assert head is not None + other, C, replaced = _head_start(head, g) + else: + other, C, in_repair = _carry(P, C, density, previous) + # Up at this block time: put into service in the last + # interval and not in a repair at its end (so that no + # probability is lost). + replaced = float(P[previous.steps]) - in_repair + other, C = _onto(other, C, previous, g) + P = other + replaced * start_P + C = C + replaced * start_C + w = _masses(P, C, steps, h) + row = other[: steps + 1] - fftconvolve(w, 1.0 - g.A)[: steps + 1] + # Failures in each cell of this interval, from the units put into + # service in it, and their running count over the interval. + density = np.diff(fftconvolve(w, g.N)[: steps + 1]) / h + failures = np.concatenate([[0.0], np.cumsum(density * h)]) + yield g, row, replaced, failures + previous = g + + +def plan_availability( + life, + repair, + duration, + lengths, + node=None, + head: Optional[BlockHead] = None, + last_like: Optional[float] = None, + lives: Optional[list] = None, + durations: Optional[list] = None, +) -> list: + """The point availability of a component replaced at the times of a + plan (if it is up at them), stretch by stretch: a ``BlockAvailability`` + of one interval for each of ``lengths``, the times from one of the + plan's times (or 0, or the end of a ``head``) to the next. + + The unit is followed as ``block_availability`` follows it, each + stretch on a grid of its own length (stretches of one length share + theirs, so that equal stretches are block replacement on that period, + to rounding), with what is carried from one into the next (the + repairs and replacements still going on) put onto the next one's grid + (see ``_onto``). Every stretch but the first from new starts with the + replacement of the unit if it is up. + + Parameters + ---------- + life, repair, duration, node, head + As for ``block_availability``. + lengths : sequence of float + Each stretch's length, positive. + last_like : float, optional + For a last stretch that ends at no time of the plan (the one after + its last time, as long as it is asked for): the length of a + stretch whose grid's step it takes, so that it is followed as + finely however long it is (up to ``_MAX_LAST_STEPS`` steps). + lives : list, optional + Each stretch's life, where the units put into service in it have + another than ``life`` (after an upgrade); by default ``life`` in + every stretch. + durations : list, optional + The time the replacement that starts each stretch takes, where + they differ (a unit renewed at several shutdowns, each of its own + length); by default ``duration`` for every stretch. + + Returns + ------- + list of BlockAvailability + + Raises + ------ + NotImplementedError + As ``block_cycle`` does, for a stretch. + """ + if lives is None: + lives = [life] * len(lengths) + if durations is None: + durations = [duration] * len(lengths) + made: dict = {} + keys = [ + (length, id(own), id(taken)) + for length, own, taken in zip(lengths, lives, durations) + ] + for k, (length, own) in enumerate(zip(lengths, lives)): + if keys[k] in made: + continue + steps = None + if last_like is not None and k == len(lengths) - 1: + wanted = _steps(own, last_like) * length / last_like + steps = int(np.clip(np.ceil(wanted), _MIN_STEPS, _MAX_LAST_STEPS)) + made[keys[k]] = _grid( + own, repair, durations[k], length, node, steps=steps + ) + fresh = head is None + out = [] + following = _followed((made[key] for key in keys), head) + for g, row, replaced, failures in following: + out.append( + BlockAvailability( + g.interval, + g.grid, + row[None, :], + np.array([replaced]), + g.replace, + False, + failures[None, :], + fresh, + ) + ) + fresh = False + return out + + def block_availability( life, repair, @@ -572,10 +738,10 @@ def block_availability( As ``block_cycle`` does, or if the availability has not settled into repeating within the intervals the grid can keep. """ - from scipy.signal import fftconvolve + from itertools import repeat g = _grid(life, repair, duration, interval, node) - steps, h = g.steps, g.h + steps = g.steps most = max(3, _MAX_VALUES // (steps + 1)) # An infinite horizon: until it settles, for its long-run cycle. count = ( @@ -583,32 +749,12 @@ def block_availability( if np.isfinite(horizon) else most + 1 ) - # A replacement that starts at the interval's start: the CDF of when - # the unit is back in service, and its integral. - start_P = g.replace.cdf(g.rho) - start_C = g.rho - g.replace.in_progress(g.rho) - down = 1.0 - g.A - if head is None: - # The first interval: put into service new at 0. - P = np.ones(g.length + 1) - C = g.rho.copy() - other = np.zeros(g.length + 1) - replaced = 1.0 - else: - other, C, replaced = _head_start(head, g) - P = other + replaced * start_P - C = C + replaced * start_C rows: list = [] probabilities: list = [] failing: list = [] settled = False - for k in range(count): - w = _masses(P, C, steps, h) - row = other[: steps + 1] - fftconvolve(w, down)[: steps + 1] - # Failures in each cell of this interval, from the units put into - # service in it, and their running count over the interval. - density = np.diff(fftconvolve(w, g.N)[: steps + 1]) / h - failures = np.concatenate([[0.0], np.cumsum(density * h)]) + following = _followed(repeat(g, count), head) + for k, (_, row, replaced, failures) in enumerate(following): if ( k >= 2 and abs(replaced - probabilities[-1]) < _SETTLED @@ -627,12 +773,6 @@ def block_availability( rows.append(row) probabilities.append(replaced) failing.append(failures) - other, C, in_repair = _carry(P, C, density, g) - # Up at the next block time: put into service in this interval and - # not in a repair at its end (so that no probability is lost). - replaced = float(P[steps]) - in_repair - P = other + replaced * start_P - C = C + replaced * start_C return BlockAvailability( g.interval, g.grid, diff --git a/repyability/rbd/_ccf_groups.py b/repyability/rbd/_ccf_groups.py index f89c844c..0bb39225 100644 --- a/repyability/rbd/_ccf_groups.py +++ b/repyability/rbd/_ccf_groups.py @@ -35,6 +35,7 @@ _Cause, ) from repyability.rbd._model_utils import distribution_name, never_fails +from repyability.rbd.ccf import Shocks from repyability.rbd.modular import GraphStructure from repyability.utils.checks import ( structure_method, @@ -60,12 +61,20 @@ def _ccf_rates(rbd, group) -> Tuple[float, Optional[float]]: rate (None for hidden failures, found by tests), for its chain (see ``_ccf_chain``); raise if the chain does not cover them.""" where = f"Common-cause group {list(group.members)}" + if isinstance(group.model, Shocks): + raise NotImplementedError( + f"{where}: its shocks come at a rate of their own while its " + "members keep their own lives, which no chain of the group " + "follows. Estimate the values by simulation, with " + "availability() or cost()." + ) if rbd._crews_couple(): raise NotImplementedError( - f"{where}: with limited repair crews, the crews' Markov " - "chain does not take common causes in, as yet. Estimate the " - "values by simulation, with availability() or cost(), which " - "take both." + f"{where}: with limited repair crews its members wait for " + "a crew with the other components, which the group's own " + "chain does not follow (the crews' Markov chain takes the " + "group in where it works the values out). Estimate the " + "values by simulation, with availability() or cost()." ) rates = set() for member in group.members: @@ -222,13 +231,23 @@ def _shared_causes(rbd) -> List[_Cause]: ``_own_rate``).""" out = [] for group in rbd.ccf_groups: - rate = _constant_rate(rbd.components[group.members[0]].reliability) - if rate is None: - continue # refused (see _require_groups_simulated) coins = any( member in rbd._inspection and rbd._inspection[member].partial for member in group.members ) + if isinstance(group.model, Shocks): + # Shocks at a rate of their own: every set of members a shock + # can fail is a cause, one member's too (its own life is its + # own model's). A cause names its members in the group's + # order, the order a strike fails them in. + out += [ + _Cause(struck, rate, coins) + for struck, rate in group.model.causes(group.members) + ] + continue + rate = _constant_rate(rbd.components[group.members[0]].reliability) + if rate is None: + continue # refused (see _require_groups_simulated) for struck, cause in _ccf_chain.causes( group.model, group.members, rate ): @@ -251,6 +270,8 @@ def _own_rate(rbd, node) -> Optional[float]: which the simulation refuses, see ``_require_groups_simulated``).""" for group in rbd.ccf_groups: if node in group.members: + if isinstance(group.model, Shocks): + return None # its own life is its own model's rate = _constant_rate(rbd.components[node].reliability) if rate is None: return None @@ -273,9 +294,10 @@ def _require_groups_simulated(rbd, states: Optional[dict] = None): for group in rbd.ccf_groups: where = f"Common-cause group {list(group.members)}" + shocked = isinstance(group.model, Shocks) for member in group.members: life = rbd.components[member].reliability - if _constant_rate(life) is None: + if not shocked and _constant_rate(life) is None: raise NotImplementedError( f"{where}: its members' failure rate is split " "between the causes, which needs exponential lives, " @@ -291,8 +313,25 @@ def _require_groups_simulated(rbd, states: Optional[dict] = None): f"{where}: member {member!r} has {what}, which " "the simulation of its group does not take in, " "as yet." + + ( + " Simulate the diagram with the member left " + f"out of the group, or without its {what}." + if shocked + else "" + ) ) start = (states or {}).get(member) + if shocked: + if start is not None and member in rbd._inspection: + raise NotImplementedError( + f"{where}: member {member!r} is tested and " + "started from a state, and a shock may have " + "failed it, unseen, since its last test, which " + "the simulation does not draw for a member with " + "a life of its own. Start it as new (leave it " + "out of the states)." + ) + continue if start is not None and start.own_life: raise NotImplementedError( f"{where}: member {member!r} has a life of its own " @@ -305,6 +344,13 @@ def _require_groups_simulated(rbd, states: Optional[dict] = None): _require_groups_simulated(component) +def _own_chains(rbd) -> bool: + """Whether the common-cause groups are worked out by chains of their + own: not with limited repair crews, whose chain takes the groups in + with the queue (#251, see ``_crews._crew_causes``).""" + return bool(rbd.ccf_groups) and not rbd._crews_couple() + + def _require_ccf_long_run(rbd) -> None: """Raise if a common-cause group's chain does not cover it.""" for group in rbd.ccf_groups: @@ -820,8 +866,9 @@ def _ccf_fv_shares( def _require_ccf_frequencies(rbd) -> None: """Raise if the failure frequency with common-cause groups is not - worked out: where their long-run values are not.""" - if rbd.ccf_groups: + worked out: where their long-run values are not (with limited repair + crews, their chain has the groups' frequencies).""" + if _own_chains(rbd): _require_ccf_long_run(rbd) diff --git a/repyability/rbd/_chain_transient.py b/repyability/rbd/_chain_transient.py index 5eb3d72e..7efa7687 100644 --- a/repyability/rbd/_chain_transient.py +++ b/repyability/rbd/_chain_transient.py @@ -317,22 +317,24 @@ class CrewSystem: len(nested)`` of them, see ``pattern_weights``), whether it is up in each state, then for each pattern the rate of its failures by the chain's components in each state, then whether each of the chain's - ``served`` components is up; with ``causes``, then for each pattern - the rate of its failures by each of them. The nested RBDs have + ``served`` components is up; with ``causes`` (their keys), then for + each pattern the rate of its failures by each of them. The nested + RBDs have crews of their own, so they are independent of the chain: at a time, the system is up with probability ``sum_m p(t) u_m w_m(t)``, ``w_m`` the pattern's probability from their availabilities then, and a nested RBD's Birnbaum importance is the difference that it being up makes.""" def __init__( - self, chain: Uniformized, nested: Sequence, served=(), causes=False + self, chain: Uniformized, nested: Sequence, served=(), causes=() ): self.chain = chain self.nested = list(nested) self.served = list(served) self.patterns = 2 ** len(self.nested) - #: The chain's components whose failures are counted apart. - self.cause_keys = list(self.served) if causes else [] + #: Whose failures are counted apart (``causes``): the chain's + #: components, and its common-cause groups' shared causes. + self.cause_keys = list(causes) #: For the pieces of the integrals: the chain's knots and settling. self.curve = ChainCurve(chain) @@ -392,7 +394,8 @@ def caused(self, values: dict, x: np.ndarray) -> dict: for node in self.nested ] ) - base, count = 2 * self.patterns + len(self.served), len(self.served) + base = 2 * self.patterns + len(self.served) + count = len(self.cause_keys) return { node: np.maximum( np.sum( @@ -402,7 +405,7 @@ def caused(self, values: dict, x: np.ndarray) -> dict: ), 0.0, ) - for k, node in enumerate(self.served) + for k, node in enumerate(self.cause_keys) } diff --git a/repyability/rbd/_common.py b/repyability/rbd/_common.py index d48e8121..e8879c8b 100644 --- a/repyability/rbd/_common.py +++ b/repyability/rbd/_common.py @@ -1,21 +1,21 @@ -"""Small helpers the ``RepairableRBD`` modules share: the checks of a -horizon and a discount rate, a model's mean, survival and cumulative -distribution as arrays, a constant failure rate, the common period of -inspection intervals, and the shapes results take. +"""Small helpers the ``RepairableRBD`` modules share: the check of a +horizon (the discount checks are ``repyability.value``'s), a model's +mean, survival and cumulative distribution as arrays, a constant +failure rate, the common period of inspection intervals, the repair +crews' salaries, and the shapes results take. """ import functools import math import numbers -import warnings import weakref from fractions import Fraction from typing import ( Any, Callable, Iterable, - List, Optional, + Tuple, ) import numpy as np @@ -26,9 +26,14 @@ ) from repyability.utils.checks import ( number_or_nan, - real_array, ) -from repyability.utils.wrappers import outside_level +from repyability.value import _rates + +# The discount checks are the money module's (``repyability.value``), +# kept under the names the diagram's modules import. +_discount_rate = _rates.discount_rate +_horizons = _rates.horizons +_present_horizon = _rates.present_horizon def _keeps_virtual_age(rbd, node) -> bool: @@ -252,91 +257,6 @@ def _horizon(horizon) -> float: return value -def _discount_rate(discount_rate) -> float: - """``discount_rate`` as a float: a ValueError unless it is a finite, - non-negative number (#184).""" - number = isinstance( - discount_rate, (int, float, np.integer, np.floating) - ) and not isinstance(discount_rate, bool) - rate = float(discount_rate) if number else float("nan") - if not (np.isfinite(rate) and rate >= 0.0): - raise ValueError( - "discount_rate must be a finite, non-negative number (a " - "continuous rate per unit time of the component models), got " - f"{discount_rate!r}." - ) - return rate - - -def _horizons(horizon, rate: float) -> np.ndarray: - """``horizon``, a number or an array of them, as an array of - non-negative floats: finite, unless costs are discounted at ``rate`` - (#231), where an endless horizon is worth ``1 / rate`` of a steady - cost rate. Else a ValueError.""" - try: - values = real_array(horizon, "horizon") - except (TypeError, ValueError): - values = np.array(np.nan) - if values.size and np.all(values >= 0.0) and np.all(values < np.inf): - return values - if values.size and np.all(values >= 0.0): - if rate > 0.0: - return values - raise ValueError( - "horizon must be finite without a discount_rate: an undiscounted " - f"cost over an endless horizon is endless; got {horizon!r}." - ) - raise ValueError( - "horizon must be a finite, non-negative number (or an array of " - f"them; inf with a discount_rate), got {horizon!r}." - ) - - -#: A discount rate times the shortest of the components' mean lives -#: beyond which their failures' costs are discounted to almost nothing -#: (``exp(-20)``, 2e-9), and times a horizon beyond which the whole time -#: scale is: a rate given per year with the models in hours, say (#231). -#: A long horizon is no mistake in itself. -_DISCOUNTED_AWAY = 20.0 - - -_HORIZON_AWAY = 1000.0 - - -def _present_horizon( - horizons: np.ndarray, - rate: float, - lives: Callable[[], List[float]] = list, -) -> np.ndarray: - """What a unit cost rate over ``[0, horizon)`` is worth at the start, - discounted continuously at ``rate`` per unit time (#184): ``(1 - - exp(-rate * horizon)) / rate``, the horizon itself undiscounted, and - ``1 / rate`` for an endless one; for each of ``horizons``. Warns where - the rate discounts the costs away (#231): times the shortest of the - components' mean ``lives`` more than ``_DISCOUNTED_AWAY``, or times a - horizon more than ``_HORIZON_AWAY``.""" - if rate == 0.0: - return horizons - known = [life for life in lives() if 0.0 < life < math.inf] - finite = horizons[np.isfinite(horizons)] - span, what = 0.0, "" - if known and rate * min(known) > _DISCOUNTED_AWAY: - span, what = min(known), "the components' shortest mean life" - elif finite.size and rate * float(finite.max()) > _HORIZON_AWAY: - span, what = float(finite.max()), "the horizon" - if what: - warnings.warn( - f"discount_rate {rate:g} discounts the costs at {what} " - f"({span:g}) by a factor of exp(-{rate * span:.3g}), to " - "almost nothing: it is a continuous rate per unit time of the " - "component models. For an annual rate i with models in hours, " - "give math.log(1 + i) / 8760 (7% a year: " - f"{math.log(1.07) / 8760:.3g} an hour).", - stacklevel=outside_level(), - ) - return -np.expm1(-rate * horizons) / rate - - #: How closely a discounted expected cost from new is worked out (#231): #: its integral by parts, to this share of itself. _DISCOUNT_TOLERANCE = 1e-8 @@ -347,6 +267,25 @@ def _present_horizon( _DISCOUNT_ROUNDS = 60 +def _crew_salaries(rbd) -> float: + """The repair crews' salaries per unit time: ``repair_crews`` crews at + ``crew_cost_rate`` each, a cost of the system that does not depend on + what happens in it; 0.0 when the crews are not priced.""" + rate = getattr(rbd, "crew_cost_rate", 0.0) + return float(rbd.repair_crews) * rate if rate else 0.0 + + +def _crew_salaries_to(rbd, ends, rate: float = 0.0) -> np.ndarray: + """The crews' salaries from 0 to each of ``ends``, discounted at + ``rate``: ``n c T``, or ``n c (1 - exp(-r T)) / r`` (see + ``_crew_salaries``).""" + ends = np.asarray(ends, dtype=float) + paid = _crew_salaries(rbd) + if not rate: + return paid * ends + return paid * -np.expm1(-rate * ends) / rate + + def _discount_pieces(ends: np.ndarray, horizon: float): """The first pieces of a discounted cost's integral (see ``RepairableRBD._discounted_cost``): from 0 to ``horizon`` in 32, @@ -357,6 +296,69 @@ def _discount_pieces(ends: np.ndarray, horizon: float): return edges[:-1], edges[1:] +def _discounted_accrual( + values: Callable[[np.ndarray], np.ndarray], + ends: np.ndarray, + rate: float, + pieces: Tuple[np.ndarray, np.ndarray], + tolerance: float = _DISCOUNT_TOLERANCE, +): + """The present value at 0, at the continuous ``rate``, of a cost that + accrues as ``C``, to each of ``ends``: ``exp(-r T) C(T) + r * + integral_0^T exp(-r s) C(s) ds``, the one design of an accrued + cost's present value, for a diagram's expected cost (#231) and a + schedule's forecast alike. ``values(times)`` is ``C`` at ``times``, + as rows (several costs at once). The integral is taken by the + Gauss-Kronrod (7, 15) rule on ``pieces`` (``(starts, stops)``, with + every one of ``ends`` among the stops), and the pieces whose two + rules differ most are halved until the first row's differences add + up to ``tolerance`` of its integral, for at most + ``_DISCOUNT_ROUNDS`` rounds: ``C`` may jump (at a scheduled event) + or bend, where a piece's error only shrinks with it. Returns the + present values (rows by ``ends``) and the first row's error, ``r`` + times the rules' differences (a bound on the integral's error).""" + from ._mean_lifetime import _G7_W, _GK_W, _GK_X + + at_ends = values(ends) + + def rules(a: np.ndarray, b: np.ndarray): + """The pieces' integrals of ``exp(-r s) C(s)`` by the Kronrod + rule, as rows, and the first row's error, against the Gauss + rule.""" + half = 0.5 * (b - a) + x = (0.5 * (a + b))[:, None] + half[:, None] * _GK_X + g = np.exp(-rate * x) * values(x.ravel()).reshape(-1, *x.shape) + kronrod = (g @ _GK_W) * half + return kronrod, np.abs(kronrod[0] - (g[0] @ _G7_W) * half) + + a, b = pieces + found, error = rules(a, b) + for _ in range(_DISCOUNT_ROUNDS): + budget = tolerance * abs(float(found[0].sum())) + if error.sum() <= budget: + break + # Halve the pieces over their share of the error allowed. + split = error > budget / error.size + middle = 0.5 * (a + b)[split] + halves, errors = rules( + np.concatenate([a[split], middle]), + np.concatenate([middle, b[split]]), + ) + a = np.concatenate([a[~split], a[split], middle]) + b = np.concatenate([b[~split], middle, b[split]]) + found = np.concatenate([found[:, ~split], halves], axis=1) + error = np.concatenate([error[~split], errors]) + order = np.argsort(b, kind="stable") + running = np.concatenate( + [np.zeros((len(at_ends), 1)), np.cumsum(found[:, order], axis=1)], + axis=1, + ) + # Every end is a piece's end: the pieces up to it are within it. + upto = np.searchsorted(b[order], ends, side="right") + present = np.exp(-rate * ends) * at_ends + rate * running[:, upto] + return present, abs(rate) * float(error.sum()) + + def _common_period(intervals: Iterable[float]) -> float: """The least common multiple of the inspection intervals: the period after which the schedules repeat together.""" diff --git a/repyability/rbd/_compiled.py b/repyability/rbd/_compiled.py index 306bfdaf..ce72038c 100644 --- a/repyability/rbd/_compiled.py +++ b/repyability/rbd/_compiled.py @@ -132,10 +132,17 @@ def _unsupported_level( if rbd._too_meshed() is not None: # Its structure is the graph itself (modular.GraphStructure). return "a structure too meshed to work out" + if rbd._upgrades: + # A unit's life changes at the upgrade (the Python loop's + # _UpgradedComponent). + return "an upgrade" if rbd.ccf_groups: return "common-cause groups" if _crews._crews_limited(rbd) and not numba: return "repair crews" + if _crews._call_when(rbd): + # The Python loop's queue has the call-out crew's rule alone. + return "a call-out crew" if rbd._standby and not numba: return "standby groups" if rbd._maintenance: @@ -143,13 +150,19 @@ def _unsupported_level( if rbd._shutdowns and ( not numba or any( - shut.duration > 0.0 or shut.cost or not shut.periodic + shut.duration > 0.0 + or shut.cost + or not shut.periodic + or shut.opportunistic is not None for shut in rbd._shutdowns.values() ) + or any(s.shuts is not None for s in rbd._preventive.values()) ): # numba's own loop runs the tasks bound to shuts on a period that # take no time and cost nothing (block replacement and tests with - # the shut's offset), which are those shuts entirely. + # the shut's offset), which are those shuts entirely; not the + # renewals a shut makes opportunistically, which the Python loop + # makes at its starts, nor a block renewed at several shuts. return "shutdowns" if rbd._imperfect: return "imperfect repair" @@ -181,8 +194,16 @@ def _unsupported_level( continue if type(component) is not NonRepairable: return f"the {type(component).__name__} of node {name!r}" - if scheduled(component) is not None: - return f"the covariate schedule of node {name!r}" + clocked = scheduled(component) + if clocked is not None: + # A life on the diagram's clock (the Python loop's + # _ScheduledComponent). + what = ( + "covariate schedule" + if clocked.lead.endswith("covariate schedule") + else "duty plan that changes over time" + ) + return f"the {what} of node {name!r}" if not _streamed(prefix + (name,), plan, rbd._standby.get(name)): return ( f"the models of node {name!r} (their draws cannot be " @@ -195,11 +216,14 @@ def _unsupported_maintenance( rbd, plan: _streams.Plan, prefix: tuple = () ) -> Optional[str]: """What in a run's preventive maintenance numba's loop cannot simulate: - replacement on condition or on a calendar policy, and a maintenance + replacement at the times of a plan (a ``"replace_at"``), on condition + or on a calendar policy, and a maintenance time whose draws cannot be streamed. (A component whose own draws cannot be is refused for that, and every drawn cost is streamed.)""" for node, schedule in rbd._preventive.items(): + if schedule.plan is not None: + return "replacement at the times of a plan" if schedule.policy == "condition": return "replacement on condition" if schedule.policy == "calendar": diff --git a/repyability/rbd/_condition_replacement.py b/repyability/rbd/_condition_replacement.py index f68838bf..b534163b 100644 --- a/repyability/rbd/_condition_replacement.py +++ b/repyability/rbd/_condition_replacement.py @@ -59,6 +59,7 @@ _grid, _head_start, _masses, + _onto, _values, ) from ._model_utils import model_mean @@ -451,71 +452,61 @@ def _head_ages(head: ConditionHead, g, ages: _Ages) -> np.ndarray: return up * (wanted / total) -def condition_availability( - life, - repair, - duration, - interval: float, - threshold: float, - horizon: float, - node=None, - head: Optional[ConditionHead] = None, - older_than: Optional[float] = None, -) -> BlockAvailability: - """The point availability of a component replaced on condition, new at - 0 (or after ``head``), over ``[0, horizon]`` or until it repeats from - one inspection interval to the next (see the module docstring). - - Parameters - ---------- - life, repair, duration, interval, threshold, node - As for ``condition_cycle``. - horizon : float - The last time the availability is needed at (from the first - inspection, after a ``head``); ``inf`` to follow it until it - settles (into its long-run cycle). - head : ConditionHead, optional - How the unit reaches its first inspection, started from a state; - by default None: new at 0. - older_than : float, optional - As for ``condition_cycle``. - - Returns - ------- - BlockAvailability - With ``inspected``, the probability that the unit is up at each - interval's starting inspection; ``replaced``, that the inspection - replaces it. - - Raises - ------ - NotImplementedError - As ``condition_cycle`` does, or if the availability has not settled - into repeating within the intervals the grid can keep. - """ +def _regrid(lo: int, masses: np.ndarray, h: float, onto: float): + """Masses on the age grid of step ``h`` (from age index ``lo``) put + onto the grid of step ``onto``: each split between the two nearest + ages of the new grid, so that the total and the mean age are kept.""" + if not masses.size or onto == h: + return lo, masses + x = (lo + np.arange(masses.size)) * (h / onto) + below = np.floor(x).astype(np.int64) + upper = x - below + first = int(below[0]) + out = np.zeros(int(below[-1]) - first + 2) + np.add.at(out, below - first, masses * (1.0 - upper)) + np.add.at(out, below - first + 1, masses * upper) + return first, out + + +class _Stretch(NamedTuple): + """An interval from one inspection to the next: its grid, and the + ages (on that grid's step) its starting inspection judges with.""" + + grid: object + ages: _Ages + + +def _followed(stretches, head: Optional[ConditionHead], life): + """A unit replaced on condition followed from one inspection to the + next (see ``condition_availability``), each interval on its own + ``_Stretch``: the same again and again on a period, one for each + stretch between given times. Yields each interval's grid, the smooth + part of the availability on it, the probability replaced at its + start, its expected failures by each grid point and the probability + up at its starting inspection.""" from scipy.signal import fftconvolve - g = _grid(life, repair, duration, interval, node, starts=True) - assert g.renewals is not None and g.done is not None # starts=True - steps, h, T = g.steps, g.h, g.interval - ages = _Ages(life, h, T, threshold, older_than) - ages.cover(steps) - most = max(3, _MAX_VALUES // (steps + 1)) - count = ( - int(np.floor(horizon / T)) + 1 if np.isfinite(horizon) else most + 1 - ) - renewals = np.diff(g.renewals) - put_in = np.zeros(steps + 1) - put_in[0] = 1.0 - put_in[:-1] += 0.5 * renewals - put_in[1:] += 0.5 * renewals - ending = np.diff(g.done) - start_P = g.replace.cdf(g.rho) - start_C = g.rho - g.replace.in_progress(g.rho) - down = 1.0 - g.A sf = life.sf + made: dict = {} + + def of(g): + """What a grid's intervals take, worked out once for each.""" + if id(g) not in made: + renewals = np.diff(g.renewals) + put_in = np.zeros(g.steps + 1) + put_in[0] = 1.0 + put_in[:-1] += 0.5 * renewals + put_in[1:] += 0.5 * renewals + made[id(g)] = ( + put_in, + np.diff(g.done), + g.replace.cdf(g.rho), + g.rho - g.replace.in_progress(g.rho), + 1.0 - g.A, + ) + return made[id(g)] - def inspect(lo_up: int, by_age: np.ndarray, first): + def inspect(ages: _Ages, lo_up: int, by_age: np.ndarray, first): """The inspection: the units up at it by age on the grid (from ``lo_up``), and the first unit at its exact age; those old enough are replaced. Returns the probability replaced, inspected, the @@ -538,33 +529,49 @@ def inspect(lo_up: int, by_age: np.ndarray, first): first = None return replaced, inspected, lo, aged, first - def starts_after(cells: np.ndarray) -> np.ndarray: - """The CDF, on ``g.rho``, of the units put into service after the - repairs of the failures in each cell of an interval.""" - started = np.zeros(g.length + 1) - started[1:] = fftconvolve(cells / h, ending)[: g.length] - return np.clip(started, 0.0, None) - - if head is None: - # The first interval: put into service new at 0, no inspection. - P = np.ones(g.length + 1) - C = g.rho.copy() - other = np.zeros(g.length + 1) - replaced, inspected = 1.0, 0.0 - lo, aged, first = 0, np.empty(0), None - else: - other, C, _ = _head_start(head, g) # type: ignore[arg-type] - replaced, inspected, lo, aged, first = inspect( - 0, _head_ages(head, g, ages), head.first - ) - P = other + replaced * start_P - C = C + replaced * start_C - rows: list = [] - probabilities: list = [] - failing: list = [] - looked: list = [] - settled = False - for k in range(count): + previous = None + for stretch in stretches: + g, ages = stretch.grid, stretch.ages + steps, h, T = g.steps, g.h, g.interval + put_in, ending, start_P, start_C, down = of(g) + + def starts_after(cells: np.ndarray) -> np.ndarray: + """The CDF, on ``g.rho``, of the units put into service after + the repairs of the failures in each cell of an interval.""" + started = np.zeros(g.length + 1) + started[1:] = fftconvolve(cells / h, ending)[: g.length] + return np.clip(started, 0.0, None) + + if previous is None: + if head is None: + # The first interval: put into service new at 0, no + # inspection. + P = np.ones(g.length + 1) + C = g.rho.copy() + other = np.zeros(g.length + 1) + replaced, inspected = 1.0, 0.0 + lo, aged, first = 0, np.empty(0), None + else: + other, C, _ = _head_start(head, g) # type: ignore + replaced, inspected, lo, aged, first = inspect( + ages, 0, _head_ages(head, g, ages), head.first + ) + P = other + replaced * start_P + C = C + replaced * start_C + else: + # The inspection that ends the last interval, judged on this + # one's grid of ages. + last, lo_up, by_age, after, carried = previous + if last is not g: + lo_up, by_age = _regrid(lo_up, by_age, last.h, h) + other, C = _onto(*carried, last, g) + else: + other, C = carried + replaced, inspected, lo, aged, first = inspect( + ages, lo_up, by_age, after + ) + P = other + replaced * start_P + C = C + replaced * start_C kept_up = np.zeros(steps + 1) kept_cells = np.zeros(steps) survivors = np.empty(0) @@ -614,8 +621,80 @@ def starts_after(cells: np.ndarray) -> np.ndarray: row = other[: steps + 1] - fftconvolve(w, down)[: steps + 1] + kept_up density = np.diff(fftconvolve(w, g.N)[: steps + 1]) / h failures = np.concatenate([[0.0], np.cumsum(density * h + kept_cells)]) + yield g, row, replaced, failures, inspected + # The units up at the inspection that ends the interval, by age: + # those put into service in it, as old as the time since, and those + # kept, an interval older. + fresh = fftconvolve(w, put_in)[: steps + 1] * ages.R[steps::-1] + total, wanted = float(fresh.sum()), float(w @ g.A[::-1]) + if total > 0.0: + fresh *= wanted / total + lo_up, by_age = _merge(0, fresh[::-1], lo + steps, survivors) + other, C, _ = _carry(P, C, density, g) + previous = (g, lo_up, by_age, after, (other, C)) + + +def condition_availability( + life, + repair, + duration, + interval: float, + threshold: float, + horizon: float, + node=None, + head: Optional[ConditionHead] = None, + older_than: Optional[float] = None, +) -> BlockAvailability: + """The point availability of a component replaced on condition, new at + 0 (or after ``head``), over ``[0, horizon]`` or until it repeats from + one inspection interval to the next (see the module docstring). + + Parameters + ---------- + life, repair, duration, interval, threshold, node + As for ``condition_cycle``. + horizon : float + The last time the availability is needed at (from the first + inspection, after a ``head``); ``inf`` to follow it until it + settles (into its long-run cycle). + head : ConditionHead, optional + How the unit reaches its first inspection, started from a state; + by default None: new at 0. + older_than : float, optional + As for ``condition_cycle``. + + Returns + ------- + BlockAvailability + With ``inspected``, the probability that the unit is up at each + interval's starting inspection; ``replaced``, that the inspection + replaces it. + + Raises + ------ + NotImplementedError + As ``condition_cycle`` does, or if the availability has not settled + into repeating within the intervals the grid can keep. + """ + g = _grid(life, repair, duration, interval, node, starts=True) + assert g.renewals is not None and g.done is not None # starts=True + steps, T = g.steps, g.interval + ages = _Ages(life, g.h, T, threshold, older_than) + ages.cover(steps) + most = max(3, _MAX_VALUES // (steps + 1)) + count = ( + int(np.floor(horizon / T)) + 1 if np.isfinite(horizon) else most + 1 + ) + stretch = _Stretch(g, ages) + rows: list = [] + probabilities: list = [] + failing: list = [] + looked: list = [] + settled = False + following = _followed((stretch for _ in range(count)), head, life) + for _, row, replaced, failures, inspected in following: if ( - k >= 2 + len(rows) >= 2 and abs(replaced - probabilities[-1]) < _SETTLED and abs(inspected - looked[-1]) < _SETTLED and np.max(np.abs(row - rows[-1])) < _SETTLED @@ -634,18 +713,6 @@ def starts_after(cells: np.ndarray) -> np.ndarray: probabilities.append(replaced) failing.append(failures) looked.append(inspected) - # The units up at the inspection that ends the interval, by age: - # those put into service in it, as old as the time since, and those - # kept, an interval older. - fresh = fftconvolve(w, put_in)[: steps + 1] * ages.R[steps::-1] - total, wanted = float(fresh.sum()), float(w @ g.A[::-1]) - if total > 0.0: - fresh *= wanted / total - lo_up, by_age = _merge(0, fresh[::-1], lo + steps, survivors) - other, C, _ = _carry(P, C, density, g) - replaced, inspected, lo, aged, first = inspect(lo_up, by_age, after) - P = other + replaced * start_P - C = C + replaced * start_C return BlockAvailability( T, g.grid, @@ -657,3 +724,92 @@ def starts_after(cells: np.ndarray) -> np.ndarray: head is None, np.array(looked), ) + + +def condition_plan_availability( + life, + repair, + duration, + lengths, + threshold: float, + node=None, + head: Optional[ConditionHead] = None, + older_than: Optional[float] = None, + last_like: Optional[float] = None, +) -> list: + """The point availability of a component inspected at the times of a + plan (a shutdown's given times) and replaced there on condition, + stretch by stretch: a ``BlockAvailability`` of one interval for each + of ``lengths``, the times from one inspection (or 0, or the end of a + ``head``) to the next. + + The unit is followed as ``condition_availability`` follows it, each + stretch on a grid of its own length (stretches of one length share + theirs, so that equal stretches are inspection on that period). What + is carried from one stretch into the next is put onto the next one's + grid: the repairs and replacements still going on (``_onto``), and the + units the inspection kept, by age, each age's mass split between the + two nearest ages of the new grid (``_regrid``). An inspection judges a + unit by the time to the next one (the stretch it starts), or, at the + last, by none to come: a unit is then more likely than any threshold + below 1 to fail before it, as the simulation has it. + + Parameters + ---------- + life, repair, duration, threshold, node, head, older_than + As for ``condition_availability``. + lengths : sequence of float + Each stretch's length, positive. + last_like : float, optional + For a last stretch that ends at no time of the plan: the length of + a stretch whose grid's step it takes (see + ``_block_replacement.plan_availability``); its inspection at the + start is the plan's last. + + Returns + ------- + list of BlockAvailability + """ + from ._block_replacement import _MAX_LAST_STEPS, _MIN_STEPS, _steps + + count = len(lengths) + open_end = last_like is not None + made: dict = {} + stretches = [] + for k, length in enumerate(lengths): + steps = None + if last_like is not None and k == count - 1: + wanted = _steps(life, last_like) * length / last_like + steps = int(np.clip(np.ceil(wanted), _MIN_STEPS, _MAX_LAST_STEPS)) + # The time its starting inspection looks ahead to: none at the + # plan's last. + ahead = np.inf if open_end and k == count - 1 else float(length) + key = (float(length), steps, ahead) + if key not in made: + g = _grid( + life, repair, duration, length, node, starts=True, steps=steps + ) + ages = _Ages(life, g.h, ahead, threshold, older_than) + ages.cover(g.steps) + made[key] = _Stretch(g, ages) + stretches.append(made[key]) + out = [] + fresh = head is None + for g, row, replaced, failures, inspected in _followed( + stretches, head, life + ): + out.append( + BlockAvailability( + g.interval, + g.grid, + row[None, :], + np.array([replaced]), + g.replace, + False, + failures[None, :], + fresh, + np.array([inspected]), + ) + ) + fresh = False + return out diff --git a/repyability/rbd/_contract.py b/repyability/rbd/_contract.py new file mode 100644 index 00000000..8e5ee3bc --- /dev/null +++ b/repyability/rbd/_contract.py @@ -0,0 +1,330 @@ +"""One call that values a plan from one JSON document (``value_plan``): +the request names the diagram (``RBD.to_dict()``), the analysis and its +inputs as plain data; the answer is plain data too, strict JSON, with the +request it answers, the units, the route and the result (or the refusal, +with what to run instead). + +The request is the record: ``value_plan(answer["request"])`` gives the +same answer, number for number. A seeded analysis given no seed has one +drawn and written into the request it echoes, so that holds for it too. +The documents' shapes are in ``repyability/schemas/npv-1.json``. +""" + +import dataclasses +import inspect +import math +from typing import Any, Callable, Dict, Hashable, NoReturn, Tuple + +from repyability.rbd import _streams + +#: The version of the request and answer documents. +SCHEMA = 1 + +#: The analyses a request may name. +ANALYSES = ( + "expected_npv", + "expected_npv_uncertainty", + "npv_distribution", + "compare_npv", + "plan_vs_actual", +) + +#: The keys of a request. +REQUEST_KEYS = ("schema", "diagram", "analysis", "inputs", "other") + +#: Inputs no JSON document can give (models, functions): left to Python. +_NOT_JSON = {"uncertainty"} + +#: The analyses that draw random numbers, and so take a ``seed``. +_SEEDED = ("expected_npv_uncertainty", "npv_distribution", "compare_npv") + + +def _fail(message: str) -> NoReturn: + raise ValueError(f"value_plan: {message}") + + +def _strict(value): + """``value`` (plain data) with every number JSON can hold: a float + that is not finite written as the string ``"inf"``, ``"-inf"`` or + ``"nan"``.""" + if isinstance(value, float) and not math.isfinite(value): + return "nan" if math.isnan(value) else ("inf" if value > 0 else "-inf") + if isinstance(value, dict): + return {key: _strict(item) for key, item in value.items()} + if isinstance(value, list): + return [_strict(item) for item in value] + return value + + +def _node(rbd, key) -> Hashable: + """The diagram's node a JSON key names: the node itself, or the one + whose name it spells (a JSON object's keys are text).""" + if key in rbd.components: + return key + for node in rbd.components: + if str(node) == str(key): + return node + _fail( + f"{key!r} is not a component of the diagram; its components are " + f"{[str(node) for node in rbd.components]}." + ) + + +def _by_node(rbd, given, what: str, convert: Callable) -> dict: + if not isinstance(given, dict): + _fail(f"{what} must be an object of a value by component.") + return {_node(rbd, key): convert(value) for key, value in given.items()} + + +def _state(value): + from repyability import NodeState + + if not isinstance(value, dict): + _fail( + f"a state must be an object of NodeState's fields, got {value!r}." + ) + names = {field.name for field in dataclasses.fields(NodeState)} + unknown = sorted(set(value) - names) + if unknown: + _fail( + f"a state has unknown field(s) {unknown}; NodeState takes " + f"{sorted(names)}." + ) + return NodeState(**value) + + +def _timeline(value): + from repyability import Timeline + + if not isinstance(value, dict) or "end" not in value: + _fail( + "a timeline must be an object with end, changes, up and " + f"planned (Timeline.to_dict()), got {value!r}." + ) + return Timeline( + value.get("changes", []), + value["end"], + value.get("up", True), + planned=value.get("planned"), + name=value.get("name"), + ) + + +def _value_rate(value): + if isinstance(value, dict): + from repyability import ValueSchedule + + unknown = sorted(set(value) - {"times", "rates"}) + if unknown or "rates" not in value: + _fail( + "a value_rate schedule is an object of times and rates " + f"(ValueSchedule), got keys {sorted(value)}." + ) + return ValueSchedule(value.get("times", []), value["rates"]) + return value + + +def _escalation(rbd, value): + if not isinstance(value, dict): + _fail("escalation must be an object of a growth rate by name.") + out = {} + for key, rate in value.items(): + named = [node for node in rbd.components if str(node) == str(key)] + out[named[0] if named else key] = rate + return out + + +def _salvage(rbd, value): + if isinstance(value, dict): + return _by_node(rbd, value, "salvage", lambda amount: amount) + return value + + +def _inputs(rbd, analysis: str, given: dict) -> dict: + """The method's keyword arguments from a request's ``inputs``, + checked by name against its signature.""" + method = getattr(rbd, analysis) + names = [ + name + for name, parameter in inspect.signature(method).parameters.items() + if parameter.kind + in (parameter.POSITIONAL_OR_KEYWORD, parameter.KEYWORD_ONLY) + and name not in _NOT_JSON + and not (analysis == "compare_npv" and name == "other") + ] + unknown = sorted(set(given) - set(names)) + if unknown: + _fail( + f"{analysis} takes no input(s) {unknown}; its inputs are " + f"{names}." + ) + convert: Dict[str, Callable[[Any], Any]] = { + "state": lambda v: _by_node(rbd, v, "state", _state), + "start_state": lambda v: _by_node(rbd, v, "start_state", _state), + "timelines": lambda v: _by_node(rbd, v, "timelines", _timeline), + "value_rate": _value_rate, + "escalation": lambda v: _escalation(rbd, v), + "salvage": lambda v: _salvage(rbd, v), + "working_nodes": lambda v: [_node(rbd, n) for n in v], + "broken_nodes": lambda v: [_node(rbd, n) for n in v], + } + return { + name: convert.get(name, lambda v: v)(value) + for name, value in given.items() + } + + +def _diagram(document, what: str): + from repyability import RepairableRBD + + if not isinstance(document, dict): + _fail(f"{what} must be a diagram's to_dict(), an object.") + if document.get("kind") == "unit_plan": + # A unit's plan, valued as its one-node diagram (UC-65 of the + # maintenance README). + from repyability.maintenance._plan import UnitPlan + + return UnitPlan.from_dict(document).diagram() + rbd = RepairableRBD.from_dict(document) + if not isinstance(rbd, RepairableRBD): + _fail(f"{what} must be a RepairableRBD: the NPV analyses are its.") + return rbd + + +def _checked(spec) -> dict: + """The request, checked: its keys, schema, analysis and inputs as an + object (a seed drawn for a seeded analysis given none).""" + if not isinstance(spec, dict): + _fail(f"the request must be an object, got {type(spec).__name__}.") + unknown = sorted(set(spec) - set(REQUEST_KEYS)) + if unknown: + _fail( + f"the request has unknown key(s) {unknown}; it takes " + f"{list(REQUEST_KEYS)}." + ) + if spec.get("schema") != SCHEMA: + _fail( + f"the request's schema must be {SCHEMA} (this version's), got " + f"{spec.get('schema')!r}." + ) + analysis = spec.get("analysis") + if analysis not in ANALYSES: + _fail(f"analysis must be one of {list(ANALYSES)}, got {analysis!r}.") + for key in ("diagram",) + ( + ("other",) if analysis == "compare_npv" else () + ): + if key not in spec: + _fail(f"{analysis} needs {key!r}: a diagram's to_dict().") + if analysis != "compare_npv" and "other" in spec: + _fail("only compare_npv takes 'other', the plan to compare with.") + inputs = spec.get("inputs", {}) + if not isinstance(inputs, dict): + _fail("inputs must be an object of the analysis's inputs by name.") + request = {**spec, "inputs": dict(inputs)} + if analysis in _SEEDED and request["inputs"].get("seed") is None: + request["inputs"]["seed"] = _streams.shared_seed(None) + return request + + +def value_plan(spec: dict) -> dict: + """Value a plan from one JSON document, and answer in one. + + In plain terms: "what is this plan worth?" in one call, for an agent + or a service. The request names a diagram as + [`to_dict`][repyability.RepairableRBD.to_dict] saves it (or a unit's + plan as [`UnitPlan.to_dict`][repyability.UnitPlan.to_dict] saves it, + valued as its one-node diagram), one of the + NPV analyses (``"expected_npv"``, ``"expected_npv_uncertainty"``, + ``"npv_distribution"``, ``"compare_npv"`` with the ``"other"`` plan, + or ``"plan_vs_actual"``), and that method's inputs by name, as plain + data: states as ``NodeState`` fields, timelines as + [`Timeline.to_dict`][repyability.Timeline.to_dict] writes them, a + ``value_rate`` schedule as ``{"times": [...], "rates": [...]}``, and + components by name. The answer echoes the request, gives the units + (the diagram's time unit, money in cost units), the analysis's + route, and the result's ``to_dict()`` or, where the analysis + refuses the diagram, the refusal and every NPV analysis's route. + It is strict JSON: a number that is not finite is the string + ``"inf"``, ``"-inf"`` or ``"nan"``. + + The request is the record: valuing ``answer["request"]`` again gives + the same answer. A seeded analysis given no ``seed`` has one drawn, + and written into the request. The shapes of both documents are in + ``repyability/schemas/npv-1.json`` + ([`npv_schema`][repyability.npv_schema]). + + Parameters + ---------- + spec : dict + ``{"schema": 1, "diagram": ..., "analysis": ..., "inputs": + {...}}`` (and ``"other"`` for ``compare_npv``). + + Returns + ------- + dict + ``schema``, ``analysis``, ``request``, ``units``, ``route`` and + ``result`` (or ``refused``). + + Raises + ------ + ValueError + If the request is not one: an unknown key or input (named, with + those it takes), another schema, an analysis not listed, or a + component the diagram does not have. + + Examples + -------- + >>> import surpyval as surv + >>> from repyability import RepairableRBD, value_plan + >>> pump = RepairableRBD( + ... [("s", "p"), ("p", "t")], + ... {"p": {"reliability": surv.Exponential.from_params([0.01]), + ... "repairability": surv.Exponential.from_params([0.5]), + ... "repair_cost": 100.0}}, + ... ) + >>> answer = value_plan({ + ... "schema": 1, + ... "diagram": pump.to_dict(), + ... "analysis": "expected_npv", + ... "inputs": {"horizon": 100.0, "discount_rate": 0.001}, + ... }) + >>> answer["route"]["route"], round(answer["result"]["cost"], 2) + ('numerical', 93.34) + >>> value_plan(answer["request"]) == answer + True + """ + from repyability.rbd import routes as r + from repyability.rbd.results import plain + + request = _checked(spec) + analysis = request["analysis"] + rbd = _diagram(request["diagram"], "diagram") + kwargs = _inputs(rbd, analysis, request["inputs"]) + args: Tuple[Any, ...] = () + if analysis == "compare_npv": + args = (_diagram(request["other"], "other"),) + route = rbd.analysis_routes()[analysis] + answer: Dict[str, Any] = { + "schema": SCHEMA, + "analysis": analysis, + "request": request, + "units": { + "time": plain(getattr(rbd, "unit", None)), + "money": "cost units", + }, + "route": {"route": route.route, "reason": route.reason}, + } + try: + result = getattr(rbd, analysis)(*args, **kwargs) + except (NotImplementedError, r.Refused) as error: + answer["refused"] = { + "reason": str(error), + "routes": { + name: found.route + for name, found in rbd.analysis_routes().items() + if name in ANALYSES + }, + } + else: + answer["result"] = plain(result) + return _strict(plain(answer)) diff --git a/repyability/rbd/_costs.py b/repyability/rbd/_costs.py index 15a0fafd..a5a118fd 100644 --- a/repyability/rbd/_costs.py +++ b/repyability/rbd/_costs.py @@ -19,6 +19,7 @@ from repyability.rbd import _crews, _long_run, _requirements, _shutdowns from repyability.rbd._common import ( + _crew_salaries, _discount_rate, _horizons, _present_horizon, @@ -45,8 +46,12 @@ def expected_cost_rate( _requirements._require_separate_setups(rbd) _shutdowns.require_exact(rbd) - # The shutdowns' own costs, at each shut. - rate = _shutdowns.cost_rate(rbd) + # The shutdowns' own costs, at each shut, and the repair crews' + # salaries, paid whatever happens. + rate = _shutdowns.cost_rate(rbd) + _crew_salaries(rbd) + # A call-out crew's fees and its rate while engaged, from the crews' + # chain. + rate += _crews._call_out_cost_rate(rbd, working_nodes, broken_nodes) # Production lost while the *system* is down. if rbd.downtime_cost_rate: @@ -224,6 +229,10 @@ def total_cost( ) -> Union[float, np.ndarray]: """See ``RepairableRBD.total_cost``.""" _requirements._require_costs(rbd) + if rbd._upgrades: + # Its long-run rate is the one once upgraded, which the horizon + # from 0 (and the upgrade's capital cost) is not. + _requirements._require_no_plans(rbd) rate = _discount_rate(discount_rate) present = _present_horizon( _horizons(horizon, rate), rate, partial(_requirements._mean_lives, rbd) diff --git a/repyability/rbd/_covariate_schedule.py b/repyability/rbd/_covariate_schedule.py index 00173fbd..49f7f61c 100644 --- a/repyability/rbd/_covariate_schedule.py +++ b/repyability/rbd/_covariate_schedule.py @@ -59,18 +59,66 @@ def is_scheduled(model) -> bool: - """Whether ``model`` is a life under a covariate schedule.""" - return isinstance(model, ScheduledLife) + """Whether ``model`` is a life on the diagram's clock (a + ``ClockLife``: under a covariate schedule, or on a duty plan that + changes over time).""" + return isinstance(model, ClockLife) -def scheduled(component) -> Optional["ScheduledLife"]: - """The ``ScheduledLife`` of a ``RepairableRBD`` component (a - ``NonRepairable``), or None for one with no covariate schedule.""" +def scheduled(component) -> Optional["ClockLife"]: + """The ``ClockLife`` of a ``RepairableRBD`` component (a + ``NonRepairable``), or None for one whose life does not depend on + when it is put into service.""" life = getattr(component, "reliability", None) - return life if isinstance(life, ScheduledLife) else None + return life if isinstance(life, ClockLife) else None -class ScheduledLife: +def on_clock(rbd) -> bool: + """Whether a component of ``rbd`` has a life on the diagram's clock + (a ``ClockLife``), which only the simulations take.""" + return any( + scheduled(component) is not None + for component in rbd.components.values() + ) + + +class ClockLife: + """A unit's life on the diagram's clock: what is left of it depends + on when the unit is put into service (``life_left``), so it is no + renewal process, and only the simulations (the Python engine) take + it. A covariate schedule's (``ScheduledLife``) and a duty plan's that + changes over time (``_duty.PlannedLife``) are such lives.""" + + #: Only simulations take it (as a simulated ``StandbyModel``). + is_simulated = True + #: Whether an age has no one meaning on it (the unit's clock changes + #: speed), so that a virtual age and a start at an age are refused. + clock = False + node: Any = None + #: How a message names what the block runs on. + lead = "runs on a covariate schedule" + #: Why an age has no one meaning on it (with ``clock``). + aged = ( + "with an accelerated failure time (or life) model, whose clock " + "changes speed with the covariates" + ) + + def life_left(self, t0: float, age: float, u: float) -> float: + raise NotImplementedError # pragma: no cover - each has its own + + def _no_reliability(self, what: str = "reliability") -> Exception: + """The refusal of the exact and numerical methods (see + ``is_simulated``), one message whatever ``what`` they need.""" + return NotImplementedError( + f"Component {self.node!r} {self.lead} on the diagram's clock, " + "so it has no reliability or mean life of its own: each " + "unit's life depends on when it is put into service. Only the " + "simulations take it: availability, cost and " + "simulate_timelines (the Python engine)." + ) + + +class ScheduledLife(ClockLife): """A unit's life under a covariate schedule on the diagram's clock (see the module's notes). It is a life only simulations take: its ``sf``, ``ff``, ``mean`` and ``random`` refuse (a unit's life depends @@ -88,9 +136,6 @@ class ScheduledLife: The block's name, for the messages. """ - #: Only simulations take it (as a simulated ``StandbyModel``). - is_simulated = True - def __init__(self, model: Any, schedule: Any, node: Any = None): from surpyval.univariate.regression import StepSchedule from surpyval.univariate.regression.kinds import ( @@ -195,18 +240,6 @@ def __init__(self, model: Any, schedule: Any, node: Any = None): # -- What it refuses --------------------------------------------------- - def _no_reliability(self, what: str = "reliability") -> Exception: - """The refusal of the exact and numerical methods (see - ``is_simulated``), one message whatever ``what`` they need.""" - return NotImplementedError( - f"Component {self.node!r} runs on a covariate schedule on the " - "diagram's clock, so it has no reliability or mean life of its " - "own: each unit's life depends on when it is put into service. " - "Only the " - "simulations take it: availability, cost and " - "simulate_timelines (the Python engine)." - ) - def sf(self, x): raise self._no_reliability() @@ -421,11 +454,12 @@ def check(rbd) -> None: members fail at their constant rates.""" for group in rbd.ccf_groups: for member in group.members: - if scheduled(rbd.components.get(member)) is not None: + life = scheduled(rbd.components.get(member)) + if life is not None: raise ValueError( - f"Component {member!r} runs on a covariate schedule, " - "and is in a common-cause group, whose members fail " - "at constant rates: leave it out of the group." + f"Component {member!r} {life.lead}, and is in a " + "common-cause group, whose members fail at constant " + "rates: leave it out of the group." ) @@ -438,7 +472,22 @@ def check_state(rbd, node, state, inspected: bool) -> None: age at the covariates in force at 0.""" life = scheduled(rbd.components[node]) assert life is not None - lead = f"Component {node!r} runs on a covariate schedule" + lead = f"Component {node!r} {life.lead}" + if getattr(life, "new_only", False) and not ( + state.alive + and not state.age + and not state.virtual_age + and state.since_scheduled is None + and not state.stationary + and not state.own_life + and not state.maintenance + ): + raise NotImplementedError( + f"{lead}, which says its operating time from the diagram's 0 " + "on, not before: a state other than new (an age, a task last " + "done, down) is not taken on it. Leave it out (new), or give " + "its duty as one share." + ) if state.stationary: raise NotImplementedError( f"{lead}, so it has no long-run state: give its state now, or " @@ -457,9 +506,8 @@ def check_state(rbd, node, state, inspected: bool) -> None: return if life.clock: raise NotImplementedError( - f"{lead} with an accelerated failure time (or life) model, " - "whose clock changes speed with the covariates, so an age " - "has no one meaning on it: leave it out (new)." + f"{lead} {life.aged}, so an age has no one meaning on it: " + "leave it out (new)." ) if inspected: raise NotImplementedError( @@ -467,6 +515,7 @@ def check_state(rbd, node, state, inspected: bool) -> None: "drawn from its last test, before the diagram's time starts. " "Leave it out (new)." ) + assert isinstance(life, ScheduledLife) # a duty plan's has clock k, _ = life._step_at(0.0) if not life._curves(k)[0](age) < math.inf: raise ValueError( diff --git a/repyability/rbd/_crew_allocation.py b/repyability/rbd/_crew_allocation.py new file mode 100644 index 00000000..02f1d00d --- /dev/null +++ b/repyability/rbd/_crew_allocation.py @@ -0,0 +1,365 @@ +"""Redundancy allocation with limited repair crews: the copies of the +components that cost least in total when the copies queue for the crews +with every other job (``RepairableRBD.allocate_redundancy``). + +Without limited crews a copy changes only its own node, so a design's +values are products and the search has bounds of its own +(``redundancy_allocation.lowest_total_cost``). With them a copy is one +more job for the crews: it can make another component wait, each copy's +own running cost depends on the whole design, and a copy more can even +raise the system's unavailability. So each design is worked out whole, +from the crews' Markov chain of its components and their copies +(``_crew_chain``'s ``copies``: a copy alike its component in rates and +priority, the chain counting how many are up, a node up while any is), +and the search keeps to two bounds that still hold: + +- crews never help by being fewer: a job that waits only starts later, so + every component is up no more than with a crew of its own, and the + system (coherent) is down no less. A design's unavailability is at + least that of the same design with unlimited crews, its components + independent (``Unlimited``, a product form that costs nothing to work + out); +- every copy is bought, and no running cost is negative: a design costs + at least its copies' acquisition, the crews' salaries and its downtime + with unlimited crews. + +``method="greedy"`` takes the single step (a copy more or fewer) that +lowers the total most until none does. ``method="exact"`` starts from +that design, lists every design that costs less to buy than it costs in +all (less the least downtime any design can have), each with the least it +can cost by the two bounds, and solves their chains from the most +promising on, until none left can beat the best found. A design it needs +whose chain is too large is refused, by name. +""" + +import math +from typing import Callable, Dict, Hashable, List, Optional, Sequence, Tuple + +import numpy as np + +from repyability.rbd import _costs, _crew_chain, _crews, _shutdowns +from repyability.rbd._common import _crew_salaries +from repyability.rbd.redundancy_allocation import _check_search_size, _slack + +#: What the result says of how its designs were worked out. +BASIS = ( + "Each design's long-run values from the repair crews' Markov chain, " + "its copies queueing for the crews with the other components." +) + + +class Design: + """A design's long-run values (see ``Evaluator``): its unavailability, + what its copies cost to buy, and its running cost per unit time.""" + + __slots__ = ("unavailability", "acquisition", "cost_rate") + + def __init__( + self, unavailability: float, acquisition: float, cost_rate: float + ): + self.unavailability = unavailability + self.acquisition = acquisition + self.cost_rate = cost_rate + + +class Evaluator: + """The long-run values of ``rbd`` with ``counts[i]`` copies of + ``chosen[i]`` (the original among them), each design from the crews' + chain of its components and their copies, and kept.""" + + def __init__(self, rbd, chosen: Sequence[Hashable]): + self.rbd = rbd + self.chosen = list(chosen) + self.rates = _crews._crew_chain_rates(rbd) + for node in self.chosen: + if node not in self.rates: + # (A nested RBD has been refused; a junction is no job.) + raise ValueError( + f"Node {node!r} is no job of the repair crews, so its " + "copies cannot be worked out with them." + ) + self.designs: Dict[Tuple[int, ...], Design] = {} + + def _copies(self, counts: Sequence[int]) -> List[int]: + """How many copies each of the crews' jobs has.""" + units = dict(zip(self.chosen, counts)) + return [int(units.get(node, 1)) for node in self.rates] + + def states(self, counts: Sequence[int]) -> int: + """How many states the design's chain has (see + ``_crew_chain.state_count``).""" + return _crew_chain.state_count( + [self.rbd._priority.get(node, 0.0) for node in self.rates], + [math.isinf(repair) for _, repair in self.rates.values()], + self.rbd.repair_crews, + _crews._call_when(self.rbd), + self._copies(counts), + ) + + def __call__(self, counts: Sequence[int]) -> Design: + key = tuple(int(n) for n in counts) + if key not in self.designs: + self.designs[key] = self._design(key) + return self.designs[key] + + def _design(self, counts: Tuple[int, ...]) -> Design: + rbd = self.rbd + if self.states(counts) > _crew_chain.MAX_STATES: + units = dict(zip(self.chosen, counts)) + raise NotImplementedError( + f"The search needs the design {units}, whose Markov chain " + "of the components' states and the repair queue has more " + f"than the {_crew_chain.MAX_STATES:,} states it is solved " + "for. Bound the copies with max_units, or compare designs " + "by simulation, with compare()." + ) + nodes = list(self.rates) + chain = _crew_chain.solve( + nodes, + [self.rates[node][0] for node in nodes], + [self.rates[node][1] for node in nodes], + [rbd._priority.get(node, 0.0) for node in nodes], + rbd.repair_crews, + _crews._call_when(rbd), + (), + self._copies(counts), + ) + weights = chain.probabilities + states = len(weights) + # A node is up while any of its copies is. + up = { + node: chain.up[:, k].astype(float) for k, node in enumerate(nodes) + } + down = {node: 1.0 - p for node, p in up.items()} + for node, component in rbd.components.items(): + if node not in up: + # A nested RBD, with crews of its own. + up[node] = np.full( + states, float(component.mean_availability()) + ) + down[node] = np.full( + states, float(component.mean_unavailability()) + ) + for node in rbd.in_or_out: + up[node], down[node] = np.ones(states), np.zeros(states) + unavailability = float(weights @ rbd._system_unreliability(up, down)) + # Every copy is run: a node's cost at its copies' availability, + # as many times (it is linear in the availability). + rate = _shutdowns.cost_rate(rbd) + _crew_salaries(rbd) + if _crews._call_out_priced(rbd): + rate += float(weights @ _crews._call_out_vector(rbd, chain)) + rate += rbd.downtime_cost_rate * unavailability + copies = self._copies(counts) + for k, node in enumerate(nodes): + if node in rbd.costs: + each = float(weights @ chain.working[:, k]) / copies[k] + rate += copies[k] * _costs._node_cost_rate(rbd, node, each) + for node in rbd.costs: + if node not in self.rates: + rate += _costs._node_cost_rate( + rbd, node, float(rbd.components[node].mean_availability()) + ) + acquisition = math.fsum( + n * rbd.acquisition_costs.get(node, 0.0) + for node, n in self._units(counts).items() + ) + return Design(unavailability, acquisition, rate) + + def _units(self, counts: Sequence[int]) -> Dict[Hashable, int]: + """Every component's number of copies.""" + units = dict(zip(self.chosen, counts)) + return {node: int(units.get(node, 1)) for node in self.rbd.components} + + +class Unlimited: + """The unavailability of a design with a crew for every job: its + components independent, each down ``lambda / (lambda + mu)`` of the + time, a node down while all its copies are. No design is down less + with the crews it has (see the module's notes).""" + + def __init__(self, rbd, chosen: Sequence[Hashable]): + self.rbd = rbd + self.chosen = list(chosen) + rates = _crews._crew_chain_rates(rbd) + self.down: Dict[Hashable, float] = {} + for node, component in rbd.components.items(): + if node in rates: + life, repair = rates[node] + self.down[node] = ( + 0.0 if math.isinf(repair) else life / (life + repair) + ) + else: + self.down[node] = float(component.mean_unavailability()) + + def __call__(self, counts: Sequence[float]) -> float: + """With ``counts[i]`` copies of ``chosen[i]`` (``inf``: perfect).""" + down = dict(self.down) + for node, n in zip(self.chosen, counts): + down[node] = 0.0 if n == math.inf else down[node] ** n + q = {node: np.array([value]) for node, value in down.items()} + p = {node: 1.0 - value for node, value in q.items()} + for node in self.rbd.in_or_out: + p[node], q[node] = np.ones(1), np.zeros(1) + return float(np.ravel(self.rbd._system_unreliability(p, q))[0]) + + +def search( + rbd, + chosen: Sequence[Hashable], + caps: Sequence[float], + max_unavailability: Optional[float], + method: str, + present: float, + worth: float, +) -> Tuple[Tuple[int, ...], Design]: + """The copies of each node in ``chosen`` (at most ``caps``) with the + lowest total cost over a horizon whose present value is ``present``, + a unit time of the system up worth ``worth`` (see the module's + notes), and the design's values. With ``max_unavailability``, among + the designs within it.""" + evaluate = Evaluator(rbd, chosen) + unlimited = Unlimited(rbd, chosen) + prices = [rbd.acquisition_costs.get(node, 0.0) for node in chosen] + for node, price, cap in zip(chosen, prices, caps): + if price <= 0.0 and cap == math.inf: + raise ValueError( + f"A copy of {node!r} costs nothing to buy, so with " + "limited repair crews the search, which is bounded by " + "what the copies cost to buy, could add copies without " + "end: give it an acquisition_cost or a max_units." + ) + lowest = unlimited(caps) + if max_unavailability is not None and lowest > max_unavailability: + raise ValueError( + "The unavailability cannot be brought down to " + f"{max_unavailability!r}: the lowest it can reach within the " + f"caps, even with a crew for every job, is {lowest!r}." + ) + # What a unit of unavailability costs over the horizon, and what the + # other components cost to buy and the crews are paid whatever the + # design. + downtime = present * (rbd.downtime_cost_rate + worth) + fixed = present * _crew_salaries(rbd) + math.fsum( + price + for node, price in rbd.acquisition_costs.items() + if node not in chosen + ) + + def total(design: Design) -> float: + return design.acquisition + present * ( + design.cost_rate + worth * design.unavailability + ) + + def feasible(design: Design) -> bool: + return ( + max_unavailability is None + or design.unavailability <= max_unavailability + ) + + best: Optional[Tuple[float, Tuple[int, ...]]] = None + try: + counts, design = _greedy(evaluate, prices, caps, total, feasible) + best = (total(design), counts) + except ValueError: + # No design within the limit by single steps. + if method == "greedy" or math.inf in caps: + raise + if method == "greedy": + assert best is not None + return best[1], evaluate(best[1]) + # The designs that could beat it: those whose copies cost less to buy + # than it costs in all, less the least downtime; each with the least + # it can cost, its copies bought and its downtime with a crew for + # every job. + limit = math.inf if best is None else best[0] + start = (1,) * len(chosen) + bought = {start: math.fsum(prices)} + frontier = [start] + candidates = [] + while frontier: + counts = frontier.pop() + _check_search_size(len(bought), "max_units") + u = unlimited(counts) + least = fixed + bought[counts] + downtime * u + if max_unavailability is None or u <= max_unavailability: + candidates.append((least, counts)) + for i, price in enumerate(prices): + if counts[i] < caps[i]: + more = counts[:i] + (counts[i] + 1,) + counts[i + 1 :] + cost = bought[counts] + price + if more not in bought and ( + fixed + cost + downtime * lowest < limit - _slack(limit) + ): + bought[more] = cost + frontier.append(more) + # The most promising first, until none left can beat the best found. + for least, counts in sorted(candidates): + if best is not None and least >= best[0] - _slack(best[0]): + break + design = evaluate(counts) + if feasible(design) and (best is None or total(design) < best[0]): + best = (total(design), counts) + if best is None: + raise ValueError( + "The unavailability cannot be brought down to " + f"{max_unavailability!r} within the caps with " + f"{rbd.repair_crews} repair crew(s): every design waits too " + "long for one. Give more crews, or a lower min_availability." + ) + return best[1], evaluate(best[1]) + + +def _greedy( + evaluate: Evaluator, + prices: Sequence[float], + caps: Sequence[float], + total: Callable[[Design], float], + feasible: Callable[[Design], bool], +) -> Tuple[Tuple[int, ...], Design]: + """From one of each: first, to a limit on the unavailability, the + copy with the largest fall in it per unit bought, until it is met; + then the single step (a copy more, or fewer while the limit holds) + that lowers the total most, until none does (as + ``lowest_total_cost``'s greedy method).""" + m = len(prices) + counts = (1,) * m + + def stepped(i: int, by: int) -> Tuple[int, ...]: + return counts[:i] + (counts[i] + by,) + counts[i + 1 :] + + design = evaluate(counts) + while not feasible(design): + step, value = None, -math.inf + for i in range(m): + if counts[i] >= caps[i]: + continue + fall = ( + design.unavailability - evaluate(stepped(i, 1)).unavailability + ) + if fall <= 0.0: + continue + worth = fall / prices[i] if prices[i] > 0.0 else math.inf + if worth > value: + step, value = stepped(i, 1), worth + if step is None: + raise ValueError( + "The unavailability cannot be brought down to the limit: " + "another copy no longer lowers it. Give more repair " + "crews, or a lower min_availability." + ) + counts, design = step, evaluate(step) + while True: + moves = [ + (total(evaluate(stepped(i, by))), stepped(i, by)) + for i in range(m) + for by in (1, -1) + if 1 <= counts[i] + by <= caps[i] + and feasible(evaluate(stepped(i, by))) + ] + if not moves: + break + cost, move = min(moves) + if cost >= total(design) - _slack(total(design)): + break + counts, design = move, evaluate(move) + return counts, design diff --git a/repyability/rbd/_crew_chain.py b/repyability/rbd/_crew_chain.py index e70f3acb..e593cb61 100644 --- a/repyability/rbd/_crew_chain.py +++ b/repyability/rbd/_crew_chain.py @@ -15,6 +15,35 @@ comes back up the moment a crew reaches it. That crew then takes the next job. +With a call-out crew (``call_when``, a ``RepairableRBD``'s ``call_out``), +a job that makes that many wait brings one more crew, which takes the +first waiting job at once; while it is engaged there is a crew more, and +it leaves at the first end of a job that leaves a crew with none to take +(the job it has then, if any, is finished by the crew that came free: +the crews are alike). So it is engaged exactly in the states with a job +more under repair than there are crews, and the chain needs no more of a +state. ``calls`` is the rate at which it is called in each state and +``engaged`` those states, for its fee and its rate while engaged. + +With common-cause groups (``shared``, #251), a shared cause strikes at its +rate and fails the components it names that are up, at once, as the +simulation's does (``_event_loop._strike``): they join the queue one after +another in the cause's order, each as a failure of its own would. The +simulation takes the first that way, and the others in the order its event +queue releases events at one time, which is the cause's order for one +other and not a rule for more: the chain takes causes of two components +(``MAX_STRUCK``). A component of a group fails on its own at its own +cause's rate, which is what ``failure_rates`` then holds. + +A component may stand for several alike copies (``copies``, for the +redundancy allocation's designs): a state then says how many of them are +under repair and waiting (the component as many times among those under +repair and in the queue), not which, as the copies are alike in rates and +priority. Each copy up fails at the component's rate and each under +repair is repaired at its rate, so the chain is that of the copies told +apart, with the states that differ only by which copy is where taken +together. + The chain is enumerated from the state with every component up, and its balance equations are solved directly: sparse equations for each other state's probability relative to that one's. They are eliminated from the @@ -28,13 +57,25 @@ """ import math -from typing import Any, Dict, Hashable, List, NamedTuple, Sequence, Tuple +from typing import ( + Any, + Dict, + Hashable, + List, + NamedTuple, + Optional, + Sequence, + Tuple, +) import numpy as np #: The most states the chain is solved for. MAX_STATES = 15_000 +#: The most components a shared cause may strike (see the module docstring). +MAX_STRUCK = 2 + #: A state: the components under repair (sorted), and those waiting, in the #: order the crews will take them. State = Tuple[Tuple[int, ...], Tuple[int, ...]] @@ -51,7 +92,12 @@ class CrewChain(NamedTuple): ``_chain_transient``). ``transitions`` are its transitions one by one, ``(sources, targets, rates, components)``: each a component's failure or the end of its repair (with the jobs the crew then takes that are - done at once), labelled with that component's position. + done at once), labelled with that component's position, or a shared + cause's strike, labelled with ``len(nodes)`` plus its group's place + (``groups`` of them). ``calls`` is + the rate at which a call-out crew is called in each state, and + ``engaged`` whether it is engaged there (see the module docstring): + zeros without one. """ nodes: Tuple[Hashable, ...] @@ -60,6 +106,12 @@ class CrewChain(NamedTuple): states: Tuple[State, ...] = () generator: Any = None transitions: Any = None + calls: Any = None + engaged: Any = None + groups: int = 0 + #: How many of each component's copies are up in each state (1 or 0 + #: without copies): ``up`` says whether any is. + working: Any = None def availability(self, node) -> float: """The long-run probability that ``node`` is up.""" @@ -70,9 +122,12 @@ def split(self, vector: np.ndarray) -> np.ndarray: """``Q_i v`` for each component ``i`` (columns), ``Q_i`` the part of the generator made of its transitions: ``Q = sum_i Q_i``, so that ``p(t) Q_i v`` is the part of ``d/dt p(t) v`` the component's - failures and repairs make.""" + failures and repairs make; then a column for each common-cause + group, of its shared causes' strikes.""" sources, targets, rates, components = self.transitions - out = np.zeros((len(self.probabilities), len(self.nodes))) + out = np.zeros( + (len(self.probabilities), len(self.nodes) + self.groups) + ) vector = np.asarray(vector, dtype=float) np.add.at( out, @@ -89,14 +144,21 @@ def _queues(r: int) -> int: def state_count( - priorities: Sequence[float], instant: Sequence[bool], crews: int + priorities: Sequence[float], + instant: Sequence[bool], + crews: int, + call_when: int = 0, + copies: Optional[Sequence[int]] = None, ) -> int: """The number of states of the chain, counted without building it. In a state either nothing waits, and at most ``crews`` of the components whose repairs take time are under repair; or every crew is busy with such a repair, and some of the other components wait, in any order - within each priority. + within each priority. With a call-out crew (``call_when``) or copies + of components (``copies``) the states are counted as they are + reached, up to ``MAX_STATES + 1``: more than that many are not told + apart. Parameters ---------- @@ -106,12 +168,30 @@ def state_count( Whether each component's repair is instant. crews : int The number of crews. + call_when : int, optional + How many waiting jobs call the call-out crew (0: there is none). + copies : Sequence[int], optional + How many alike copies each component stands for (one each, by + default). Returns ------- int The number of states. """ + if call_when or copies is not None: + return len( + _enumerate( + [1.0] * len(instant), + [math.inf if now else 1.0 for now in instant], + priorities, + crews, + call_when, + MAX_STATES + 1, + (), + copies, + )[0] + ) timed = sum(1 for now in instant if not now) count = sum(math.comb(timed, k) for k in range(min(crews, timed) + 1)) if timed < crews: @@ -141,10 +221,22 @@ def _enumerate( repair_rates: Sequence[float], priorities: Sequence[float], crews: int, -) -> Tuple[List[State], List[int], List[int], List[float], List[int]]: + call_when: int = 0, + limit: int = 0, + shared: Sequence[Tuple[Tuple[int, ...], float, int]] = (), + copies: Optional[Sequence[int]] = None, +) -> Tuple[ + List[State], List[int], List[int], List[float], List[int], List[int] +]: """The states reached from the one with every component up, and the - transitions between them: sources, targets, rates, and the component - whose failure or repair each is.""" + transitions between them: sources, targets, rates, the component + whose failure or repair each is (or, for a strike of one of the + ``shared`` causes, each ``(components struck, rate, group)``, the + number of components plus its group), and how many times it calls + the call-out crew (``call_when`` waiting jobs do; see the module + docstring). With a ``limit``, it stops once it has reached that many + states. With ``copies``, each component stands for that many alike + ones (see the module docstring).""" instant = [math.isinf(rate) for rate in repair_rates] start: State = ((), ()) index = {start: 0} @@ -153,8 +245,15 @@ def _enumerate( targets: List[int] = [] rates: List[float] = [] components: List[int] = [] + calls: List[int] = [] - def reach(source: int, state: State, rate: float, component: int) -> None: + def reach( + source: int, + state: State, + rate: float, + component: int, + call: int = 0, + ) -> None: target = index.get(state) if target is None: target = index[state] = len(states) @@ -163,42 +262,74 @@ def reach(source: int, state: State, rate: float, component: int) -> None: targets.append(target) rates.append(rate) components.append(component) + calls.append(call) + def taken(serving: tuple, waiting: tuple) -> State: + """A crew takes the next waiting job, and an instant one is done + at once, so it goes on to the one after.""" + while waiting: + head, waiting = waiting[0], waiting[1:] + if not instant[head]: + return tuple(sorted(serving + (head,))), waiting + return serving, waiting + + def failed(state: State, i: int) -> Tuple[State, int]: + """The state once component ``i``, up in ``state``, has failed, + and whether that called the call-out crew.""" + serving, queue = state + if len(serving) < crews: + if instant[i]: + return state, 0 # repaired at once: nothing changes + return (tuple(sorted(serving + (i,))), queue), 0 + # Behind every waiting job of the same priority or higher. + place = len(queue) + while place and priorities[queue[place - 1]] < priorities[i]: + place -= 1 + waiting = queue[:place] + (i,) + queue[place:] + if call_when and len(serving) == crews and len(waiting) >= call_when: + # The call-out crew comes, and takes the first of them. + return taken(serving, waiting), 1 + return (serving, waiting), 0 + + count = len(failure_rates) + alike = [1] * count if copies is None else list(copies) source = 0 - while source < len(states): - serving, queue = states[source] - down = set(serving).union(queue) + while source < len(states) and not (limit and len(states) >= limit): + state = states[source] + serving, queue = state + # How many of each component's copies are up. + up = list(alike) + for i in serving + queue: + up[i] -= 1 for i, rate in enumerate(failure_rates): - if i in down: + if not up[i]: continue - if len(serving) < crews: - if instant[i]: - continue # repaired at once: nothing changes - reach(source, (tuple(sorted(serving + (i,))), queue), rate, i) - continue - # Behind every waiting job of the same priority or higher. - place = len(queue) - while place and priorities[queue[place - 1]] < priorities[i]: - place -= 1 + after, call = failed(state, i) + if after != state or call: + reach(source, after, up[i] * rate, i, call) + for struck, rate, group in shared: + # Those up fail one after another, in the cause's order. + after, called = state, 0 + for i in struck: + if up[i]: + after, call = failed(after, i) + called += call + if after != state or called: + reach(source, after, rate, count + group, called) + for i in sorted(set(serving)): + # One of its copies under repair is done. + place = serving.index(i) + rest = serving[:place] + serving[place + 1 :] + # The crew takes the next job; with none, the call-out crew + # (engaged with a job more than the crews under repair) goes. reach( source, - (serving, queue[:place] + (i,) + queue[place:]), - rate, + taken(rest, queue), + serving.count(i) * repair_rates[i], i, ) - for i in serving: - rest = tuple(j for j in serving if j != i) - waiting = queue - # The crew takes the next job, and an instant one is done at - # once, so it goes on to the one after. - while waiting: - head, waiting = waiting[0], waiting[1:] - if not instant[head]: - rest = tuple(sorted(rest + (head,))) - break - reach(source, (rest, waiting), repair_rates[i], i) source += 1 - return states, sources, targets, rates, components + return states, sources, targets, rates, components, calls def solve( @@ -207,6 +338,9 @@ def solve( repair_rates: Sequence[float], priorities: Sequence[float], crews: int, + call_when: int = 0, + shared: Sequence[Tuple[Tuple[int, ...], float, int]] = (), + copies: Optional[Sequence[int]] = None, ) -> CrewChain: """The chain of ``nodes`` with these failure and repair rates (``inf`` for an instant repair) and priorities (higher first), sharing ``crews`` @@ -222,6 +356,17 @@ def solve( Each component's priority for a crew. crews : int The number of crews. + call_when : int, optional + How many waiting jobs call a call-out crew (0, the default: there + is none). + shared : sequence, optional + The common-cause groups' shared causes, each ``(positions of the + components it strikes, in its order; its rate; its group's + place)``; ``failure_rates`` are then the components' own causes'. + copies : Sequence[int], optional + How many alike copies each component stands for (one each, by + default): ``working`` then counts those up, and ``up`` says + whether any is. Not with ``shared`` causes. Returns ------- @@ -232,13 +377,35 @@ def solve( from scipy import sparse from scipy.sparse.linalg import splu - states, sources, targets, rates, components = _enumerate( - failure_rates, repair_rates, priorities, crews + states, sources, targets, rates, components, called = _enumerate( + failure_rates, + repair_rates, + priorities, + crews, + call_when, + 0, + shared, + copies, ) size = len(states) - up = np.ones((size, len(nodes)), dtype=bool) + groups = 1 + max((group for _, _, group in shared), default=-1) + calls = np.bincount( + np.array(sources, dtype=np.intp), + weights=np.array(rates, dtype=float) * np.array(called, dtype=float), + minlength=size, + ) + engaged = np.array([len(serving) > crews for serving, _ in states]) + working = np.tile( + ( + np.ones(len(nodes), dtype=np.intp) + if copies is None + else np.asarray(copies, dtype=np.intp) + ), + (size, 1), + ) for s, (serving, queue) in enumerate(states): - up[s, list(serving + queue)] = False + np.subtract.at(working[s], list(serving + queue), 1) + up = working > 0 generator = sparse.csr_matrix( (np.array(rates, dtype=float), (sources, targets)), shape=(size, size) ) @@ -259,6 +426,10 @@ def solve( tuple(states), generator, transitions, + calls, + engaged, + groups, + working, ) # The most components down first; within a level, by the queue. The # state with every component up, the only one with none down, is last. @@ -290,5 +461,14 @@ def solve( probabilities = np.empty(size) probabilities[order] = weights / weights.sum() return CrewChain( - tuple(nodes), up, probabilities, tuple(states), generator, transitions + tuple(nodes), + up, + probabilities, + tuple(states), + generator, + transitions, + calls, + engaged, + groups, + working, ) diff --git a/repyability/rbd/_crews.py b/repyability/rbd/_crews.py index 8124fa0b..64836221 100644 --- a/repyability/rbd/_crews.py +++ b/repyability/rbd/_crews.py @@ -20,7 +20,7 @@ import numpy as np from repyability.rbd import ( - _ccf_groups, + _ccf_chain, ) from repyability.rbd import _crew_chain as crew_chain from repyability.rbd import _long_run, _requirements @@ -63,6 +63,48 @@ def _crews_limited(rbd) -> bool: ) +def _call_when(rbd) -> int: + """How many waiting jobs call the call-out crew (``call_out``'s + ``"when_waiting"``); 0 with none, or where no job can wait.""" + call_out = getattr(rbd, "_call_out", None) + if call_out is None or not _crews_limited(rbd): + return 0 + return call_out.when_waiting + + +def _call_out_priced(rbd) -> bool: + """Whether a call-out crew that can be called costs anything.""" + call_out = getattr(rbd, "_call_out", None) + return bool( + call_out is not None + and (call_out.fee or call_out.rate) + and _crews_limited(rbd) + ) + + +def _call_out_charge(rbd, calls, engaged): + """What the call-out crew costs for ``calls`` call-outs and a time + ``engaged``: its fee each time it comes, and its rate while engaged.""" + return rbd._call_out.fee * calls + rbd._call_out.rate * engaged + + +def _call_out_vector(rbd, chain) -> np.ndarray: + """The rate at which the call-out crew costs in each state of the + crews' ``chain``: its fee at the rate it is called there, and its + rate where it is engaged.""" + return _call_out_charge(rbd, chain.calls, chain.engaged.astype(float)) + + +def _call_out_cost_rate(rbd, working_nodes, broken_nodes) -> float: + """The call-out crew's long-run cost per unit time, from the crews' + chain without the nodes held (0.0 where it costs nothing).""" + if not _call_out_priced(rbd): + return 0.0 + forced = frozenset(working_nodes or ()) | frozenset(broken_nodes or ()) + chain = _crew_chain(rbd, forced) + return float(chain.probabilities @ _call_out_vector(rbd, chain)) + + def _require_unlimited_crews( rbd, assumes: str = "these values assume", @@ -141,28 +183,88 @@ def _crew_chain_rates(rbd) -> Dict[Any, Tuple[float, float]]: f"and the repair times of component {node!r} are not", ) rates[node] = (life, repair) - count = crew_chain.state_count( - [rbd._priority.get(node, 0.0) for node in rates], - [math.isinf(repair) for _, repair in rates.values()], - rbd.repair_crews, - ) - if count > crew_chain.MAX_STATES: + priorities = tuple(rbd._priority.get(node, 0.0) for node in rates) + instant = tuple(math.isinf(repair) for _, repair in rates.values()) + call_when = _call_when(rbd) + # (Kept beside the chains, under a key of another shape.) + counts = rbd._cache.kept("crew_chains") + key = (priorities, instant, rbd.repair_crews, call_when) + if key not in counts: + counts[key] = crew_chain.state_count(*key) + if counts[key] > crew_chain.MAX_STATES: _no_crew_chain( rbd, - f"here it has {count:,} states, more than the " - f"{crew_chain.MAX_STATES:,} it is solved for", + ( + "here it has more than the " + if call_when + else f"here it has {counts[key]:,} states, more than the " + ) + + f"{crew_chain.MAX_STATES:,} " + + ("states " if call_when else "") + + "it is solved for", ) return rates +def _crew_causes(rbd, nodes) -> Tuple[Dict[Any, float], List[tuple]]: + """The causes of failure of the crews' chain's ``nodes`` with + common-cause groups (#251), as the simulation strikes them (see + ``_ccf_groups._shared_causes``): each node's own cause's rate (its + failure rate, outside the groups), and the shared causes, each ``(the + places in nodes of the members it strikes, in its order; its rate; + its group's place)``. A member not among ``nodes`` (held working, it + never fails, and held broken it is never repaired) is struck no more, + and the causes it shares still strike the others. Raise if the chain + does not take a group in: a cause that strikes more than + ``_crew_chain.MAX_STRUCK`` members, or a member repaired instantly.""" + rates = _crew_chain_rates(rbd) + own = {node: rates[node][0] for node in nodes} + place = {node: k for k, node in enumerate(nodes)} + shared: List[tuple] = [] + for g, group in enumerate(rbd.ccf_groups): + members = list(group.members) + where = f"common-cause group {members}" + for member in members: + if math.isinf(rates[member][1]): + _no_crew_chain( + rbd, + f"it takes no member of a common-cause group repaired " + f"instantly, as member {member!r} of {where} is", + ) + for struck, rate in _ccf_chain.causes( + group.model, members, rates[members[0]][0] + ): + if len(struck) == 1: + if members[struck[0]] in place: + own[members[struck[0]]] = rate + continue + if len(struck) > crew_chain.MAX_STRUCK: + _no_crew_chain( + rbd, + "it takes shared causes that strike " + f"{crew_chain.MAX_STRUCK} components, and {where} " + f"({group.model!r}) has one that strikes " + f"{len(struck)}: the simulation queues components " + "struck at one instant in the order its event queue " + "releases them, which is a rule only for two", + ) + left = [members[i] for i in struck if members[i] in place] + if len(left) == 1: + own[left[0]] += rate + elif left: + shared.append((tuple(place[m] for m in left), rate, g)) + return own, shared + + def _require_crew_chain(rbd) -> None: """Raise if the exact long-run values with limited repair crews - cannot be computed: the Markov chain does not take common-cause - groups in (#251, see ``_ccf_rates``), does not cover the components - (see ``_crew_chain_rates``), or nested RBDs' calendars fall together - (see ``_require_calendars``).""" - _ccf_groups._require_ccf_long_run(rbd) - _crew_chain_rates(rbd) + cannot be computed: the Markov chain does not cover the components + (see ``_crew_chain_rates``) or their common-cause groups (#251, see + ``_crew_causes``), or nested RBDs' calendars fall together (see + ``_require_calendars``).""" + rates = _crew_chain_rates(rbd) + if rbd.ccf_groups: + _crew_causes(rbd, list(rates)) _requirements._require_calendars(rbd) @@ -179,18 +281,33 @@ def _crew_chain( assert rbd.repair_crews is not None # limited crews only nodes = [node for node in rates if node not in forced] priorities = [rbd._priority.get(node, 0.0) for node in nodes] + call_when = _call_when(rbd) + own = {node: rates[node][0] for node in nodes} + shared: List[tuple] = [] + if rbd.ccf_groups: + own, shared = _crew_causes(rbd, nodes) key = ( rbd.repair_crews, - tuple(zip(nodes, (rates[node] for node in nodes), priorities)), + call_when, + tuple( + zip( + nodes, + ((own[node], rates[node][1]) for node in nodes), + priorities, + ) + ), + tuple(shared), ) cache = rbd._cache.kept("crew_chains") if key not in cache: cache[key] = crew_chain.solve( nodes, - [rates[node][0] for node in nodes], + [own[node] for node in nodes], [rates[node][1] for node in nodes], priorities, rbd.repair_crews, + call_when, + shared, ) return cache[key] @@ -261,7 +378,13 @@ def crew_states( working, broken = rbd._held_nodes(working_nodes, broken_nodes) _require_coupling_crews(rbd) availability, probabilities = _chain_probabilities(rbd, working, broken) - return CrewStates(availability, probabilities) + chain = _crew_chain(rbd, frozenset(working) | frozenset(broken)) + return CrewStates( + availability, + probabilities, + np.array(chain.calls, dtype=float), + chain.engaged.astype(float), + ) def _chain_outage_terms( @@ -277,6 +400,8 @@ def _chain_outage_terms( ) forced = set(working_nodes or ()) | set(broken_nodes or ()) rates = _crew_chain_rates(rbd) + chain = _crew_chain(rbd, frozenset(forced)) + own = _crew_causes(rbd, chain.nodes)[0] if rbd.ccf_groups else {} birnbaum = rbd._birnbaum_importance( availability, node_failures=unavailability ) @@ -287,7 +412,8 @@ def _chain_outage_terms( continue importance = np.asarray(birnbaum[node]) if node in rates: - life = rates[node][0] + # (Its own cause's rate, in a common-cause group.) + life = own.get(node, rates[node][0]) node_failures, node_planned = life * availability[node], 0.0 else: node_failures, _, node_planned = _long_run._node_frequencies( @@ -295,4 +421,12 @@ def _chain_outage_terms( ) terms.append((node, float(weights @ (importance * node_failures)))) planned += float(weights @ (importance * node_planned)) + if rbd.ccf_groups: + # Each group's shared causes: a strike takes the system down + # where it is up, and down with the members struck down. + from repyability.rbd import _curves + + struck = _curves._crew_strikes(rbd, chain, availability) + for g, group in enumerate(rbd.ccf_groups): + terms.append((tuple(group.members), float(weights @ struck[:, g]))) return terms, planned diff --git a/repyability/rbd/_curves.py b/repyability/rbd/_curves.py index 7b40a515..abe71cae 100644 --- a/repyability/rbd/_curves.py +++ b/repyability/rbd/_curves.py @@ -39,6 +39,7 @@ from repyability.rbd._block_replacement import ( BlockHead, block_availability, + plan_availability, ) from repyability.rbd._common import ( _common_period, @@ -50,6 +51,7 @@ from repyability.rbd._condition_replacement import ( ConditionHead, condition_availability, + condition_plan_availability, ) from repyability.rbd._covariate_schedule import scheduled from repyability.rbd._hidden_life import ( @@ -74,6 +76,7 @@ InspectionCurve, MinimalRepairCurve, PartialTestCurve, + PlanCurve, ShiftedCurve, StartedBlockCurve, SteadyCurve, @@ -294,6 +297,13 @@ def _node_over_time(rbd, node, kind: str = "availability") -> Tuple[str, str]: "followed from one shut to the next on a grid, the units kept " "by age", ) + if calendar and schedule.shuts is not None: # type: ignore + return ( + r.NUMERICAL, + "block replacement at the starts of several shutdowns: " + "followed from one start to the next on a grid, each renewal " + "taking its own shut's length", + ) if calendar and schedule.policy == "condition": # type: ignore return ( r.NUMERICAL, @@ -325,7 +335,7 @@ def _over_time( ``_crew_over_time``).""" from repyability.rbd import routes as r - refusal = r.refusal(partial(_shutdowns.require_exact, rbd)) + refusal = r.refusal(partial(_shutdowns.require_over_time, rbd)) if refusal: return r.refused(refusal) if rbd._crews_couple(): @@ -438,11 +448,10 @@ def _require_crew_over_time( rbd, forced=frozenset(), kind: str = "availability" ) -> list: """Raise what the crews' chain over time refuses, in the order the - methods check it: common-cause groups, what the chain does not - cover (see ``_require_crew_chain``), and too many nested RBDs (see - ``_crew_nested``). Return the nested RBDs, less those in - ``forced``.""" - _ccf_groups._require_ccf_long_run(rbd) + methods check it: what the chain does not cover, of the components + and their common-cause groups (see ``_require_crew_chain``), and too + many nested RBDs (see ``_crew_nested``). Return the nested RBDs, less + those in ``forced``.""" _crews._require_crew_chain(rbd) return _crew_nested(rbd, forced) @@ -755,6 +764,7 @@ def _check_state(rbd, node, state: NodeState, simulated=False) -> None: schedule = rbd._preventive.get(node) inspection = rbd._inspection.get(node) _shutdowns.check_state(rbd, node, state) + _requirements._check_plan_state(rbd, node, state) if state.virtual_age is not None and not _keeps_virtual_age(rbd, node): raise ValueError( f"Component {node!r} is not repaired imperfectly (it has no " @@ -1273,45 +1283,85 @@ def _crew_vectors( ) -> Tuple[np.ndarray, dict]: """Over the states of the crews' ``chain``, with the other nodes' probabilities ``values`` (arrays, one entry per state): whether the - system is up, and each node's Birnbaum importance.""" + system is up, and each node's Birnbaum importance (with, under + ``_STRIKES``, the rate of the system's failures by each common-cause + group's shared causes, see ``_crew_strikes``).""" size = len(chain.probabilities) own = { node: chain.up[:, k].astype(float) for k, node in enumerate(chain.nodes) } own.update(values) - importance, works, fails, _, _ = rbd._importances( - _windows._filled(rbd, own, size, working_nodes, broken_nodes) - ) + filled = _windows._filled(rbd, own, size, working_nodes, broken_nodes) + importance, works, fails, _, _ = rbd._importances(filled) up = works if structure_method(method) == "p" else 1.0 - fails + importance = {**importance, _STRIKES: _crew_strikes(rbd, chain, filled)} return np.asarray(up, dtype=float), importance -def _crew_failing(rbd, chain, importance: dict) -> np.ndarray: - """The rate of the system's failures in each state of the crews' - ``chain``: a component that is up fails at its rate, and takes the - system down where it is critical (its Birnbaum ``importance`` - there, 1 or 0), as ``system_failure_frequency`` has it.""" - rates = _crews._crew_chain_rates(rbd) - failing = np.zeros(len(chain.probabilities)) - for k, node in enumerate(chain.nodes): - failing += importance[node] * chain.up[:, k] * rates[node][0] - return failing +class _Strikes: + """The key of the shared causes' part among a chain's importances + (equal to no node name).""" + + +_STRIKES = _Strikes() + + +def _crew_strikes(rbd, chain, filled: dict) -> np.ndarray: + """The rate of the system's failures by each common-cause group's + shared causes (columns) in each state of the crews' ``chain`` (#251), + the nodes up with the probabilities ``filled`` there: a cause strikes + at its rate, and takes the system down where it is up, and down with + the members it strikes down (as ``_ccf_groups._ccf_outage_terms`` has + it).""" + out = np.zeros((len(chain.probabilities), len(rbd.ccf_groups))) + if not rbd.ccf_groups: + return out + down = np.asarray(rbd._system_unreliability(filled), dtype=float) + zero = np.zeros(len(chain.probabilities)) + for struck, rate, g in _crews._crew_causes(rbd, chain.nodes)[1]: + hit = {**filled, **{chain.nodes[k]: zero for k in struck}} + out[:, g] += rate * ( + np.asarray(rbd._system_unreliability(hit), dtype=float) - down + ) + return out def _crew_failing_each(rbd, chain, importance: dict) -> np.ndarray: - """``_crew_failing`` by component: the rate of the system's failures - by each of the chain's components (columns) in each of its states - (#199).""" + """The rate of the system's failures by each of the chain's + components (columns) in each of its states (#199): a component that + is up fails at its rate (its own cause's, in a common-cause group), + and takes the system down where it is critical (its Birnbaum + ``importance`` there, 1 or 0), as ``system_failure_frequency`` has + it; then by each common-cause group's shared causes (see + ``_crew_strikes``).""" rates = _crews._crew_chain_rates(rbd) + own = _crews._crew_causes(rbd, chain.nodes)[0] if rbd.ccf_groups else {} return np.column_stack( [ - importance[node] * chain.up[:, k] * rates[node][0] + importance[node] * chain.up[:, k] * own.get(node, rates[node][0]) for k, node in enumerate(chain.nodes) ] + + [importance[_STRIKES]] ) +def _crew_failing(rbd, chain, importance: dict) -> np.ndarray: + """The rate of the system's failures in each state of the crews' + ``chain``: by any of its components or shared causes (see + ``_crew_failing_each``).""" + return _crew_failing_each(rbd, chain, importance).sum(axis=1) + + +def _cause_keys(rbd, chain) -> list: + """Whose the columns of ``_crew_failing_each`` are: the chain's + components, then each common-cause group, as the tuple of its + members.""" + return list(chain.nodes) + [ + tuple(group.members) for group in rbd.ccf_groups + ] + + def _crew_each(rbd, chain, nested: list, working, broken, method: str) -> list: """For each pattern of the ``nested`` RBDs up and down, the rate of the system's failures by each of the crews' chain's components in @@ -1526,12 +1576,19 @@ def _crew_window( ``system_failure_frequency`` has it), and each component's down time and failures (at its rate while it is up), each a repair. No component has scheduled maintenance or tests, and none fails at the - same instant as another.""" + same instant as another. A call-out crew that costs anything is + counted too (``"call_out"``: what it has cost by each end), from the + chain's last vector, the rate at which it costs in each state.""" working, broken = set(working_nodes), set(broken_nodes) forced = working | broken nested = _require_crew_over_time(rbd, frozenset(forced), "window") chain = _crews._crew_chain(rbd, frozenset(forced)) rates = _crews._crew_chain_rates(rbd) + called = ( + [_crews._call_out_vector(rbd, chain)] + if _crews._call_out_priced(rbd) + else [] + ) if nested: # The nested RBDs, independent of the chain, counted as nodes, # with the system worked out over the chain (#162). @@ -1549,10 +1606,14 @@ def _crew_window( _crew_patterns(rbd, chain, nested, working, broken, method) + [chain.up.astype(float)] + each + + called ), ) system = _chain_transient.CrewSystem( - uniformized, nested, chain.nodes, causes + uniformized, + nested, + chain.nodes, + _cause_keys(rbd, chain) if causes else (), ) horizon = float(np.max(ends)) if len(ends) else 0.0 curves = { @@ -1581,6 +1642,10 @@ def _crew_window( curves[node] = _chain_transient.CrewNodeEvents( uniformized, column + k, rates[node][0] ) + if called: + totals["call_out"] = np.maximum( + uniformized.integrals(ends)[:, -1], 0.0 + ) return curves, totals up, importance = _crew_vectors(rbd, chain, {}, working, broken, method) failing = _crew_failing(rbd, chain, importance) @@ -1590,7 +1655,7 @@ def _crew_window( chain.generator, _crew_start(rbd, chain, states), chain.probabilities, - np.column_stack([up, failing, chain.up.astype(float)] + each), + np.column_stack([up, failing, chain.up.astype(float)] + each + called), ) totals = uniformized.integrals(ends) zero = np.zeros(len(ends)) @@ -1601,11 +1666,13 @@ def _crew_window( "downtime": {}, "overlaps": {name: zero for name in groups or {}}, } + if called: + counts["call_out"] = np.maximum(totals[:, -1], 0.0) if causes: base = 2 + len(chain.nodes) counts["caused"] = { - node: np.maximum(totals[:, base + k], 0.0) - for k, node in enumerate(chain.nodes) + key: np.maximum(totals[:, base + k], 0.0) + for k, key in enumerate(_cause_keys(rbd, chain)) } curves = {} for k, node in enumerate(chain.nodes): @@ -1887,6 +1954,18 @@ def _block_curve(rbd, node, horizon: float, start: Optional[NodeState] = None): level (``y0`` if new), which its first inspection reads.""" component = rbd.components[node] schedule = rbd._preventive[node] + if ( + schedule.policy == "block" + and ( + schedule.times is not None + or schedule.shuts is not None + or schedule.upgrade_at is not None + ) + ) or (schedule.policy == "condition" and schedule.times is not None): + # Its own plan's times, a shutdown's given times (renewed there, + # or inspected and kept unless due), or the starts of several + # shutdowns. + return _plan_curve(rbd, node, horizon, start) duration = schedule.duration stationary = start is not None and start.stationary knots = np.empty(0) if duration is None else point_knots(duration) @@ -1973,6 +2052,159 @@ def failures(u): return ShiftedCurve(curve, curve.settle + since) +def _plan_curve(rbd, node, horizon: float, start: Optional[NodeState] = None): + """A component's point availability over ``[0, horizon]``, replaced + at the times of its plan (its ``"replace_at"``, or those of the + shutdown it is renewed at) if it is up at them and after the last no + more: followed stretch by stretch, each from + one of the times to the next (see + ``_block_replacement.plan_availability``). From new, the first + stretch starts new at 0; from a state, the unit's own curve reaches + the first time and the plan is followed from there (as + ``_block_curve`` starts block replacement). The stretch after the last + time is as long as the longest of the others, doubled until it + reaches the horizon, so that nearby horizons are worked out on the + same grid, with that stretch's step.""" + if not math.isfinite(horizon): + _requirements._require_no_plans(rbd) + component = rbd.components[node] + schedule = rbd._preventive[node] + duration = schedule.duration + times, taken = _plan_times(schedule, horizon) + # A shut at 0 does not replace the unit, new or as its state says + # then: the simulation's tasks fall due after 0 (_Preventive.due). + taken = [d for t, d in zip(times, taken) if t > 0.0] + times = times[times > 0.0] + if not times.size: + return _unit_curve( + rbd, node, horizon, counts=True, start=start, unscheduled=True + ) + edges = np.concatenate(([0.0], times)) + gaps = np.diff(edges) + started = start is not None and not start.new + # The stretches that start by the horizon (from a state, the one + # after the head at least). + used = max( + int(np.searchsorted(times, max(horizon, 0.0), side="right")), + 1 if started else 0, + ) + lengths = list(gaps[: used + 1]) + like = None + if used == len(times): + like = last = float(gaps.max()) + while last < horizon - times[-1]: + last *= 2.0 + lengths.append(last) + models = (component.reliability, component.time_to_replace, duration) + # After an upgrade, the units put into service have its life. + upgrade = rbd._upgrades.get(node) + lives = None + if upgrade is not None: + lives = [ + upgrade.life if begin >= upgrade.at else component.reliability + for begin in edges[: len(lengths)] + ] + + # The time each stretch's replacement takes, where they differ (the + # first's, from new, starts no replacement: it shares the next one's + # grid). + durations = None + if schedule.shuts is not None: + durations = ([taken[0]] + taken)[: len(lengths)] + + def curve(results, starts): + return PlanCurve( + [BlockCurve(r, _knots(r.replace.model)) for r in results], + starts, + ) + + def followed(lengths, head=None): + if schedule.policy == "condition": + # Inspected at each time and kept unless due. + return condition_plan_availability( + *models, + lengths, + float(schedule.threshold), + node, + head, + older_than=schedule.older_than, + last_like=like, + ) + return plan_availability( + *models, + lengths, + node, + head, + like, + None if lives is None else lives[-len(lengths) :], # noqa + None if durations is None else durations[-len(lengths) :], # noqa + ) + + if not started: + return curve(followed(lengths), edges[: len(lengths)]) + assert start is not None + length = float(times[0]) + head = _unit_curve( + rbd, node, length, counts=True, start=start, unscheduled=True + ) + down_sf = None + if not start.alive: + down_sf = _first_unit(rbd, node, start, None, (), None, None).down_sf + + def failures(u): + return head.events(np.asarray(u, dtype=float))["failures"] + + up = float(head.at(np.array([length]))[0]) + reached: Any + if schedule.policy == "condition": + first = None + if start.alive: + # The unit in service now, if unfailed by the first + # inspection, and its age there. + ages = float(start.age) + np.array([0.0, length]) + alive = _sf_values(component.reliability.sf, ages) + first = (float(alive[1] / alive[0]), float(ages[1])) + reached = ConditionHead(length, up, failures, down_sf, first) + else: + reached = BlockHead(length, up, failures, down_sf) + results = followed(lengths[1:], reached) + tail = curve(results, edges[1 : len(lengths)] - length) # noqa: E203 + return StartedBlockCurve(head, tail, length) + + +def _knots(duration) -> np.ndarray: + """The knots of a replacement's time (none for none).""" + return np.empty(0) if duration is None else point_knots(duration) + + +def _plan_times(schedule, horizon: float): + """The times a component replaced at given times is replaced at, + and the model of the time each takes: its plan's (or a shutdown's) + times, each its ``duration``; at several shutdowns (``shuts``), the + starts of each in order up to the first after ``horizon`` (enough for + the stretches that cover it), each its own shut's.""" + if schedule.upgrade_at is not None: + # Block replacement on its interval, up to the first time after + # the horizon, and at the upgrade. + T = float(schedule.interval) + last = math.floor(max(horizon, 0.0) / T) + 1 + times = np.union1d(T * np.arange(1, last + 1), [schedule.upgrade_at]) + return times, [schedule.duration] * len(times) + if schedule.shuts is None: + times = np.asarray(schedule.times, dtype=float) + return times, [schedule.duration] * len(times) + stop = max(horizon, 0.0) + starts, models = [], [] + for shut, model in schedule.shuts: + # Up to and including its first start after the horizon. + own = shut.starts(np.nextafter(shut.due(stop), np.inf)) + starts.append(own) + models.extend([model] * len(own)) + times = np.concatenate(starts) + order = np.argsort(times, kind="stable") + return times[order], [models[i] for i in order] + + def _first_unit( rbd, node, start: NodeState, up_sf, up_splits, age, stage_model ) -> First: diff --git a/repyability/rbd/_degradation.py b/repyability/rbd/_degradation.py index f9ffab92..8f3d282a 100644 --- a/repyability/rbd/_degradation.py +++ b/repyability/rbd/_degradation.py @@ -29,6 +29,7 @@ """ import math +import sys import numpy as np from scipy.special import gammainc, gammaincinv, log_ndtr, ndtr @@ -45,7 +46,14 @@ def _kinds(): def is_degradation(model) -> bool: """Whether ``model`` is a surpyval Wiener or gamma degradation process - (fitted, or built), as a component life.""" + (fitted, or built), as a component life. + + No model can be one before ``surpyval.degradation`` is imported, so + until then it is not imported to check: it loads surpyval's + regression code with pandas, which took about 2 s of a session's + first diagram.""" + if "surpyval.degradation" not in sys.modules: + return False return isinstance(model, _kinds()) diff --git a/repyability/rbd/_discounted_long_run.py b/repyability/rbd/_discounted_long_run.py new file mode 100644 index 00000000..f8935761 --- /dev/null +++ b/repyability/rbd/_discounted_long_run.py @@ -0,0 +1,284 @@ +"""A ``RepairableRBD``'s equivalent annual cost in the long run: the steady +cost per unit time worth the same, at a discount rate, as every cost of +running the diagram for ever from new. + +Each component's own costs are discounted over its renewal cycle (Fox, +1966): a unit run to failure or replaced at an age starts afresh after +each repair or replacement, so the present value of all its costs is its +first cycle's over ``1 - E[exp(-r L)]``, ``L`` the cycle's length. With +``M`` the discounted time up, ``failed`` and ``kept`` the chances of a +cycle ending at a failure or at the age, each discounted to then, and +``m`` the discounted mean time of what follows (a repair, or the +replacement at the age), the rate cancels:: + + eac = (failed (c_f + d m_f) + kept (c_p + d m_p)) + / (M + failed m_f + kept m_p) + +which at rate 0 is the long-run cost rate (renewal reward). + +A component with hidden failures, tested and repaired in no time by tests +that find every failure, starts afresh at the test that finds it failed: +its cycle is the tests up to that one (``_tested_eac``), the first cycle +from new with its tests from their offset. The system's +own terms (the cost of its downtime, a value earned while it works) are +taken at its long-run availability: an approximation, as a system new at +0 is up more often at first, which ``basis`` says. +""" + +import math +from typing import Hashable + +import numpy as np + +from repyability.rbd import _requirements +from repyability.rbd._common import _crew_salaries +from repyability.rbd._mean_lifetime import _integrate, model_knots +from repyability.rbd._model_utils import MODEL_ERRORS, model_mean +from repyability.rbd._spec import _mean_cost + +#: Where a discounted time stops: where an amount is discounted to +#: ``exp(-REACH)``, or the time has all but surely ended. +REACH = 40.0 +ENDED = 1e-12 + +#: What a refusal names to run instead. +INSTEAD = ( + 'Use objective="npv" with a horizon, which discounts the expected ' + "costs over time (expected_npv), or simulate the plans " + "(npv_distribution)." +) + + +def _discounted_time(model, rate: float) -> float: + """The integral of ``exp(-r t) S(t)`` over all ``t``, ``S`` the + survival function of a time's ``model``: its discounted mean (its + mean at rate 0), and 0 for a time that is none.""" + if model is None: + return 0.0 + + def sf(t) -> np.ndarray: + return np.clip(np.ravel(np.asarray(model.sf(t), dtype=float)), 0, 1) + + if not float(sf(np.zeros(1))[0]) > 0.0: + return 0.0 + if rate == 0.0: + return float(model_mean(model)) + try: + upper = float(model_mean(model)) + except MODEL_ERRORS: + upper = math.nan + if not (math.isfinite(upper) and upper > 0.0): + upper = 1.0 + for _ in range(400): + if rate * upper >= REACH: + upper = REACH / rate + break + if float(sf(np.array([upper]))[0]) <= ENDED: + break + upper *= 2.0 + knots = model_knots(model) + inside = knots[(knots > 0.0) & (knots < upper)] + return float( + _integrate( + lambda t: np.exp(-rate * t) * sf(t), + np.concatenate(([0.0], inside, [upper])), + ) + ) + + +def require_discounted(rbd) -> None: + """Raise unless every priced part of the diagram has a discounted + long run worked out here: its priced components plain units or under + age replacement, with no repair crews to wait for, common-cause + groups, maintenance groups or shutdowns.""" + from repyability.rbd.repairable_rbd import RepairableRBD + + def refuse(what: str) -> None: + raise NotImplementedError( + f"The equivalent annual cost at a discount rate is worked out " + f"from each component's own renewal cycle, which {what} does " + f"not have. {INSTEAD}" + ) + + if rbd._crews_couple(): + refuse("a component that can wait for a repair crew") + if rbd.ccf_groups: + refuse("a member of a common-cause group") + if rbd._shutdowns: + refuse("a diagram with shutdowns") + if any(group.setup_cost for group in rbd._maintenance.values()): + refuse("a maintenance group with a set-up cost") + for node in rbd.costs: + component = rbd.components[node] + schedule = rbd._preventive.get(node) + if isinstance(component, RepairableRBD): + refuse(f"the nested RBD {node!r}") + if node in rbd._standby: + refuse(f"the standby group {node!r}") + if node in rbd._inspection and not _tested_cycle(rbd, node): + refuse( + f"the tested component {node!r}, whose tests or repairs " + "take time or can miss a failure," + ) + if node in rbd._imperfect: + refuse(f"component {node!r}, whose repairs are not perfect") + if node in rbd._early_members: + refuse(f"component {node!r}, renewed early at its group's stops") + if schedule is not None and schedule.policy != "age": + refuse(f"component {node!r}, under {schedule.policy} replacement,") + _requirements._require_full_restoration(rbd, node) + _requirements._require_times(rbd, node) + + +def _tested_cycle(rbd, node) -> bool: + """Whether a component with hidden failures has the cycle + ``_tested_eac`` discounts: tested and repaired in no time, by tests + at an interval that find every failure.""" + inspection = rbd._inspection[node] + return ( + _requirements._tested_kind(rbd, node) in ("closed", "life") + and not inspection.partial + and inspection.times is None + ) + + +def _tested_eac(rbd, node: Hashable, rate: float) -> float: + """The equivalent annual cost at ``rate`` (more than 0) of a + component with hidden failures (see ``_tested_cycle``): ``rate`` + times the present value of its costs for ever from new. + + A cycle from a new unit is the tests at ``t_1 < t_2 < ...`` up to the + first after its failure at ``X``, which finds it and renews it: + every test of the cycle is paid for, the failure when it is found, + and the unit's own downtime from ``X`` to then. With ``p_k`` the + chance that test ``k`` finds it, a cycle's discount is ``phi = sum + exp(-r t_k) p_k`` and its cost ``K``; the first cycle's tests are + from the offset, and every later one's an interval apart from the + test that began it, so the present value is ``K_1 + phi_1 K / (1 - + phi)``.""" + from repyability.maintenance._options import _discounted_length, _reach + + costs = rbd.costs.get(node, {}) + component = rbd.components[node] + inspection = rbd._inspection[node] + interval = float(inspection.interval) + survival = component.reliability_function + reach = _reach(component, rate) + # A new unit's failure, discounted: 1 - r M, M its discounted life. + failure = 1.0 - rate * _discounted_length(component, 0.0, reach, rate) + per_failure = sum( + _mean_cost(costs[key]) + for key in rbd.PER_FAILURE_COST_KEYS + if key in costs + ) + per_test = _mean_cost(costs.get("inspection_cost", 0.0)) + down = costs.get("downtime_cost", 0.0) + + def cycle(first: float): + """A cycle's cost, its discount and one less its discount, its + tests from ``first``.""" + count = max(int(math.ceil((reach - first) / interval)), 0) + 1 + tests = first + interval * np.arange(count) + alive = np.clip( + np.ravel( + np.asarray( + survival(np.concatenate(([0.0], tests))), dtype=float + ) + ), + 0.0, + 1.0, + ) + alive[0] = 1.0 + found = alive[:-1] - alive[1:] + factor = np.exp(-rate * tests) + discount = float(factor @ found) + cost = ( + per_test * float(factor @ alive[:-1]) + + per_failure * discount + + down * (failure - discount) / rate + ) + # What is left past the reach is discounted to nothing. + less = float(-np.expm1(-rate * tests) @ found) + float(alive[-1]) + return cost, discount, less + + cost, discount, less = cycle(interval) + if inspection.offset: + first_cost, first_discount, _ = cycle(float(inspection.offset)) + else: + first_cost, first_discount = cost, discount + return rate * (first_cost + first_discount * cost / less) + + +def node_eac(rbd, node: Hashable, rate: float) -> float: + """A component's own equivalent annual cost at ``rate`` (see the + module docstring): its failures', its replacements' at an age, its + tests' and its own downtime's.""" + from repyability.maintenance._options import cycle_eac + + if node in rbd._inspection: + return _tested_eac(rbd, node, rate) + costs = rbd.costs.get(node, {}) + component = rbd.components[node] + schedule = rbd._preventive.get(node) + age = math.inf if schedule is None else float(schedule.interval) + return cycle_eac( + component, + age, + rate, + failure_cost=sum( + _mean_cost(costs[key]) + for key in rbd.PER_FAILURE_COST_KEYS + if key in costs + ), + planned_cost=_mean_cost(costs.get("preventive_cost", 0.0)), + downtime=costs.get("downtime_cost", 0.0), + repair=_discounted_time(component.time_to_replace, rate), + planned=( + 0.0 + if schedule is None + else _discounted_time(schedule.duration, rate) + ), + ) + + +def system_terms(rbd, availability: float, value_rate: float) -> float: + """The diagram's own steady terms of an equivalent annual cost, at + its long-run ``availability``: the repair crews' salaries and the + cost of its downtime, less the value it earns while it works.""" + return ( + _crew_salaries(rbd) + + rbd.downtime_cost_rate * (1.0 - availability) + - value_rate * availability + ) + + +def basis(rbd, rate: float, value_rate: float) -> str: + """What a plan's equivalent annual cost is made of, in words: said on + the result, with what is approximate in it.""" + if rate == 0.0: + return "Not discounted: the long-run cost rate" + ( + ", less the value rate times the long-run availability." + if value_rate + else "." + ) + own = ( + "Each component's own costs are discounted over its renewal " + "cycle, exactly (Fox, 1966)." + ) + system = [ + name + for name, given in ( + ("the cost of the system's downtime", rbd.downtime_cost_rate), + ("the value earned while it works", value_rate), + ) + if given + ] + if not system: + return own + return ( + f"{own} Approximate: {' and '.join(system)} " + f"{'are' if len(system) > 1 else 'is'} taken at the long-run " + "availability, though a system new at 0 is up more often at " + 'first; objective="npv" with a horizon discounts the system\'s ' + "availability over time." + ) diff --git a/repyability/rbd/_downtime_risk.py b/repyability/rbd/_downtime_risk.py new file mode 100644 index 00000000..fef1b514 --- /dev/null +++ b/repyability/rbd/_downtime_risk.py @@ -0,0 +1,453 @@ +"""The least spend that keeps a bad run's downtime under a limit +(``RepairableRBD.least_spend_for_downtime``, UC-68 of the maintenance +README). + +The target is the system's downtime over a horizon, in hours or as its +cost (each hour down at the diagram's ``downtime_cost_rate`` and any +``value_rate`` lost), counting all of it (``downtime="all"``) or the +unplanned part alone. A design meets the limit when an upper confidence +bound on the downtime's risk measure (``repyability.value._risk``: the +quantile at ``level``, an order statistic, or the tail mean) is at or +under it. + +The levers are each at their own price, and spend has no bound but an +optional ``budget``: + +- ``redundancy``: copies of a node in parallel with it, at a price each + (drawn as ``allocate_redundancy`` draws a train of one node: fed as the + node is, feeding the node it feeds, whose ``k`` is kept); +- ``intervals``: a node's preventive task's interval, through the + candidates given, its spend the expected preventive cost over the + horizon (from the same runs). + +The search is greedy marginal analysis, as the allocations' searches +are: from the diagram as it is, each step takes the move that lowers the +risk estimate most per extra spend, every design run on the same seed +(common random numbers), until a design meets the limit or no move +lowers the risk. Its designs are the frontier of spend against the bad +run's downtime. When the levers stop short, the result says which floor +stopped them: the budget, the levers' caps, or downtime no lever left +lowers (the planned task downtime, when it is planned). + +Every design reports both planned and unplanned downtime (each +simulation's, from the engines' own split, ``_unplanned``): their means +and their quantiles at ``level``, in hours and, with a rate, in cost. +""" + +import math +from typing import Dict, Hashable, List, Mapping, Optional, Tuple + +import numpy as np + +from repyability.rbd.results import DowntimeDesign, DowntimeRiskResult +from repyability.utils import checks +from repyability.value import _risk + +#: Each design's runs by default. +MC_SAMPLES = 2000 +#: The most steps the search takes. +MAX_STEPS = 200 + + +def _share(value, name: str) -> float: + number = checks.number_or_nan(value) + if not 0.0 < number < 1.0: + raise ValueError( + f"{name} must be a share strictly between 0 and 1; got " + f"{value!r}." + ) + return float(number) + + +def _copy_name(rbd, node, index: int): + name = f"{node} (copy {index})" + if name in rbd.G.nodes: + raise ValueError( + f"A copy of node {node!r} would be named {name!r}, which the " + "diagram already has: rename that node." + ) + return name + + +def _levers(rbd, redundancy, intervals, max_units): + """The levers, checked: each redundancy node's price and cap, each + interval node's candidates.""" + from repyability.rbd import _repairable_allocation as allocation + from repyability.rbd import _requirements + + prices: Dict[Hashable, float] = {} + caps: Dict[Hashable, Optional[int]] = {} + for node, price in (redundancy or {}).items(): + _requirements._require_component(rbd, node, "redundancy") + allocation._allocation_trains(rbd, {("copies", node): [node]}, ()) + if not isinstance(rbd._init_args["components"].get(node), dict): + raise ValueError( + f"Node {node!r} is not given as a spec or a UnitPlan, so it " + "cannot be copied here: give it as one." + ) + grouped = [ + name + for name, spec in ( + rbd._init_args.get("maintenance_groups") or {} + ).items() + if node in spec.get("members", ()) + ] + if grouped or any( + node in getattr(g, "members", ()) for g in rbd.ccf_groups + ): + raise NotImplementedError( + f"Node {node!r} is in a maintenance or common-cause group, " + "which its copies would have to join: copy nodes outside " + "groups, or use allocate_redundancy for groups." + ) + cost = checks.number_or_nan(price) + if not (math.isfinite(cost) and cost > 0.0): + raise ValueError( + f"The price of a copy of node {node!r} must be a number " + f"more than 0; got {price!r}." + ) + prices[node] = float(cost) + cap = None if max_units is None else max_units.get(node) + if cap is not None and not ( + checks.is_number(cap) and int(cap) == cap and cap >= 0 + ): + raise ValueError( + f"max_units for node {node!r} must be a whole number of " + f"copies, at least 0; got {cap!r}." + ) + caps[node] = None if cap is None else int(cap) + candidates: Dict[Hashable, Tuple[float, ...]] = {} + for node, values in (intervals or {}).items(): + _requirements._require_component(rbd, node, "intervals") + spec = rbd._init_args["components"].get(node) + preventive = spec.get("preventive") if isinstance(spec, dict) else None + if not isinstance(preventive, dict) or "interval" not in preventive: + raise ValueError( + f"Node {node!r} has no preventive task with an interval to " + "move: give it one (its 'preventive' spec's 'interval')." + ) + row = checks.real_array(values, f"intervals[{node!r}]").ravel() + if row.size == 0 or not np.all(np.isfinite(row) & (row > 0.0)): + raise ValueError( + f"intervals[{node!r}] must be the intervals to try, in the " + f"order to try them, each more than 0; got {values!r}." + ) + candidates[node] = tuple(float(v) for v in row) + return prices, caps, candidates + + +def _design(rbd, copies: Dict, steps: Dict, candidates: Dict): + """The diagram with ``copies[node]`` copies of each node and each + interval node's task at ``candidates[node][steps[node] - 1]`` (as + given at step 0).""" + from repyability.rbd.repairable_rbd import RepairableRBD + + if not any(copies.values()) and not any(steps.values()): + return rbd + args = dict(rbd._init_args) + components = dict(args["components"]) + edges = [tuple(e) for e in args["edges"]] + k = dict(args.get("k") or {}) + for node, step in steps.items(): + if step: + spec = dict(components[node]) + spec["preventive"] = dict( + spec["preventive"], interval=candidates[node][step - 1] + ) + components[node] = spec + for node, count in copies.items(): + feeds = list(rbd.G.predecessors(node)) + exit_node = next(iter(rbd.G.successors(node))) + for index in range(1, count + 1): + name = _copy_name(rbd, node, index) + components[name] = components[node] + edges += [(u, name) for u in feeds] + [(name, exit_node)] + args.update(edges=edges, components=components, k=k or None) + return RepairableRBD(**args) + + +def _evaluate( + diagram, + horizon, + n, + seed, + engine, + rate, + downtime, + measure, + level, + confidence, + objective, +): + """One design's runs: its risk, and its planned and unplanned + downtime.""" + run = diagram.availability( + horizon, + mc_samples=n, + seed=seed, + engine=engine, + control_variate=False, + conditional=False, + ) + down = horizon - np.asarray(run.uptimes, float) + unplanned = ( + down + if run.unplanned_downtimes is None + else np.asarray(run.unplanned_downtimes, float) + ) + planned = np.maximum(down - unplanned, 0.0) + target = down if downtime == "all" else unplanned + scale = 1.0 if measure == "hours" else rate + found = _risk.risk(target * scale, level, objective, confidence) + preventive = 0.0 + if run.cost is not None: + preventive = float(run.cost.by_category.get("preventive", 0.0)) + + def summary(values) -> Dict[str, Optional[float]]: + ordered = np.sort(values) + hours = (float(values.mean()), _risk.quantile(ordered, level)) + return { + "mean_hours": hours[0], + "bad_hours": hours[1], + "mean_cost": hours[0] * rate if rate else None, + "bad_cost": hours[1] * rate if rate else None, + } + + return found, summary(planned), summary(unplanned), preventive + + +def least_spend_for_downtime( + rbd, + horizon, + limit, + *, + level: float, + objective: str, + measure: str, + downtime: str, + redundancy: Optional[Mapping], + intervals: Optional[Mapping], + max_units: Optional[Mapping], + budget, + value_rate: float, + confidence: float, + mc_samples: Optional[int], + seed, + engine: str, +) -> DowntimeRiskResult: + """See ``RepairableRBD.least_spend_for_downtime``.""" + from repyability.rbd import _npv_runs + + horizon = checks.number_or_nan(horizon) + if not (math.isfinite(horizon) and horizon > 0.0): + raise ValueError( + f"horizon must be a number more than 0; got {horizon!r}." + ) + level = _share(level, "level") + confidence = _share(confidence, "confidence") + checks.one_of("objective", objective, _risk.MEASURES) + checks.one_of("measure", measure, ("hours", "cost")) + checks.one_of("downtime", downtime, ("all", "unplanned")) + checks.one_of("engine", engine, ("auto", "python", "numba")) + worth = checks.number_or_nan(value_rate) + if not (math.isfinite(worth) and worth >= 0.0): + raise ValueError( + f"value_rate must be a number, at least 0; got {value_rate!r}." + ) + rate = float(rbd.downtime_cost_rate) + float(worth) + if measure == "cost" and rate <= 0.0: + raise ValueError( + 'measure="cost" needs downtime to cost something: give the ' + "diagram a downtime_cost_rate, or value_rate= (the value lost " + 'per hour down), or measure="hours".' + ) + bound = checks.number_or_nan(limit) + if not (math.isfinite(bound) and bound > 0.0): + raise ValueError( + "limit must be the downtime a bad run must stay under, a " + f"number more than 0; got {limit!r}." + ) + if budget is not None: + cap = checks.number_or_nan(budget) + if not (math.isfinite(cap) and cap >= 0.0): + raise ValueError( + f"budget must be a number, at least 0; got {budget!r}." + ) + budget = float(cap) + n = checks.whole_number( + MC_SAMPLES if mc_samples is None else mc_samples, "mc_samples" + ) + seed = _npv_runs._seed(seed) + prices, caps, candidates = _levers(rbd, redundancy, intervals, max_units) + + designs: List[DowntimeDesign] = [] + cache: Dict[tuple, DowntimeDesign] = {} + base_preventive: List[float] = [] + used = [engine] + methods = [""] + + def key(copies, steps): + return tuple(sorted(copies.items(), key=repr)) + tuple( + sorted(steps.items(), key=repr) + ) + + def score(copies: Dict, steps: Dict) -> DowntimeDesign: + found = cache.get(key(copies, steps)) + if found is not None: + return found + diagram = _design(rbd, copies, steps, candidates) + risk, planned, unplanned, preventive = _evaluate( + diagram, + horizon, + n, + seed, + engine, + rate, + downtime, + measure, + level, + confidence, + objective, + ) + methods[0] = risk.bound_method + if not base_preventive: + base_preventive.append(preventive) + spend = sum(prices[node] * c for node, c in copies.items()) + ( + preventive - base_preventive[0] + ) + design = DowntimeDesign( + copies=dict(copies), + intervals={ + node: (candidates[node][s - 1] if s else None) + for node, s in steps.items() + }, + spend=float(spend), + estimate=risk.estimate, + bound=risk.bound, + meets=risk.bound <= bound, + planned=planned, + unplanned=unplanned, + ) + cache[key(copies, steps)] = design + return design + + copies = {node: 0 for node in prices} + steps = {node: 0 for node in candidates} + current = score(copies, steps) + designs.append(current) + floor = None + over_budget = False + for _ in range(MAX_STEPS): + if current.meets: + break + moves = [] + for node in prices: + if caps[node] is None or copies[node] < caps[node]: + moves.append(({**copies, node: copies[node] + 1}, steps)) + for node in candidates: + # Any later interval: a quantile can stay put over one step. + for step in range(steps[node] + 1, len(candidates[node]) + 1): + moves.append((copies, {**steps, node: step})) + if not moves: + floor = "caps" + break + best, best_gain = None, 0.0 + over_budget = False + for move_copies, move_steps in moves: + option = score(move_copies, move_steps) + drop = current.estimate - option.estimate + if drop <= 0.0: + continue + if budget is not None and option.spend > budget: + over_budget = True + continue + extra = option.spend - current.spend + gain = math.inf if extra <= 0.0 else drop / extra + if best is None or gain > best_gain: + best, best_gain = (move_copies, move_steps, option), gain + if best is None: + floor = "budget" if over_budget else "lowest" + break + copies, steps, current = dict(best[0]), dict(best[1]), best[2] + designs.append(current) + else: + floor = "steps" + + met = [d for d in designs if d.meets] + answer = min(met, key=lambda d: d.spend) if met else None + stopped = None + if answer is None: + last = designs[-1] + planned_bad = float(last.planned["bad_hours"] or 0.0) * ( + 1.0 if measure == "hours" else rate + ) + if downtime == "all" and planned_bad >= bound: + floor = "planned" + stopped = _floor_words(floor, last, bound, measure, budget) + return DowntimeRiskResult( + horizon=float(horizon), + limit=float(bound), + level=level, + objective=objective, + measure=measure, + downtime=downtime, + confidence=confidence, + bound_method=methods[0], + budget=budget, + met=answer is not None, + design=( + answer + if answer is not None + else min(designs, key=lambda d: d.estimate) + ), + frontier=_frontier(list(cache.values())), + floor=None if answer is not None else floor, + stopped=stopped, + n_simulations=n, + seed=seed, + engine=used[0], + ) + + +def _frontier(designs: List[DowntimeDesign]) -> List[DowntimeDesign]: + """The designs no other beats on both spend and bad-run downtime, + by spend: more spend never raises the downtime along it.""" + out: List[DowntimeDesign] = [] + for design in sorted(designs, key=lambda d: (d.spend, d.estimate)): + if not out or design.estimate < out[-1].estimate: + out.append(design) + return out + + +def _floor_words(floor, last, limit, measure, budget) -> str: + unit = "hours" if measure == "hours" else "in cost" + lowest = ( + f"The lowest bad-run downtime the levers reached is " + f"{last.estimate:.6g} {unit} (bound {last.bound:.6g}), against a " + f"limit of {limit:.6g}" + ) + if floor == "budget": + return ( + f"{lowest}: the budget ({budget:.6g}) stopped them; a move " + "that would lower it further costs more. Raise budget=, or " + "leave it out." + ) + if floor == "caps": + return ( + f"{lowest}: every lever is at its cap (max_units, or the last " + "interval given). Raise max_units, or give more intervals." + ) + if floor == "planned": + return ( + f"{lowest}: {last.planned['bad_hours']:.6g} hours of a bad " + "run are planned task downtime, at or over the limit alone; " + "shorter intervals add to it, and copies with the same tasks " + "do not remove it. Give tasks that take less time, or " + 'downtime="unplanned".' + ) + if floor == "steps": + return f"{lowest}: the search took its most steps ({MAX_STEPS})." + return ( + f"{lowest}: no lever given lowers it further. Give other levers " + "(redundancy=, intervals=)." + ) diff --git a/repyability/rbd/_duty.py b/repyability/rbd/_duty.py index 4d5e72d2..dfdc02b9 100644 --- a/repyability/rbd/_duty.py +++ b/repyability/rbd/_duty.py @@ -3,17 +3,23 @@ A node that operates a fraction ``d`` of the calendar ages only then, so its life in calendar time is its operating life over ``d``: ``R_c(t) = -R(d t)``. A surpyval parametric distribution of a time stays one under that -change of scale, with its parameters moved (``_SCALED``), so the node keeps +R(d t)``. A surpyval model of a time stays one of its kind under that +change of scale, with its times moved: the model moves itself where it can +(``rescale_time``, from the surpyval release after 0.28), so the node keeps its model's kind and every exact method and simulation takes it as it would -the model fitted in calendar time. +the model fitted in calendar time. With surpyval 0.28, which has no +``rescale_time``, ``_SCALED`` moves the parameters of each distribution +(the workaround goes once the minimum surpyval rescales). """ import math -from typing import Callable, Dict, List +from typing import Any, Callable, Dict, List, Union + +import numpy as np from repyability.utils.checks import is_number +from ._covariate_schedule import ClockLife from ._model_utils import distribution_name, is_fixed_probability @@ -28,7 +34,8 @@ def _location_scale(p: List[float], d: float) -> List[float]: #: How each surpyval distribution's parameters move when its time is -#: divided by ``d`` (``R_c(t) = R(d t)``). +#: divided by ``d`` (``R_c(t) = R(d t)``), for a surpyval whose models do +#: not rescale themselves (0.28). _SCALED: Dict[str, Callable[[List[float], float], List[float]]] = { "Exponential": lambda p, d: [p[0] * d], "Weibull": _scale_first, @@ -63,20 +70,195 @@ def duty_fraction(node, value) -> float: return d +def planned_refusals(node, spec: dict) -> None: + """Refuse what a block on a duty plan that changes over time cannot + go with: a virtual age (imperfect repair, partial restoration), whose + operating time would run at a pace that changes; replacement on + condition, which judges the next inspection's risk at the age alone; + and a standby group, whose spares age on a clock of their own.""" + lead = f"Component {node!r} runs on a duty plan that changes over time" + preventive = spec.get("preventive") + restoring = ( + isinstance(preventive, dict) + and preventive.get("restoration") is not None + ) + if spec.get("repair") is not None or restoring: + raise NotImplementedError( + f"{lead}, and keeps a virtual age (imperfect repair or partial " + "restoration), which is not followed on a plan that changes " + "yet: give repairs and tasks that renew, or the duty as one " + "share." + ) + if isinstance(preventive, dict) and preventive.get("policy") == ( + "condition" + ): + raise NotImplementedError( + f"{lead}, and is replaced on condition, whose threshold judges " + "the chance of failing before the next inspection at the " + "unit's age alone: give it age or block replacement, or the " + "duty as one share." + ) + if spec.get("standby") is not None: + raise NotImplementedError( + f"{lead}, and is a standby group, whose spares age on a clock " + "of their own: give the duty as one share." + ) + + +def duty_value(node, value) -> Union[float, Any]: + """A node's duty, checked: a share of the time in ``(0, 1]``, or a + duty plan that changes over time (a ``schedule.DutySchedule``, or the + dict it saves as: from ``times[k]``, the share ``shares[k]``). A plan + of one share is that share.""" + from repyability.schedule import DutySchedule + + if isinstance(value, dict) and {"times", "shares"} <= set(value): + value = DutySchedule( + str(value.get("unit", "hours")), + tuple(float(t) for t in value["times"]), + tuple(float(x) for x in value["shares"]), + ) + if not isinstance(value, DutySchedule): + return duty_fraction(node, value) + lead = f"The duty plan of node {node!r}" + times = np.asarray(value.times, dtype=float) + shares = np.asarray(value.shares, dtype=float) + if times.size == 0 or times.size != shares.size: + raise ValueError( + f"{lead} must have a share for each of its times, and at least " + f"one; got {times.size} times and {shares.size} shares." + ) + if times[0] != 0.0 or not np.all(np.diff(times) > 0.0): + raise ValueError( + f"{lead} must start at 0, the diagram's start, its times " + f"increasing (UsageForecast.schedule() gives one); got times " + f"from {times[0]:g}." + ) + if not (np.all(np.isfinite(times)) and np.all(np.isfinite(shares))): + raise ValueError(f"{lead} must have finite times and shares.") + if np.any(shares < 0.0) or np.any(shares > 1.0) or not np.any(shares): + raise ValueError( + f"{lead} must have shares of the time in [0, 1], at least one " + "above 0." + ) + if np.all(shares == shares[0]): + return duty_fraction(node, float(shares[0])) + return value + + +class PlannedLife(ClockLife): + """A unit's life in operating time on a duty plan that changes over + time: from ``times[k]`` of the diagram's clock it operates the share + ``shares[k]`` of the time (the last held on), so its operating time is + ``D(t)``, piecewise linear from ``D(0) = 0``. A unit put into service + at ``t0`` fails when ``D`` has run its operating life on from + ``D(t0)``: at ``D⁻¹(D(t0) + L)``, ``L`` drawn from the model's own + quantile function. From new at 0 its survival is ``R(D(t))`` (exact); + a unit put in later has another, so the diagram's exact methods do not + take it, and only the simulations (the Python engine) do. + + Parameters + ---------- + model + The life in operating time: any model with ``qf`` and ``sf``. + plan : schedule.DutySchedule + The shares over the diagram's clock (``duty_value`` checks it). + node : hashable + The block's name, for the messages. + """ + + clock = True + new_only = True + lead = "runs on a duty plan that changes over time" + aged = "whose operating time runs at a pace that changes" + + def __init__(self, model: Any, plan: Any, node: Any = None): + self.model = model + self.plan = plan + self.node = node + self._times = np.asarray(plan.times, dtype=float) + self._shares = np.asarray(plan.shares, dtype=float) + hours = np.concatenate( + ([0.0], np.cumsum(self._shares[:-1] * np.diff(self._times))) + ) + #: D at each time of the plan. + self._hours = hours + + def operating(self, t): + """``D(t)``: the operating time from the diagram's 0 to ``t``.""" + x = np.asarray(t, dtype=float) + k = np.clip( + np.searchsorted(self._times, x, side="right") - 1, + 0, + self._times.size - 1, + ) + out = self._hours[k] + self._shares[k] * (x - self._times[k]) + out = np.where(x <= 0.0, 0.0, out) + return float(out) if out.ndim == 0 else out + + def inverse(self, y: float) -> float: + """``D⁻¹(y)``: the first time the operating time reaches ``y`` + (``inf`` if it never does).""" + y = float(y) + if not y > 0.0: + return 0.0 + if math.isinf(y): + return math.inf + k = int(np.searchsorted(self._hours, y, side="left")) - 1 + share = float(self._shares[k]) + if share == 0.0: + return math.inf # the last share is 0: it never gets there + return float(self._times[k] + (y - self._hours[k]) / share) + + def life_left(self, t0: float, age: float, u: float) -> float: + """The time on the diagram's clock to the failure of a unit put + into service new at ``t0``, from the uniform ``u`` (no ``age``: a + state other than new is refused).""" + life = float(np.ravel(self.model.qf(np.array([u])))[0]) + return self.inverse(self.operating(t0) + life) - t0 + + def sf(self, x): + """``R(D(x))``: a unit new at 0 is up at ``x``.""" + return self.model.sf(self.operating(x)) + + def ff(self, x): + return self.model.ff(self.operating(x)) + + def Hf(self, x): + return self.model.Hf(self.operating(x)) + + def mean(self): + raise self._no_reliability("mean life") + + def random(self, size): + raise self._no_reliability("draws without a start time") + + def __repr__(self) -> str: + return ( + f"PlannedLife({type(self.model).__name__}, " + f"{self._times.size} steps)" + ) + + def on_calendar(node, model, d: float): """``model``, a life in operating time, as the life on the calendar of - a node that operates the fraction ``d`` of the time; raise for a model - that is not a surpyval parametric distribution of a time.""" + a node that operates the fraction ``d`` of the time: the model's own + ``rescale_time(d)`` where it has one, else (surpyval 0.28) a surpyval + parametric distribution with its parameters moved (``_SCALED``); + raise for any other model.""" if d == 1.0: return model + rescale = getattr(model, "rescale_time", None) + if callable(rescale) and not is_fixed_probability(model): + return rescale(d) name = distribution_name(model) move = _SCALED.get(name) if name is not None else None if move is None or is_fixed_probability(model): raise ValueError( - f"Node {node!r} is given a duty, which moves a surpyval " - "parametric distribution of a time onto the calendar, but its " - f"life is {name or type(model).__name__}: give the life it has " - "on the calendar instead." + f"Node {node!r} is given a duty, which moves a life in " + "operating time onto the calendar, but its life is " + f"{name or type(model).__name__}, which cannot be moved: give " + "the life it has on the calendar instead." ) import surpyval @@ -89,6 +271,28 @@ def on_calendar(node, model, d: float): return getattr(surpyval, name).from_params(move(params, d), **extras) +def _clocked_task(node, key: str, task: dict) -> None: + """Refuse a task counted in operating time on a duty plan that + changes over time that the simulation does not place on it.""" + lead = ( + f"Component {node!r} runs on a duty plan that changes over time, " + f"and its {key} is counted in operating time" + ) + if key == "inspection": + raise NotImplementedError( + f"{lead}: tests counted in operating time are not placed on a " + "plan that changes yet. Give the test interval in calendar " + "time, or the duty as one share." + ) + for name in ("opportunity", "older_than"): + if task.get(name) is not None: + raise NotImplementedError( + f"{lead}, with an age for the stops ({name!r}), which is " + "not placed on a plan that changes yet: drop it, or give " + "the duty as one share." + ) + + #: What a task's times (``"basis"``) are counted in: the diagram's clock, #: the calendar (the default), or the block's operating time. BASES = ("calendar", "operating") @@ -105,10 +309,15 @@ def tasks_on_calendar(node, spec: dict, d): """``spec`` with each task (a ``"preventive"`` or ``"inspection"``) on the calendar: one counted in operating time (``"basis": "operating"``) has its times divided by ``d``, the block's duty (None - for none), and the basis is taken off either way. Return the spec - and whether a task was counted in operating time; refuse a basis - other than ``BASES``, and one in operating time with no duty, at a - shutdown or under a ``"calendar"`` policy.""" + for none), and the basis is taken off either way. On a duty plan that + changes over time (``d`` a ``PlannedLife``) a preventive task keeps + its times in operating time, for its ``_Preventive``'s ``clock`` to + place; with no duty, the diagram's clock is the block's operating + time. Return the spec and whether a task was counted in operating + time; refuse a basis other than ``BASES``, and one in operating time + at a shutdown or under a ``"calendar"`` policy (and, on + a plan that changes, an inspection, or an age at which a stop renews + the unit).""" from repyability.utils.checks import one_of out = spec @@ -135,18 +344,26 @@ def tasks_on_calendar(node, spec: dict, d): "counted in operating time: drop its basis." ) if d is None: - raise ValueError( - f"Component {node!r}: its {key} is counted in " - "operating time, which needs the block's duty: give " - "the block's duty, the share of the time it operates, " - "or give the interval in calendar time." - ) + # No duty here: the diagram's clock is the block's + # operating time, until an analysis's calendar gives the + # block its duty plan (schedule.CalendarContext). + d = 1.0 operating = True + if isinstance(d, PlannedLife): + _clocked_task(node, key, task) + out = {**out, key: task} + continue for name in times: value = task.get(name) if value is not None and is_number(value): # Not refused here if not a number: the task's own # checks say what it must be. task[name] = float(value) / d + plan = task.get("replace_at") if key == "preventive" else None + if plan is not None: + try: + task["replace_at"] = [float(t) / d for t in plan] + except (TypeError, ValueError): + pass # not numbers: the task's own check says so out = {**out, key: task} return out, operating diff --git a/repyability/rbd/_event_loop.py b/repyability/rbd/_event_loop.py index 9576a3d6..90323181 100644 --- a/repyability/rbd/_event_loop.py +++ b/repyability/rbd/_event_loop.py @@ -41,6 +41,7 @@ _unplanned, ) from repyability.rbd._common import ( + _crew_salaries, _keeps_virtual_age, _safe_mean, ) @@ -491,11 +492,13 @@ def maintained(self, t: float) -> None: return restoration: Any = self._restoration x = t - self.since - self.age = ( - restoration.q * (self.age + x) - if restoration.kijima == "kijima2" - else self.age + restoration.q * x - ) + if restoration.kijima == "to_age": + # To a given virtual age, whatever its age before (#570). + self.age = restoration.q + elif restoration.kijima == "kijima2": + self.age = restoration.q * (self.age + x) + else: + self.age = self.age + restoration.q * x self._fails_next = True self.operated = 0.0 self.tasks += 1 @@ -567,10 +570,82 @@ def _life(self) -> float: return self._unit.reliability.life_left(self.now, self.age, u) +class _UpgradedComponent(_StreamedComponent): + """Stands in during a simulation for an upgraded component (a spec's + ``"upgrade"``, see ``_spec._Upgrade``): as ``_StreamedComponent``, + but each life is a uniform of its ``FAILURE`` stream turned into a + time by the life in service when it starts (the time ``now`` the loop + sets before each draw, ``_clock``): the component's own before the + upgrade's time ``at``, the upgrade's from it. So an upgrade to the + same life is a plain replacement at ``at``, draw for draw. The unit + up at ``at`` is replaced then by the component's schedule, and one in + a repair is back with the new life once it is repaired. Without + streams, each life is drawn by its model from numpy's global RNG.""" + + __slots__ = ("now", "_at", "_lives") + + def __init__( + self, + uniforms, + repair, + lives, + at: float, + start=None, + timed=(None, None), + ): + # ``timed``: its block replacements' times, a stream and the model. + super().__init__(uniforms, repair, timed[0], timed[1], start) + self.now = 0.0 + self._at = at + #: The two lives' quantile functions (with streams), or their + #: models' draws (without). + self._lives = lives + + def next_event(self): + if not self._fails_next: + return super().next_event() + self._fails_next = False + life = self._lives[self.now >= self._at] + if self._failure is None: + return life.draw(), False + u = np.array([self._failure.draw()]) + return float(np.asarray(life(u), dtype=float)[0]), False + + +def _upgraded(rbd, node, run=None, path: tuple = ()) -> _UpgradedComponent: + """The stand-in of upgraded component ``node`` (see + ``_UpgradedComponent``): its draws from its streams in ``run``, at + ``path``, where it has them, else from its models and numpy's global + RNG.""" + component, upgrade = rbd.components[node], rbd._upgrades[node] + models = (component.reliability, upgrade.life) + uniforms = repair = start = duration = None + if run is not None: + uniforms = run.stream(path, _streams.FAILURE) + repair = run.stream(path, _streams.REPAIR) + start = run.stream(path, _streams.START) + duration = run.stream(path, _streams.DURATION) + timed = (duration, _duration_model(rbd, node)) + if uniforms is None or repair is None: + return _UpgradedComponent( + None, + _ModelDraws(component.time_to_replace), + tuple(_ModelDraws(model) for model in models), + upgrade.at, + start, + timed, + ) + lives = tuple(stream_sampler(model) for model in models) + return _UpgradedComponent( + uniforms, repair, lives, upgrade.at, start, timed + ) + + def _clock(source, t: float) -> None: - """Tell a component on a covariate schedule that its next draw is - made at ``t`` (a life starting then); nothing for any other.""" - if source.__class__ is _ScheduledComponent: + """Tell a component on a covariate schedule, or an upgraded one, that + its next draw is made at ``t`` (a life starting then); nothing for + any other.""" + if source.__class__ in (_ScheduledComponent, _UpgradedComponent): source.now = t @@ -714,25 +789,72 @@ def _simulate_block(span: Tuple[int, int]) -> "_Tally": class _Shut: """A shutdown in a simulation (see ``_shutdowns``), the component of the events of its windows: a start (status False), which holds its - ``nodes`` off line, charges its ``cost`` and stands its ``paused`` - nodes' own processes still, and an end ``duration`` later (status - True), which lets them go.""" + ``nodes`` off line, charges its ``cost``, stands its ``paused`` + nodes' own processes still and renews each of its ``opportunistic`` + components (with its age) that is that old (see ``_outage_renewals``), + and an end ``duration`` later (status True), which lets them go. + ``places`` gives each start's place in a simulation's + ``outage_jobs``, where its renewals are counted.""" - __slots__ = ("name", "nodes", "paused", "duration", "cost") + __slots__ = ( + "name", + "nodes", + "paused", + "duration", + "cost", + "opportunistic", + "places", + ) - def __init__(self, name, nodes, paused, duration: float, cost: float): + def __init__( + self, + name, + nodes, + paused, + duration: float, + cost: float, + opportunistic: tuple = (), + places: Optional[dict] = None, + ): self.name, self.nodes, self.paused = name, nodes, paused self.duration, self.cost = duration, cost + self.opportunistic, self.places = opportunistic, places or {} + + +def outage_starts(rbd, t_simulation: float) -> List[Tuple[Hashable, float]]: + """The starts of the shutdowns that renew components opportunistically + in ``[0, t_simulation)``, as ``(name, time)``, shut by shut: the + outages whose renewals a simulation counts (``outage_jobs``).""" + return [ + (shut.name, float(start)) + for shut in rbd._shutdowns.values() + if rbd._outage_rules.get(shut.name) + for start in shut.starts(t_simulation) + ] def _shut_events(rbd, t_simulation: float, forced: set) -> list: """The events of the shutdowns' windows in ``[0, t_simulation)``: each start, and its end if it falls in the window, the nodes held at - ``forced`` left out (they are held whatever a shut does).""" + ``forced`` left out (they are held whatever a shut does). A shut in + no time that costs or renews components opportunistically has its + starts alone, which hold nothing (but charge its cost).""" from repyability.rbd import _shutdowns out = [] - for shut in _shutdowns.timed(rbd): + first = 0 + for shut in rbd._shutdowns.values(): + rules = tuple( + (node, age) + for node, age in rbd._outage_rules.get(shut.name, ()) + if node not in forced + ) + if not ( + shut.duration > 0.0 + or shut.cost + or rbd._outage_rules.get(shut.name) + ): + continue nodes = tuple( node for node in _shutdowns.scope(rbd, shut) if node not in forced ) @@ -740,13 +862,22 @@ def _shut_events(rbd, t_simulation: float, forced: set) -> list: node for node in nodes if not shut.idle_ageing - and shut.name not in _shutdowns.bound_to(rbd, node) + and shut.name not in _shutdowns.worked_on(rbd, node) ) - source = _Shut(shut.name, nodes, paused, shut.duration, shut.cost) - for start in shut.starts(t_simulation): - out.append(Event(float(start), source, False)) + if not shut.duration > 0.0: + nodes = paused = () + starts = [float(start) for start in shut.starts(t_simulation)] + places = {} + if rbd._outage_rules.get(shut.name): + places = {start: first + k for k, start in enumerate(starts)} + first += len(starts) + source = _Shut( + shut.name, nodes, paused, shut.duration, shut.cost, rules, places + ) + for start in starts: + out.append(Event(start, source, False)) end = float(start) + shut.duration - if end < t_simulation: + if shut.duration > 0.0 and end < t_simulation: out.append(Event(end, source, True)) return out @@ -912,6 +1043,11 @@ def close(self) -> None: _ACTION_COST_KEYS = ("preventive_cost", "inspection_cost", "replacement_cost") +#: The place of the repair crews' costs among the categories. +_CREWS = _CATEGORIES.index("crews") +_CAPITAL = _CATEGORIES.index("capital") + + def _validate_crews(crews) -> Optional[int]: """``repair_crews``, validated: a whole number of crews, at least 1, or None for as many as are needed.""" @@ -964,19 +1100,24 @@ def _failures_between(model, ages: np.ndarray) -> np.ndarray: return out -def _on_duty(components: dict) -> Tuple[dict, dict]: +def _on_duty(components: dict) -> Tuple[dict, dict, dict]: """The components, each spec whose life is at a usage rate given the surpyval distribution it is (``_usage.first_clock_life``), each spec with a ``"duty"`` given its life on the - calendar (see ``_duty.on_calendar``): one object for each model and + calendar (see ``_duty.on_calendar``; on a duty plan that changes over + time, a ``_duty.PlannedLife``): one object for each model and duty, so that components sharing a model still share it; and each task counted in operating time put on the calendar through its - block's duty (``_duty.tasks_on_calendar``). Return them, and the duty + block's duty (``_duty.tasks_on_calendar``). Return them, the duty of each component with such a task (its tasks' times in operating - time per unit of calendar time).""" + time per unit of calendar time), and the ``PlannedLife`` of each + component whose preventive task is counted in operating time on a + plan that changes (its task's ``clock``).""" from repyability.rbd._duty import ( - duty_fraction, + PlannedLife, + duty_value, on_calendar, + planned_refusals, tasks_on_calendar, ) from repyability.rbd._usage import first_clock_life, is_life_at_usage @@ -984,6 +1125,7 @@ def _on_duty(components: dict) -> Tuple[dict, dict]: moved: dict = {} out = {} operating: dict = {} + clocks: dict = {} for name, component in components.items(): if isinstance(component, dict): d = None @@ -996,18 +1138,25 @@ def _on_duty(components: dict) -> Tuple[dict, dict]: "reliability": moved["usage", id(life)], } if component.get("duty") is not None: - d = duty_fraction(name, component["duty"]) + d = duty_value(name, component["duty"]) life = component["reliability"] - key = (id(life), d) - if key not in moved: - moved[key] = on_calendar(name, life, d) - component = {**component, "reliability": moved[key]} + if isinstance(d, float): + key = (id(life), d) + if key not in moved: + moved[key] = on_calendar(name, life, d) + component = {**component, "reliability": moved[key]} + else: + planned_refusals(name, component) + d = PlannedLife(life, d, name) + component = {**component, "reliability": d} component, counted = tasks_on_calendar(name, component, d) if counted: - assert d is not None # refused without one - operating[name] = d + if isinstance(d, PlannedLife): + clocks[name] = d + else: + operating[name] = 1.0 if d is None else d out[name] = component - return out, operating + return out, operating, clocks def _is_junction(name, component) -> bool: @@ -1114,6 +1263,12 @@ def add(path: tuple, kind: int, sampler, expected: float) -> None: if scheduled(component) is not None: # Uniforms, which its stand-in inverts along the schedule. failure = _uniforms + upgrade = rbd._upgrades.get(name) + if upgrade is not None: + # Uniforms, which its stand-in turns into lives by the + # life in service (see _UpgradedComponent). + old_and_new = (failure, stream_sampler(upgrade.life)) + failure = None if None in old_and_new else _uniforms repair = stream_sampler(component.time_to_replace) if failure is None or repair is None: complete = False @@ -1311,6 +1466,10 @@ def _streamed_components( component, run, prefix + (name,), arrangement ) ) + if name in rbd._upgrades: + made[id(component)] = _upgraded( + rbd, name, run, prefix + (name,) + ) own = _ccf_groups._own_rate(rbd, name) if own is not None and made[id(component)] is component: # Not streamed: its own cause's life all the same. @@ -1710,7 +1869,12 @@ def _start_queue( # may need one (with enough, no job ever waits). crews = rbd.repair_crews rbd._run_state._crews = ( - _Crews(crews, _crews._crew_served(rbd), rbd._priority) + _Crews( + crews, + _crews._crew_served(rbd), + rbd._priority, + _crews._call_when(rbd), + ) if crews is not None and _crews._crews_limited(rbd) else None ) @@ -1996,7 +2160,16 @@ def _crew_follow_up(rbd, event: Event, next_event: Event) -> Optional[Event]: _crew_started(rbd, started) return next_event if next_event.status: - return crews.request(node, event.time, next_event) + ends = crews.request(node, event.time, next_event) + if ends is None and crews.call_when: + # The job waits: the call-out crew may come for the first + # waiting job (this one, perhaps, which then never waited). + started = crews.call(event.time) + if started is not None and started[0] == node: + return started[2] + if started is not None: + _crew_started(rbd, started) + return ends return next_event @@ -2046,6 +2219,10 @@ def _maintained_follow_up( source.reset() if not event.status: # Down for maintenance: back, as new, once it is done. + if schedule.shuts is not None: + # At several shutdowns: the length of the one starting now. + fixed = schedule.duration_at(t) + return Event(t + float(fixed.params[0]), node, True, True) if isinstance(source, _StreamedComponent): duration = source.maintenance_time() else: @@ -2127,9 +2304,10 @@ def _renewal( else: # Maintenance that takes time is a planned outage; in zero time # the unit is renewed in place, and stays up. - event = Event(due, node, schedule.duration is None, True) - if node in rbd._early_members: - # Kept, should a stop of its group renew it early (see _stop). + event = Event(due, node, schedule.duration_at(due) is None, True) + if node in rbd._early_members or node in rbd._outage_members: + # Kept, should a stop of its group, or a shutdown, renew it early + # (see _stop and _outage_renewals). rbd._run_state._renewed_at[node] = start rbd._run_state._pending_event[node] = event return event @@ -2160,6 +2338,7 @@ def _own_sources(rbd, states: Optional[dict] = None) -> dict: and not starting and not rbd.ccf_groups and not timed + and not rbd._upgrades ): return rbd.components sources = dict(rbd.components) @@ -2185,9 +2364,15 @@ def _own_sources(rbd, states: Optional[dict] = None) -> dict: model=_duration_model(rbd, node), restoration=rbd._restoring.get(node), ) + for node in rbd._upgrades: + sources[node] = _upgraded(rbd, node) for node in starting: - if node in timed or _ccf_groups._own_rate(rbd, node) is not None: - continue # its schedule's, or its own cause's, draws above + if ( + node in timed + or node in rbd._upgrades + or _ccf_groups._own_rate(rbd, node) is not None + ): + continue # its schedule's, upgrade's or own cause's draws component = rbd.components[node] sources[node] = _StreamedComponent( _ModelDraws(component.reliability), @@ -2239,6 +2424,39 @@ def _stop(rbd, group, t: float, trigger=None) -> List[Event]: return out +def _outage_renewals(rbd, rules: tuple, t: float) -> List[Event]: + """At the start of a shutdown at ``t``, the components of ``rules`` + (each with its age) renewed opportunistically: each that is working + and at least that old (the time since it was put in), renewed now as + its age replacement would renew it, at its cost and in its time; the + failure or replacement it had ahead of it is cancelled, as at a stop + of a maintenance group (``_stop``). One whose own failure or + replacement is due at ``t``, or that is being renewed, keeps it. + Returns the renewals to queue.""" + run = rbd._run_state + out: List[Event] = [] + for member, age in rules: + if ( + member not in run._renewed_at + or member in run._renewing + or not run.component_status[member] + or t - run._renewed_at[member] < age + ): + continue + pending = run._pending_event.get(member) + if pending is not None and pending.time <= t: + continue # due now + run._pending_event.pop(member, None) + if pending is not None and pending.time < run.t_simulation: + run._cancelled[id(pending)] = pending + schedule = rbd._preventive[member] + renewal = Event(t, member, schedule.duration is None, True) + run._early[id(renewal)] = renewal + run._renewing.add(member) + out.append(renewal) + return out + + def _replaced_at( rbd, node, @@ -2662,9 +2880,13 @@ def _run_alone( ), jobs, ) + # The crews' salaries, the same in every simulation: charged here, + # on every engine (a sharded run's shards charge their own). + salaries = 0.0 if sharded is not None else _crew_salaries(rbd) start, goal = first, first + N while True: runner(start, goal) + tally.charge_crews(goal - start, salaries * t_simulation) more = 0 if stop is None else stop(tally) if not more: break @@ -2752,6 +2974,13 @@ def _replicate(rbd, ctx: "_Context", replication: int) -> _Replication: maintenance, member_group = rbd._maintenance, rbd._member_group cancelled, early = rbd._run_state._cancelled, rbd._run_state._early opportunistic = [0] * n + # The renewals made at each start of a shutdown that renews components + # opportunistically (see outage_starts). + outage_jobs = ( + [0] * len(outage_starts(rbd, ctx.t_simulation)) + if rbd._outage_members + else None + ) failures = restorations = planned = 0 changes: list = [] deltas: list = [] @@ -2779,11 +3008,17 @@ def pay(node, category: int, charges) -> float: # among its changes) were planned changes down, maintenance or a # test off line; and the system's changes: their times, the # component whose change made each, which of its changes that was, - # and whether it was planned. + # and whether it was planned. With shutdowns, also which of each + # component's planned changes were a shut's holds (places among its + # changes, as planned_of), and the changes down its hold hid, each + # charged: their times and whether planned (see _npv_runs). history = ctx.history at_start = [view[node] for node in index] if history else None times_of: list = [[] for _ in range(n)] if history else [] planned_of: list = [[] for _ in range(n)] if history else [] + shut_record = bool(history) and bool(rbd._shutdowns) + held_of: list = [[] for _ in range(n)] if shut_record else [] + hidden_of: list = [[] for _ in range(n)] if shut_record else [] system_record: tuple = ([], [], [], []) if history else () # The system's state, and its up and down time until ``since``, its # last change; each component's last change, and the system's up and @@ -2892,6 +3127,7 @@ def stop(group, t: float, trigger=None) -> float: times_of[c].append(t) if not event.status: planned_of[c].append(len(times_of[c]) - 1) + held_of[c].append(len(times_of[c]) - 1) if not event.status: # Charged at its start; its paused nodes stand still. if node.cost: @@ -2901,6 +3137,12 @@ def stop(group, t: float, trigger=None) -> float: moved = _shifted(rbd, member, t, node.duration) if moved is not None: push(heap, (moved.time, moved)) + if node.opportunistic: + renewals = _outage_renewals(rbd, node.opportunistic, t) + assert outage_jobs is not None # it has rules + outage_jobs[node.places[t]] += len(renewals) + for renewal in renewals: + push(heap, (renewal.time, renewal)) if changed is not None and works(view) != up: system_up, system_down, since = system_up_t, system_down_t, t up = not up @@ -3003,6 +3245,11 @@ def stop(group, t: float, trigger=None) -> float: times_of[c].append(t) if not event.status and (event.preventive or event.inspection): planned_of[c].append(len(times_of[c]) - 1) + elif shut_record and not event.status: + # A change down a shut's hold hides, charged all the same. + hidden_of[c].append( + (t, bool(event.preventive or event.inspection)) + ) if event.status: restored[c] += 1 elif event.preventive: @@ -3122,6 +3369,19 @@ def stop(group, t: float, trigger=None) -> float: charge = rbd.downtime_cost_rate * (t_simulation - system_up) rep_cost += charge by_category[5] += charge + for node, upgrade in rbd._upgrades.items(): + # An upgrade's capital cost, at its time, in every simulation + # that reaches it. + if upgrade.cost and upgrade.at < t_simulation: + rep_cost += upgrade.cost + by_category[_CAPITAL] += upgrade.cost + by_node[node] += upgrade.cost + if crews is not None and crews.call_when: + # The call-out crew: its fee each time it came, and its rate + # while it was engaged (see _Crews). + charge = _crews._call_out_charge(rbd, *crews.close(t_simulation)) + rep_cost += charge + by_category[_CREWS] += charge rec = _Replication() rec.uptime = system_up @@ -3136,8 +3396,17 @@ def stop(group, t: float, trigger=None) -> float: rec.capacity_changes = rec.capacity_time = rec.delivered = None rec.replacements = replaced rec.opportunistic = opportunistic + rec.outage_jobs = outage_jobs rec.history = ( - (at_start, times_of, planned_of, started_up, system_record) + ( + at_start, + times_of, + planned_of, + started_up, + system_record, + held_of if shut_record else None, + hidden_of if shut_record else None, + ) if history else None ) diff --git a/repyability/rbd/_events.py b/repyability/rbd/_events.py index 600b773e..8449b2f5 100644 --- a/repyability/rbd/_events.py +++ b/repyability/rbd/_events.py @@ -257,6 +257,12 @@ def _repair(self, unit: int, t: float) -> None: _Unit(self._node, unit), t, Event(ends, None, True) ): self._queue(ends, _UNIT_REPAIRED, unit) + elif crews.call_when: + from . import _event_loop + + started = crews.call(t) + if started is not None: + _event_loop._crew_started(self._rbd, started) def crew_started(self, unit: int, ends: float) -> None: """A crew has started unit ``unit``'s repair late: it ends at @@ -343,11 +349,33 @@ class _Crews: the highest priority, and of those the one that fell due first. The job's length was drawn when it fell due, so waiting shifts the component's restoration without changing its draws. + + With a call-out crew (``call_when`` waiting jobs call it, a + ``RepairableRBD``'s ``call_out``): a job that makes that many wait + brings it, and it starts the first of them at once (``call``). While + it is engaged there is a crew more; it leaves at the first end of a + job that leaves a crew with no waiting job to take (``release``): the + crews are alike, so whichever job it has then is finished by the crew + that came free. ``calls`` counts its call-outs and ``engaged_time`` + its time engaged, which ``close`` ends at the end of the window. The + crews' Markov chain copies this (``_crew_chain._enumerate``). """ - __slots__ = ("free", "served", "holding", "waiting", "_order", "_rank") + __slots__ = ( + "free", + "served", + "holding", + "waiting", + "_order", + "_rank", + "call_when", + "engaged", + "calls", + "engaged_time", + "_since", + ) - def __init__(self, crews: int, served, priority: dict): + def __init__(self, crews: int, served, priority: dict, call_when: int = 0): self.free = crews self.served = frozenset(served) self.holding: set = set() @@ -360,10 +388,16 @@ def __init__(self, crews: int, served, priority: dict): ) for key in served } + self.call_when = call_when + self.engaged = False + self.calls = 0 + self.engaged_time = 0.0 + self._since = 0.0 def request(self, node, due: float, done: "Event") -> Optional["Event"]: """``node``'s job, due at ``due`` and ending with ``done`` if a crew - starts it at once: ``done``, or None while the job waits.""" + starts it at once: ``done``, or None while the job waits (with a + call-out crew, ``call`` then says whether it comes).""" if self.free: self.free -= 1 self.holding.add(node) @@ -373,14 +407,38 @@ def request(self, node, due: float, done: "Event") -> Optional["Event"]: self._order += 1 return None + def call(self, t: float) -> Optional[Tuple[Any, float, "Event"]]: + """A job has had to wait at ``t``: if that makes ``call_when`` of + them and the call-out crew is not engaged, it comes and starts + the first (as ``release`` gives it); or None.""" + if ( + not self.call_when + or self.engaged + or len(self.waiting) < self.call_when + ): + return None + self.engaged = True + self.calls += 1 + self._since = t + return self._start(t) + def release(self, node, t: float) -> Optional[Tuple[Any, float, "Event"]]: """``node``'s job is done at ``t``: its crew starts the next waiting job, if any. That job's component, how long it waited, and the event - that now ends it; or None.""" + that now ends it; or None, and the call-out crew, if engaged, + leaves in its place.""" self.holding.discard(node) - if not self.waiting: + if self.waiting: + return self._start(t) + if self.engaged: + self.engaged = False + self.engaged_time += t - self._since + else: self.free += 1 - return None + return None + + def _start(self, t: float) -> Tuple[Any, float, "Event"]: + """A crew starts the first waiting job at ``t``.""" _, due, _, waiting, done = heapq.heappop(self.waiting) self.holding.add(waiting) wait = t - due @@ -393,6 +451,13 @@ def release(self, node, t: float) -> Optional[Tuple[Any, float, "Event"]]: ) return waiting, wait, ends + def close(self, t: float) -> Tuple[int, float]: + """The call-out crew's call-outs and its time engaged by ``t``, + the end of the window.""" + if self.engaged: + return self.calls, self.engaged_time + (t - self._since) + return self.calls, self.engaged_time + class _Fixed: """A cost charged at the same amount every time.""" @@ -594,20 +659,61 @@ class _Preventive(NamedTuple): #: which the unit is replaced there, in place of the ``threshold``; #: None for none. older_than: Optional[float] = None - #: At a shutdown's given times (sorted, from 0) rather than every - #: ``interval``: those times; None for a period. + #: At given times (sorted, from 0) rather than every ``interval``: a + #: shutdown's, or the component's own plan (``"replace_at"``); None + #: for a period. times: Optional[Tuple[float, ...]] = None #: The name of the shutdown the actions are done at; None for none. + #: At several shutdowns, their names (a tuple), with ``shuts``. shutdown: Any = None + #: At several shutdowns (block replacement at each of their starts): + #: each ``_Shutdown`` with the model of the time its renewal takes + #: there (its own duration; None for none). ``interval`` is then the + #: shortest of theirs and ``duration`` the longest, which only size + #: the simulation's streams; None at one shutdown or none. + shuts: Optional[Tuple[Tuple[Any, Any], ...]] = None + #: Under ``"block"`` on its own interval, for an upgraded component + #: (see ``_Upgrade``): the upgrade's time, at which the unit is + #: replaced as at a block time (at its cost and in its time); None + #: for none. + upgrade_at: Optional[float] = None + + #: Counted in operating time on a duty plan that changes over time + #: (a ``_duty.PlannedLife``, the block's life): each action falls when + #: the plan's operating time reaches the time it is due at in + #: operating time; None on the diagram's clock. + clock: Any = None + + @property + def plan(self) -> Optional[Tuple[float, ...]]: + """The component's own list of replacement times + (``"replace_at"``), after the last of which it is replaced no + more; None on a period, or at a shutdown's times.""" + return self.times if self.shutdown is None else None def due(self, renewed: float) -> float: """When the next preventive action (under ``"condition"``, the next inspection) falls, for a unit put into service as new at - ``renewed``, or inspected then.""" + ``renewed``, or inspected then; an upgrade's time (``upgrade_at``) + is one such action.""" + if self.clock is not None: + # In operating time, and back on the diagram's clock. + clock = self.clock + due = clock.inverse(self._due(clock.operating(renewed))) + else: + due = self._due(renewed) + if self.upgrade_at is not None and renewed < self.upgrade_at: + return min(due, self.upgrade_at) + return due + + def _due(self, renewed: float) -> float: if self.policy == "age": return renewed + self.interval if self.policy == "calendar": return self.calendar._next_planned(renewed, renewed)[0] + if self.shuts is not None: + # The first start of any of its shutdowns after ``renewed``. + return min(shut.due(renewed) for shut, _ in self.shuts) if self.times is not None: return _next_time(self.times, renewed) if self.offset or self.shutdown is not None: @@ -624,6 +730,29 @@ def due(self, renewed: float) -> float: due = float(np.floor(renewed / self.interval) + 1.0) * self.interval return due if due > renewed else due + self.interval + def duration_at(self, t: float): + """The model of the time the preventive action due at ``t`` takes + (None for none): at several shutdowns, that of the one starting + at ``t``; else ``duration``.""" + if self.shuts is None: + return self.duration + before = float(np.nextafter(t, -np.inf)) + for shut, model in self.shuts: + if shut.due(before) == t: + return model + return self.duration + + +class _Upgrade(NamedTuple): + """A component's upgrade (its spec's ``"upgrade"``): at the time + ``at`` the unit in service is replaced, in no time, by one of the life + ``life``, as is every unit put into service after it, for the capital + cost ``cost``, charged then.""" + + at: float + life: Any + cost: float + class _Imperfect(NamedTuple): """A component's imperfect repair (#109): ``kijima`` (``"kijima1"`` or @@ -644,9 +773,11 @@ class _Restoration(NamedTuple): """A component's preventive maintenance that restores it only partly (a ``"preventive"`` spec's ``"restoration"``): ``kijima`` (``"kijima1"`` or ``"kijima2"``) and its restoration factor ``q`` (0 - as new, 1 as bad as old), and the task, counting from the unit's last - renewal, that replaces it as new instead (``"replace_every"``; None - for never).""" + as new, 1 as bad as old, above 1 older than it was), or + ``"to_age"`` and the virtual age ``q`` every task leaves the unit at + (``"restore_to"``); and the task, + counting from the unit's last renewal, that replaces it as new + instead (``"replace_every"``; None for never).""" kijima: str q: float @@ -758,7 +889,8 @@ class _Shutdown(NamedTuple): lasts, ``duration``; the nodes it holds off line (``scope``, None for the whole system); its ``cost``, charged at each; and whether the blocks in its scope not worked on keep ageing through it - (``idle_ageing``) or stand still until it ends.""" + (``idle_ageing``) or stand still until it ends; and the components + it renews if they are old enough (``opportunistic``).""" name: Any #: A float, or None at given times. @@ -769,6 +901,10 @@ class _Shutdown(NamedTuple): scope: Optional[Tuple[Any, ...]] cost: float idle_ageing: bool + #: The components renewed at each start if old enough: ``{node: + #: age}``, a number for every component in the scope under age + #: replacement, or None (resolved by ``_shutdowns.check``). + opportunistic: Any = None @property def periodic(self) -> bool: diff --git a/repyability/rbd/_first_failure.py b/repyability/rbd/_first_failure.py index 2f6a6106..b9fd3227 100644 --- a/repyability/rbd/_first_failure.py +++ b/repyability/rbd/_first_failure.py @@ -34,7 +34,7 @@ import numpy as np from repyability.rbd import _crew_chain as crew_chain -from repyability.rbd import _curves, _overrides, _requirements +from repyability.rbd import _crews, _curves, _overrides, _requirements from repyability.rbd._common import _constant_rate, _repair_rate from repyability.rbd._mean_lifetime import mean_lifetime, model_knots from repyability.rbd.modular import NODE, SERIES, GraphStructure @@ -145,11 +145,13 @@ def _markov_rates(rbd) -> Tuple[Dict[Any, Tuple[float, float]], int]: [rbd._priority.get(node, 0.0) for node in rates], [math.isinf(repair) for _, repair in rates.values()], crews, + _crews._call_when(rbd), ) if count > crew_chain.MAX_STATES: + # (With a call-out crew, the states are counted only that far.) _refuse( - f"Its Markov chain has {count:,} states, more than the " - f"{crew_chain.MAX_STATES:,} it is solved for" + "Its Markov chain has more than the " + f"{crew_chain.MAX_STATES:,} states it is solved for" ) return rates, crews @@ -256,6 +258,7 @@ def __init__(self, rbd, states: dict): [rates[node][1] for node in nodes], [rbd._priority.get(node, 0.0) for node in nodes], crews, + _crews._call_when(rbd), ) structure = rbd._decomposition() size = len(chain.probabilities) diff --git a/repyability/rbd/_intervals.py b/repyability/rbd/_intervals.py index 23bca0a7..30d35b0c 100644 --- a/repyability/rbd/_intervals.py +++ b/repyability/rbd/_intervals.py @@ -7,8 +7,10 @@ names call these. """ +import dataclasses import itertools import math +from functools import partial from typing import ( TYPE_CHECKING, Callable, @@ -21,14 +23,17 @@ import numpy as np from scipy.optimize import minimize -from repyability.rbd import _crews, _requirements +from repyability.rbd import _crews, _discounted_long_run, _requirements +from repyability.rbd._common import _crew_salaries, _discount_rate from repyability.rbd._model_utils import ( failure_time_scale, ) from repyability.rbd.results import ( MaintenancePlan, + PlanRobustness, ) from repyability.rbd.routes import Refused +from repyability.utils import checks if TYPE_CHECKING: from repyability.rbd.repairable_rbd import RepairableRBD @@ -53,6 +58,152 @@ def _objective(cost: float, availability: float, max_cost_rate) -> float: return 1.0 - availability if max_cost_rate is not None else cost +#: What an interval choice can minimise. +OBJECTIVES = ("cost", "eac", "npv") + + +class _Goal: + """What an interval choice minimises in place of the long-run cost + rate (``objective`` ``"eac"`` or ``"npv"``): the equivalent annual + cost at a discount rate, less the value earned, or less the expected + net present value over a horizon. A lower ``score`` is better.""" + + def __init__( + self, objective: str, rate: float, value_rate: float, horizon + ): + self.objective = objective + self.rate = rate + self.value_rate = value_rate + self.horizon = horizon + #: Each component's own equivalent annual cost, by its schedule. + self._own: dict = {} + + def eac(self, plan, cost: float, availability: float) -> float: + """``plan``'s equivalent annual cost less the value it earns, + from its long-run ``cost`` rate and ``availability``: at rate 0, + those themselves.""" + if self.rate == 0.0: + return cost - self.value_rate * availability + own = 0.0 + for node in plan.costs: + key = ( + node, + plan._preventive.get(node), + plan._inspection.get(node), + ) + if key not in self._own: + self._own[key] = _discounted_long_run.node_eac( + plan, node, self.rate + ) + own += self._own[key] + return own + _discounted_long_run.system_terms( + plan, availability, self.value_rate + ) + + def less_npv(self, plan) -> float: + """Less ``plan``'s expected net present value over the horizon.""" + return -plan.expected_npv( + self.horizon, + discount_rate=self.rate, + value_rate=self.value_rate, + ).npv + + def achieved(self, score: float, salaries: float = 0.0) -> float: + """The objective's value at a ``score``: the equivalent annual + cost, or the net present value; with the repair crews' + ``salaries`` per unit time, left out of the score, paid.""" + if self.objective == "npv": + span = ( + -math.expm1(-self.rate * self.horizon) / self.rate + if self.rate + else self.horizon + ) + return -score - salaries * span + return score + salaries + + def basis(self, rbd) -> str: + """What the value achieved is made of, and what is approximate + in it: said on the plan.""" + if self.objective == "npv": + return ( + "The expected net present value over the horizon, from " + "new: expected_npv." + ) + return _discounted_long_run.basis(rbd, self.rate, self.value_rate) + + +def _goal(rbd, objective, discount_rate, value_rate, horizon): + """The checked goal of an interval choice (see ``_Goal``); None for + the long-run cost rate, ``"cost"``.""" + checks.one_of("objective", objective, OBJECTIVES) + rate = _discount_rate(discount_rate) + worth = checks.number_or_nan(value_rate) + if not (math.isfinite(worth) and worth >= 0.0): + raise ValueError( + "value_rate must be a finite number, at least 0 (the value " + f"earned per unit time while the system works); got " + f"{value_rate!r}." + ) + if objective == "cost": + given = [ + name + for name, value in ( + ("discount_rate", rate), + ("value_rate", worth), + ("horizon", horizon), + ) + if value + ] + if given: + raise ValueError( + f"{' and '.join(given)} need{'s' if len(given) == 1 else ''}" + ' an objective that takes them: objective="eac" (the ' + 'equivalent annual cost in the long run) or objective="npv"' + " (the expected net present value over a horizon)." + ) + return None + if objective == "npv": + length = checks.number_or_nan(horizon) if horizon is not None else 0.0 + if not (math.isfinite(length) and length > 0.0): + raise ValueError( + 'objective="npv" is over a horizon: give horizon, a ' + f"finite time more than 0; got {horizon!r}." + ) + return _Goal(objective, rate, worth, float(length)) + if horizon is not None: + raise ValueError( + 'objective="eac" is the long run, with no horizon: leave ' + 'horizon out, or give objective="npv" for the net present ' + "value over it." + ) + if rate: + _discounted_long_run.require_discounted(rbd) + return _Goal(objective, rate, worth, None) + + +def _long_run_goal(rbd, goal: _Goal) -> Optional[_Goal]: + """The long-run goal nearest to a net present value's: the + equivalent annual cost at its rates where the diagram has one worked + out, else the cost rate (None).""" + try: + return _goal(rbd, "eac", goal.rate, goal.value_rate, None) + except NotImplementedError: + return None + + +def _scorer(goal: Optional[_Goal], evaluate, planned, over_time=None): + """What an interval choice minimises for ``goal``, as a function of + the intervals (None for the cost rate): ``planned(intervals)`` gives + the diagram with them for the long run, ``over_time(intervals)`` for + its curves from new (the same by default).""" + if goal is None: + return None + if goal.objective == "npv": + build = planned if over_time is None else over_time + return lambda intervals: goal.less_npv(build(intervals)) + return lambda intervals: goal.eac(planned(intervals), *evaluate(intervals)) + + def _meets(cost, availability, min_availability, max_cost_rate) -> bool: """Whether long-run values meet an interval choice's target.""" if min_availability is not None and availability < min_availability: @@ -69,17 +220,26 @@ def _choose_intervals( bounds: Tuple[np.ndarray, np.ndarray], min_availability: Optional[float], max_cost_rate: Optional[float], + score=None, + quadrature: bool = False, ) -> dict: """The intervals (by node) that minimise the cost rate, or, with a cost cap, the unavailability, subject to the target: SLSQP over the logarithms of the intervals from each of ``starts``, keeping the best that meets the target. ``evaluate(intervals)`` gives their exact - ``(cost rate, availability)``. A ValueError if no intervals in - ``bounds`` meet the target, giving the best they can do.""" + ``(cost rate, availability)``. With ``score`` (see ``_scorer``), they + minimise ``score(intervals)`` instead, subject to the same target; + one worked out by ``quadrature`` (a net present value over a + horizon, known to about 1e-8 of itself and with a kink wherever a + replacement falls on the horizon) is searched without its gradient + (COBYLA), from steps of a tenth of an interval down to 1e-4 of it. + A ValueError if no intervals in ``bounds`` meet the target, giving + the best they can do.""" low, high = bounds box = list(zip(low, high)) options = {"ftol": 1e-10, "maxiter": 200, "eps": 1e-6} cache: dict = {} + scores: dict = {} def point(x) -> tuple: """``x`` rounded: the intervals evaluated, and returned.""" @@ -104,6 +264,22 @@ def unavailable(x): def cost(x): return values(x)[0] / rate0 + def scored(x) -> float: + """What is minimised at ``x``, unscaled.""" + if score is None: + return _objective(*values(x), max_cost_rate) + key = point(x) + if key not in scores: + scores[key] = score( + {node: math.exp(xi) for node, xi in zip(nodes, key)} + ) + return scores[key] + + score0 = max(abs(scored(high)), 1e-300) if score is not None else 1.0 + + def given(x): + return scored(x) / score0 + if max_cost_rate is not None: objective = unavailable @@ -121,6 +297,8 @@ def slack(x): 1.0 - min_availability ) + if score is not None: + objective = given constrained = min_availability is not None or max_cost_rate is not None if constrained and not any( _meets(*values(start), min_availability, max_cost_rate) @@ -152,22 +330,38 @@ def slack(x): ) starts = [reach] + list(starts) best, best_value = None, math.inf + limits = [{"type": "ineq", "fun": slack}] if constrained else [] for start in starts: - found = minimize( - objective, - start, - method="SLSQP", - bounds=box, - constraints=( - [{"type": "ineq", "fun": slack}] if constrained else [] - ), - options=options, - ) + if quadrature: + inside = [ + {"type": "ineq", "fun": lambda x, i=i: x[i] - low[i]} + for i in range(len(nodes)) + ] + [ + {"type": "ineq", "fun": lambda x, i=i: high[i] - x[i]} + for i in range(len(nodes)) + ] + found = minimize( + objective, + start, + method="COBYLA", + constraints=limits + inside, + options={"rhobeg": 0.1, "tol": 1e-4, "maxiter": 200}, + ) + found.x = np.clip(found.x, low, high) + else: + found = minimize( + objective, + start, + method="SLSQP", + bounds=box, + constraints=limits, + options=options, + ) for x in (found.x, start): rate, availability = values(x) if not _meets(rate, availability, min_availability, max_cost_rate): continue - value = _objective(rate, availability, max_cost_rate) + value = scored(x) if value < best_value: best, best_value = np.asarray(x, dtype=float), value assert best is not None # the start that meets the target is kept @@ -224,6 +418,7 @@ def _choose_divisor( evaluate, min_availability: Optional[float], max_cost_rate: Optional[float], + score=None, ) -> dict: """The interval of a component whose tests can miss a failure (#221), from those that divide its full tests' interval ``full`` (``full / @@ -237,7 +432,7 @@ def _choose_divisor( def best_of(ks) -> int: options = {node: tuple(full / k for k in ks)} chosen = _choose_from( - [node], options, evaluate, min_availability, max_cost_rate + [node], options, evaluate, min_availability, max_cost_rate, score ) return int(round(full / chosen[node])) @@ -258,6 +453,7 @@ def _choose_from( evaluate, min_availability: Optional[float], max_cost_rate: Optional[float], + score=None, ) -> dict: """The intervals, each from its node's ``options``, that minimise the cost rate, or with a cost cap the unavailability, subject to the target: @@ -265,8 +461,10 @@ def _choose_from( interval changed at a time, from several starts) otherwise. Of plans that cost the same, the most available is chosen (and of those as available, the cheapest): tests' offsets change no cost. Of plans as - good (``_AS_GOOD``), the first tried is kept. A ValueError if none - meets the target, giving the best any does.""" + good (``_AS_GOOD``), the first tried is kept. With ``score`` (see + ``_scorer``), the lowest ``score(intervals)`` is chosen first, of the + plans that meet the target. A ValueError if none meets the target, + giving the best any does.""" def merit(intervals: dict) -> tuple: """(How far from the target, the objective, the other one), each @@ -281,6 +479,9 @@ def merit(intervals: dict) -> tuple: else: short = (0.0, 1.0) down = (1.0 - availability, 1.0) + if score is not None: + scored = score(intervals) + return short, (scored, abs(scored)), (cost, priced), down if max_cost_rate is None: return short, (cost, priced), down return short, down, (cost, priced) @@ -415,8 +616,17 @@ def optimal_replacement_intervals( min_availability: Optional[float], max_cost_rate: Optional[float], assume_unlimited_crews: bool, + objective: str, + discount_rate: float, + value_rate: float, + horizon, + robust=False, + uncertainty=None, + n_draws: int = 200, + seed=None, ) -> MaintenancePlan: """See ``RepairableRBD.optimal_replacement_intervals``.""" + robust = _robust_method(robust) chosen = _maintained(rbd, nodes) min_availability, max_cost_rate = _interval_targets( rbd, min_availability, max_cost_rate @@ -424,17 +634,24 @@ def optimal_replacement_intervals( if rbd._crews_couple(): if not assume_unlimited_crews: _require_interval_crews(rbd) - return _unlimited_crews(rbd).optimal_replacement_intervals( + salaries = _crew_salaries(rbd) + plan = _unlimited_crews(rbd).optimal_replacement_intervals( chosen, allowed=allowed, min_availability=min_availability, - max_cost_rate=max_cost_rate, + max_cost_rate=_less_salaries(max_cost_rate, salaries), + objective=objective, + discount_rate=discount_rate, + value_rate=value_rate, + horizon=horizon, + robust=robust, + uncertainty=uncertainty, + n_draws=n_draws, + seed=seed, ) - - def evaluate(intervals: dict) -> Tuple[float, float]: - plan = _with_intervals(rbd, preventive=intervals) - return plan.expected_cost_rate(), plan.mean_availability() - + return _with_salaries(plan, salaries) + goal = _goal(rbd, objective, discount_rate, value_rate, horizon) + planned, evaluate, score = _replacement_scoring(rbd, goal) if allowed is not None: best = _choose_from( chosen, @@ -442,14 +659,268 @@ def evaluate(intervals: dict) -> Tuple[float, float]: evaluate, min_availability, max_cost_rate, + score, ) else: + near = None + if goal is not None and goal.objective == "npv": + # A net present value takes its curves over the horizon at + # each plan: searched from the long run's best plan. + near = _searched_replacements( + rbd, + chosen, + evaluate, + min_availability, + max_cost_rate, + _scorer(_long_run_goal(rbd, goal), evaluate, planned), + ) best = _searched_replacements( - rbd, chosen, evaluate, min_availability, max_cost_rate + rbd, + chosen, + evaluate, + min_availability, + max_cost_rate, + score, + near, ) cost, availability = evaluate(best) + plan = _planned( + rbd, + {node: float(best[node]) for node in chosen}, + cost, + availability, + goal, + score, + best, + ) + if not robust: + return plan + options = ( + None + if allowed is None + else _allowed_intervals(allowed, chosen, never=True) + ) + + def again(diagram) -> dict: + """The draw's own best intervals.""" + return dict( + optimal_replacement_intervals( + diagram, + chosen, + allowed=allowed, + min_availability=min_availability, + max_cost_rate=max_cost_rate, + assume_unlimited_crews=assume_unlimited_crews, + objective=objective, + discount_rate=discount_rate, + value_rate=value_rate, + horizon=horizon, + ).intervals + ) + + return dataclasses.replace( + plan, + robustness=_robustness( + rbd, + {node: float(best[node]) for node in chosen}, + options, + (objective, discount_rate, value_rate, horizon), + (min_availability, max_cost_rate), + robust, + again, + uncertainty, + n_draws, + seed, + ), + ) + + +def _replacement_scoring(rbd, goal): + """For a choice of age-replacement intervals on ``rbd``: the plan + with given intervals (for the long run), its long-run cost rate and + availability, and the score of ``goal`` (None for the cost rate).""" + + def planned(intervals: dict) -> "RepairableRBD": + return _with_intervals(rbd, preventive=intervals) + + def over_time(intervals: dict) -> "RepairableRBD": + """The plan for its curves from new: a component never replaced + has no schedule there.""" + never = [node for node in intervals if math.isinf(intervals[node])] + if not never: + return planned(intervals) + return _with_intervals( + with_intervals(rbd, dict.fromkeys(never, math.inf), None), + preventive={ + node: interval + for node, interval in intervals.items() + if node not in never + }, + ) + + def evaluate(intervals: dict) -> Tuple[float, float]: + plan = planned(intervals) + return plan.expected_cost_rate(), plan.mean_availability() + + return planned, evaluate, _scorer(goal, evaluate, planned, over_time) + + +#: How robust a choice is, by ``robust``'s values (see ``_robustness``). +ROBUST = { + True: "neighbours", + "neighbours": "neighbours", + "reoptimise": "reoptimise", +} + +#: How far a neighbour of a continuously searched interval is: this many +#: times longer, or shorter. +NEIGHBOUR_STEP = 1.25 + + +def _robust_method(robust): + """``robust`` checked: False, or the method's name.""" + if robust is False or robust is None: + return False + if isinstance(robust, (bool, str)) and robust in ROBUST: + return ROBUST[robust] + raise ValueError( + "robust must be False, True (the choice against its neighbours " + 'under each draw) or "reoptimise" (against each draw\'s own best ' + f"intervals, slower); got {robust!r}." + ) + + +def _neighbours(best: dict, options: Optional[dict]) -> list: + """The choice and its neighbours: each interval one step either way, + the next of its ``options``, or ``NEIGHBOUR_STEP`` times longer or + shorter (an interval of never has none).""" + out = [dict(best)] + for node, interval in best.items(): + if options is not None: + values = options[node] + k = values.index(interval) + moved = [values[j] for j in (k - 1, k + 1) if 0 <= j < len(values)] + elif math.isfinite(interval): + moved = [interval / NEIGHBOUR_STEP, interval * NEIGHBOUR_STEP] + else: + moved = [] + out.extend({**best, node: value} for value in moved) + return out + + +def _robustness( + rbd, + best: dict, + options: Optional[dict], + objective: tuple, + targets: tuple, + method: str, + again, + uncertainty, + n_draws: int, + seed, +) -> PlanRobustness: + """How the choice ``best`` fares under draws of the uncertain models + (see ``PlanRobustness``): every candidate scored under each draw's + diagram by the choice's own objective and targets, with the same + draws for every candidate; or, with ``"reoptimise"``, against each + draw's own best intervals (``again(diagram)``).""" + from repyability.rbd import _repairable_uncertainty as drawn + + min_availability, max_cost_rate = targets + inputs, groups = drawn.sources(rbd, uncertainty) + models, group_models = drawn.draws(rbd, inputs, groups, n_draws, seed) + candidates = ( + [best] if method == "reoptimise" else _neighbours(best, options) + ) + choices: Optional[list] = [] if method == "reoptimise" else None + scores = np.empty((n_draws, len(candidates))) + meets = np.empty((n_draws, len(candidates)), dtype=bool) + regret = np.empty(n_draws) + for i in range(n_draws): + diagram = drawn.build(rbd, inputs, models, group_models, i) + _, evaluate, score = _replacement_scoring( + diagram, _goal(diagram, *objective) + ) + + def scored(intervals: dict) -> Tuple[float, bool]: + cost, availability = evaluate(intervals) + ok = _meets(cost, availability, min_availability, max_cost_rate) + if score is not None: + return score(intervals), ok + return _objective(cost, availability, max_cost_rate), ok + + for k, candidate in enumerate(candidates): + scores[i, k], meets[i, k] = scored(candidate) + if choices is not None: + try: + own = again(diagram) + except ValueError: + # No intervals meet the target under this draw. + own = None + choices.append(own) + regret[i] = ( + np.nan if own is None else scores[i, 0] - scored(own)[0] + ) + else: + feasible = np.where(meets[i], scores[i], np.inf) + low = float(feasible.min()) + regret[i] = scores[i, 0] - low if math.isfinite(low) else np.nan + if choices is not None: + share_best = ( + None + if options is None + else float(np.mean([own == best for own in choices])) + ) + by_candidate: list = [] + else: + feasible = np.where(meets, scores, np.inf) + winner = np.argmin(feasible, axis=1) + has = np.isfinite(feasible.min(axis=1)) + by_candidate = [ + float(np.mean(has & (winner == k))) for k in range(len(candidates)) + ] + # The choice is best where nothing that meets the target scores + # lower: ties count for it. + share_best = float( + np.mean(meets[:, 0] & (scores[:, 0] <= feasible.min(axis=1))) + ) + known = regret[np.isfinite(regret)] + return PlanRobustness( + method=method, + candidates=candidates, + scores=scores, + meets_target=meets, + regret=regret, + share_best=share_best, + share_best_by_candidate=by_candidate, + share_meets_target=float(np.mean(meets[:, 0])), + expected_regret=float(known.mean()) if known.size else float("nan"), + draw_choices=choices, + n_draws=n_draws, + band=drawn.band_of(rbd, inputs, groups), + held_fixed=drawn.held_fixed(rbd, inputs, groups), + ) + + +def _planned( + rbd, intervals, cost, availability, goal, score, best, offsets=None +) -> MaintenancePlan: + """The plan of an interval choice, with what its ``goal`` (if any) + comes to at the choice ``best``.""" + if goal is None: + return MaintenancePlan(intervals, cost, availability, offsets=offsets) return MaintenancePlan( - {node: float(best[node]) for node in chosen}, cost, availability + intervals, + cost, + availability, + offsets=offsets, + objective=goal.objective, + discount_rate=goal.rate, + value_rate=goal.value_rate, + horizon=goal.horizon, + objective_value=goal.achieved(score(best)), + basis=goal.basis(rbd), ) @@ -459,12 +930,16 @@ def _searched_replacements( evaluate: Callable[[dict], Tuple[float, float]], min_availability: Optional[float], max_cost_rate: Optional[float], + score=None, + near: Optional[dict] = None, ) -> dict: """The age-replacement intervals of ``chosen`` that ``optimal_replacement_intervals`` gives without ``allowed``: by a gradient search over their logarithms, each from a thousandth to a thousand times its component's mean life, one at the top of its - range compared with never replacing it.""" + range compared with never replacing it. With ``near`` (intervals), + the search is from those alone, for a ``score`` worked out by + quadrature.""" scale = {} for node in chosen: life = failure_time_scale(rbd.components[node].reliability) @@ -488,6 +963,17 @@ def _searched_replacements( np.array([math.log(0.3 * scale[n]) for n in chosen]), high.copy(), ] + if near is not None: + starts = [ + np.clip( + [ + math.log(near[n]) if math.isfinite(near[n]) else h + for n, h in zip(chosen, high) + ], + low, + high, + ) + ] best = _choose_intervals( chosen, evaluate, @@ -495,7 +981,15 @@ def _searched_replacements( (low, high), min_availability, max_cost_rate, + score, + quadrature=near is not None, ) + + def scored(intervals: dict) -> float: + if score is not None: + return score(intervals) + return _objective(*evaluate(intervals), max_cost_rate) + # An interval at the top of its range may be better never used. for i, node in enumerate(chosen): if best[node] >= 0.99 * math.exp(high[i]): @@ -503,9 +997,7 @@ def _searched_replacements( cost, availability = evaluate(never) if _meets( cost, availability, min_availability, max_cost_rate - ) and _objective(cost, availability, max_cost_rate) <= _objective( - *evaluate(best), max_cost_rate - ): + ) and scored(never) <= scored(best): best = never return best @@ -519,6 +1011,10 @@ def optimal_inspection_intervals( max_cost_rate: Optional[float], assume_unlimited_crews: bool, offset_shares, + objective: str, + discount_rate: float, + value_rate: float, + horizon, ) -> MaintenancePlan: """See ``RepairableRBD.optimal_inspection_intervals``.""" chosen = _inspected(rbd, nodes) @@ -528,23 +1024,34 @@ def optimal_inspection_intervals( if rbd._crews_couple(): if not assume_unlimited_crews: _require_interval_crews(rbd) - return _unlimited_crews(rbd).optimal_inspection_intervals( + salaries = _crew_salaries(rbd) + plan = _unlimited_crews(rbd).optimal_inspection_intervals( chosen, allowed=allowed, min_availability=min_availability, - max_cost_rate=max_cost_rate, + max_cost_rate=_less_salaries(max_cost_rate, salaries), offset_shares=offset_shares, + objective=objective, + discount_rate=discount_rate, + value_rate=value_rate, + horizon=horizon, ) + return _with_salaries(plan, salaries) + goal = _goal(rbd, objective, discount_rate, value_rate, horizon) # Each failure rate per unit its interval is given in. rates = { node: _requirements._tested_scale(rbd, node) / _per_given(rbd, node) for node in chosen } + def planned(intervals: dict) -> "RepairableRBD": + return _with_intervals(rbd, inspection=intervals) + def evaluate(intervals: dict) -> Tuple[float, float]: - plan = _with_intervals(rbd, inspection=intervals) + plan = planned(intervals) return plan.expected_cost_rate(), plan.mean_availability() + score = _scorer(goal, evaluate, planned) if offset_shares is not None: if allowed is None: raise ValueError( @@ -559,6 +1066,7 @@ def evaluate(intervals: dict) -> Tuple[float, float]: _allowed_shares(offset_shares, chosen), min_availability, max_cost_rate, + goal, ) if allowed is None and rbd._inspection[chosen[0]].partial: _requirements._require_one_inspected(rbd) @@ -572,6 +1080,7 @@ def evaluate(intervals: dict) -> Tuple[float, float]: evaluate, min_availability, max_cost_rate, + score, ) elif allowed is None: _requirements._require_one_inspected(rbd) @@ -588,14 +1097,28 @@ def evaluate(intervals: dict) -> Tuple[float, float]: np.array([math.log(0.1 / rate)]), np.array([math.log(1.0 / rate)]), ] - best = _choose_intervals( + searched = partial( + _choose_intervals, chosen, evaluate, - starts, - (low, high), - min_availability, - max_cost_rate, + bounds=(low, high), + min_availability=min_availability, + max_cost_rate=max_cost_rate, ) + if goal is not None and goal.objective == "npv": + # A net present value takes its curves over the horizon at + # each interval: searched from the long run's best. + near = searched( + starts, + score=_scorer(_long_run_goal(rbd, goal), evaluate, planned), + ) + best = searched( + [np.array([math.log(near[node])])], + score=score, + quadrature=True, + ) + else: + best = searched(starts, score=score) else: best = _choose_from( chosen, @@ -603,6 +1126,7 @@ def evaluate(intervals: dict) -> Tuple[float, float]: evaluate, min_availability, max_cost_rate, + score, ) cost, availability = evaluate(best) # The offsets the plan's tests keep: each its share of the interval. @@ -612,10 +1136,14 @@ def evaluate(intervals: dict) -> Tuple[float, float]: / rbd._inspection[node].interval for node in chosen } - return MaintenancePlan( + return _planned( + rbd, {node: float(best[node]) for node in chosen}, cost, availability, + goal, + score, + best, offsets=offsets_kept, ) @@ -651,10 +1179,50 @@ def _require_interval_crews(rbd) -> None: def _unlimited_crews(rbd) -> "RepairableRBD": - """This RBD with as many repair crews as jobs, built as it was.""" + """This RBD with as many repair crews as jobs, built as it was, but + with no crews' salaries (as many crews as are needed are not paid: + see ``_with_salaries``).""" from repyability.rbd.repairable_rbd import RepairableRBD - return RepairableRBD(**{**rbd._init_args, "repair_crews": None}) + return RepairableRBD( + **{ + **rbd._init_args, + "repair_crews": None, + "crew_cost_rate": 0.0, + "call_out": None, + } + ) + + +def _less_salaries(max_cost_rate, salaries: float): + """A ``max_cost_rate`` for the plan without the crews' ``salaries`` + (see ``_unlimited_crews``), which every plan pays.""" + if max_cost_rate is None or not salaries: + return max_cost_rate + if max_cost_rate <= salaries: + raise ValueError( + f"max_cost_rate {max_cost_rate} cannot be met: the repair " + f"crews' salaries alone cost {salaries:.6g} per unit time." + ) + return max_cost_rate - salaries + + +def _with_salaries(plan: MaintenancePlan, salaries: float) -> MaintenancePlan: + """``plan``, chosen without the crews' ``salaries``, with them.""" + if not salaries: + return plan + achieved = plan.objective_value + if achieved is not None: + # Its score again, with the salaries paid. + goal = _Goal( + plan.objective, plan.discount_rate, plan.value_rate, plan.horizon + ) + achieved = goal.achieved( + -achieved if plan.objective == "npv" else achieved, salaries + ) + return dataclasses.replace( + plan, cost_rate=plan.cost_rate + salaries, objective_value=achieved + ) def with_intervals(rbd, intervals, offsets) -> "RepairableRBD": @@ -731,6 +1299,7 @@ def _choose_tests( shares: dict, min_availability: Optional[float], max_cost_rate: Optional[float], + goal: Optional[_Goal] = None, ) -> MaintenancePlan: """``optimal_inspection_intervals`` with the offsets chosen too: each node's interval from ``intervals`` and its first test's share of it @@ -743,22 +1312,35 @@ def _choose_tests( options = {("interval", n): intervals[n] for n in chosen} options.update({("offset", n): shares[n] for n in chosen}) - def evaluate(choice: dict) -> Tuple[float, float]: - plan = _with_intervals( + def planned(choice: dict) -> "RepairableRBD": + return _with_intervals( rbd, inspection={n: choice[("interval", n)] for n in chosen}, offsets={n: choice[("offset", n)] for n in chosen}, ) + + def evaluate(choice: dict) -> Tuple[float, float]: + plan = planned(choice) return plan.expected_cost_rate(), plan.mean_availability() + score = _scorer(goal, evaluate, planned) best = _choose_from( - list(options), options, evaluate, min_availability, max_cost_rate + list(options), + options, + evaluate, + min_availability, + max_cost_rate, + score, ) cost, availability = evaluate(best) - return MaintenancePlan( + return _planned( + rbd, {n: float(best[("interval", n)]) for n in chosen}, cost, availability, + goal, + score, + best, offsets={ n: float(best[("offset", n)] * best[("interval", n)]) for n in chosen diff --git a/repyability/rbd/_long_run.py b/repyability/rbd/_long_run.py index 65f0dfab..0d8049da 100644 --- a/repyability/rbd/_long_run.py +++ b/repyability/rbd/_long_run.py @@ -103,7 +103,7 @@ def mean_unavailability( _shutdowns.require_exact(rbd) method = structure_method(method) working_nodes, broken_nodes = rbd._held_nodes(working_nodes, broken_nodes) - if rbd.ccf_groups: + if _ccf_groups._own_chains(rbd): # Each group conditioned on within its module (#218). _, weights, inputs = _ccf_groups._ccf_long_run( rbd, working_nodes, broken_nodes @@ -136,6 +136,7 @@ def _node_long_run(rbd, node) -> Tuple[str, str]: for check in ( partial(_requirements._require_perfect_repair, rbd), partial(_requirements._require_times, rbd), + partial(_shocked, rbd), ): message = r.refusal(partial(check, node)) if message: @@ -195,6 +196,12 @@ def _node_long_run(rbd, node) -> Tuple[str, str]: message = r.refusal( partial(_requirements._require_block_models, rbd, node) ) + if not message and ( + schedule.plan is not None + or schedule.shuts is not None + or schedule.upgrade_at is not None + ): + message = r.refusal(partial(_requirements._require_no_plans, rbd)) if message: return r.REFUSED, message if schedule.level is not None: @@ -226,6 +233,17 @@ def _node_long_run(rbd, node) -> Tuple[str, str]: return r.NUMERICAL, "age replacement: its mean up time, by quadrature" +def _shocked(rbd, node) -> None: + """Raise for a member of a ``Shocks`` group: its long-run values + have no exact form (see ``_require_own_failures``).""" + _requirements._require_own_failures( + rbd, + node, + "estimate its availability by simulation, with availability() " + "(the run's node_uptime and node_downtime).", + ) + + def _long_run_nodes(rbd) -> Dict[Any, Tuple[str, str]]: """Each component's long-run route (see ``_node_long_run``).""" return {node: _node_long_run(rbd, node) for node in rbd.components} @@ -241,16 +259,16 @@ def _long_run_route(rbd, groups: bool = True) -> "AnalysisRoute": shut = r.refusal(partial(_shutdowns.require_exact, rbd)) if shut: return r.refused(shut) + if rbd._crews_couple(): + # (Their chain takes the common-cause groups in, or refuses.) + return _crew_chain_route(rbd) chains = ( r.refusal(partial(_ccf_groups._require_ccf_long_run, rbd)) if groups else None ) if chains: - # (Before the crews: the groups' chains do not take them in.) return r.refused(chains) - if rbd._crews_couple(): - return _crew_chain_route(rbd) calendars = r.refusal(partial(_requirements._require_calendars, rbd)) if calendars: return r.refused(calendars) @@ -307,7 +325,14 @@ def _crew_chain_route(rbd) -> "AnalysisRoute": r.EXACT, "The long-run distribution of the Markov chain of the " "components' states and the repair queue, solved exactly, and " - "the system's values averaged over its states.", + "the system's values averaged over its states." + + ( + " A common-cause group's shared causes strike in the chain: " + "the members up fail at once and join the queue in the " + "group's order." + if rbd.ccf_groups + else "" + ), nested, "long-run values", ) @@ -325,7 +350,7 @@ def mean_availability( # https://www.diva-portal.org/smash/get/diva2:986067/FULLTEXT01.pdf working_nodes, broken_nodes = rbd._held_nodes(working_nodes, broken_nodes) - if rbd.ccf_groups: + if _ccf_groups._own_chains(rbd): # Each group conditioned on within its module (#218). method = structure_method(method) _, weights, inputs = _ccf_groups._ccf_long_run( @@ -371,6 +396,7 @@ def _node_availability(rbd, node) -> float: if node in chain.nodes: return chain.availability(node) return float(rbd.components[node].mean_availability()) + _shocked(rbd, node) if node in rbd._imperfect: terms = _minimal_cycle_terms(rbd, node) return terms.up / terms.length @@ -412,6 +438,7 @@ def _node_unavailability(rbd, node) -> float: not couple the components (see ``_long_run_unavailabilities``).""" _requirements._require_perfect_repair(rbd, node) _requirements._require_times(rbd, node) + _shocked(rbd, node) if node in rbd._imperfect: terms = _minimal_cycle_terms(rbd, node) return min(1.0, (terms.failed + terms.planned) / terms.length) @@ -535,6 +562,12 @@ def _block_cycle(rbd, node): _requirements._require_full_restoration(rbd, node) component = rbd.components[node] schedule = rbd._preventive[node] + if ( + schedule.plan is not None + or schedule.shuts is not None + or schedule.upgrade_at is not None + ): + _requirements._require_no_plans(rbd) if schedule.level is not None: return level_model(rbd, node).cycle() cache = rbd._cache.kept("block_cycles") @@ -600,6 +633,7 @@ def replacement_cycle(rbd, node) -> ReplacementCycle: # The checks _node_long_run makes, in its order. _requirements._require_perfect_repair(rbd, node) _requirements._require_times(rbd, node) + _shocked(rbd, node) _requirements._require_no_opportunities(rbd, node) _requirements._require_block_models(rbd, node) cycle = _block_cycle(rbd, node) @@ -1136,11 +1170,10 @@ def _long_run_probabilities( by every combination of their states (see ``_with_ccf_groups``, which ``what`` refuses where they are too many): for the capacity distribution, which takes the nodes' joint states.""" - if rbd.ccf_groups: - # The groups' chains refuse the crews (see _ccf_rates). - _ccf_groups._require_ccf_long_run(rbd) if rbd._crews_couple(): return _crews._chain_probabilities(rbd, working_nodes, broken_nodes) + if rbd.ccf_groups: + _ccf_groups._require_ccf_long_run(rbd) times, weights = _long_run_grid(rbd) probabilities = rbd._probabilities_with_overrides( _availabilities_at(rbd, times), working_nodes, broken_nodes @@ -1198,6 +1231,7 @@ def _node_frequencies(rbd, node) -> Tuple[float, float, float]: _requirements._require_perfect_repair(rbd, node) _requirements._require_times(rbd, node) + _shocked(rbd, node) component = rbd.components[node] if isinstance(component, RepairableRBD): failures, planned = _outage_frequencies(component) @@ -1373,10 +1407,10 @@ def _outage_terms( ``_chain_outage_terms``; with common-cause groups, ``_ccf_outage_terms``.""" _shutdowns.require_exact(rbd) - if rbd.ccf_groups: - return _ccf_groups._ccf_outage_terms(rbd, working_nodes, broken_nodes) if rbd._crews_couple(): return _crews._chain_outage_terms(rbd, working_nodes, broken_nodes) + if rbd.ccf_groups: + return _ccf_groups._ccf_outage_terms(rbd, working_nodes, broken_nodes) times, weights = _long_run_grid(rbd) availability = rbd._probabilities_with_overrides( _availabilities_at(rbd, times), working_nodes, broken_nodes @@ -1464,3 +1498,86 @@ def mean_down_time( if omega > 0.0: return unavailability / omega return 0.0 if unavailability <= 0.0 else float("inf") + + +#: The long-run methods a diagram with upgrades answers as the diagram +#: after them (see ``after_upgrades``): those that are long-run values, +#: or are by default (no ``x``, ``window`` or ``state`` given). +#: ``parameter_sensitivity`` is not one: its levers are the diagram's +#: own (the upgrade's time, the old life), which the diagram after the +#: upgrades has not; the long-run values it asks for are those once +#: upgraded all the same (``ROUTED_AFTER_UPGRADES``). +AFTER_UPGRADES = ( + "availability_allocation", + "barlow_proschan_importance", + "birnbaum_importance", + "capacity_distribution", + "criticality_importance", + "differential_importance", + "expected_cost_rate", + "expected_cost_rate_uncertainty", + "fussell_vesely", + "improvement_potential", + "joint_importance", + "mean_availability", + "mean_availability_uncertainty", + "mean_down_time", + "mean_time_between_failures", + "mean_unavailability", + "mean_up_time", + "mttf_mttr_allocation", + "node_action_rates", + "node_availability", + "pfd_breakdown", + "replacement_cycle", + "risk_achievement_worth", + "risk_reduction_worth", + "system_failure_frequency", + "uncertainty_importance", +) + +#: The methods whose routes are those of the diagram after the upgrades. +ROUTED_AFTER_UPGRADES = AFTER_UPGRADES + ("parameter_sensitivity",) + +#: The arguments that ask one of those methods for values over time. +_OVER_TIME = ("x", "window", "state") + + +def after_upgrades(rbd): + """The diagram as it is once its upgrades are done, for its long run: + each upgraded component with the upgrade's life in place of its own, + and no upgrade (its time and capital cost dropped; a block + replacement on its own interval kept). Built once and kept.""" + twin = getattr(rbd, "_upgraded_twin", None) + if twin is None: + components = dict(rbd._init_args["components"]) + for node in rbd._upgrades: + spec = dict(components[node]) + upgrade = spec.pop("upgrade") + spec["reliability"] = upgrade["reliability"] + components[node] = spec + twin = type(rbd)(**{**rbd._init_args, "components": components}) + rbd._upgraded_twin = twin + return twin + + +def follows_upgrades(method): + """A long-run method of ``RepairableRBD`` (one of ``AFTER_UPGRADES``): + on a diagram with upgrades, and not asked over time, the long run is + that after the upgrades, the earlier stretch ignored, so the method + is asked of ``after_upgrades``.""" + import inspect + + signature = inspect.signature(method) + timed = [name for name in _OVER_TIME if name in signature.parameters] + + @functools.wraps(method) + def wrapper(self, *args, **kwargs): + if self._upgrades: + given = signature.bind(self, *args, **kwargs).arguments + if all(given.get(name) is None for name in timed): + twin = after_upgrades(self) + return getattr(twin, method.__name__)(*args, **kwargs) + return method(self, *args, **kwargs) + + return wrapper diff --git a/repyability/rbd/_model_utils.py b/repyability/rbd/_model_utils.py index f3570fd2..21de9038 100644 --- a/repyability/rbd/_model_utils.py +++ b/repyability/rbd/_model_utils.py @@ -129,6 +129,14 @@ def call(name, *args): return missing +def is_diagram_life(model) -> bool: + """Whether ``model`` is a ``NonRepairableRBD`` taken as a life: one + whose reliability changes with time.""" + from .non_repairable_rbd import NonRepairableRBD + + return isinstance(model, NonRepairableRBD) and not model.is_fixed + + def by_functions(model) -> bool: """Whether ``model`` is a life taken by what it can do (#93): a surpyval model none of the kinds RePyability takes by its class (a @@ -137,12 +145,16 @@ def by_functions(model) -> bool: of ``LIFE_FUNCTIONS`` (``life_functions``): a Royston-Parmar fit, a regression at one unit's covariates (``regression.at(Z)``), a destructive degradation model, and any other surpyval model with - them.""" + them. A ``NonRepairableRBD`` whose reliability changes with time is + one too: a subassembly replaced whole at its failure, taken by its + functions (its ``qf`` inverting its ``ff``).""" from surpyval import NonParametric, Parametric from ._degradation import is_degradation from .joint_node import is_joint + if is_diagram_life(model): + return True if not type(model).__module__.startswith("surpyval."): return False if ( diff --git a/repyability/rbd/_npv.py b/repyability/rbd/_npv.py index 6f3c1477..b77596d1 100644 --- a/repyability/rbd/_npv.py +++ b/repyability/rbd/_npv.py @@ -11,7 +11,7 @@ import numpy as np -from repyability.rbd import _curves, _requirements, _windows +from repyability.rbd import _curves, _requirements, _shutdowns, _windows from repyability.rbd._common import ( _discount_rate, _present_horizon, @@ -19,6 +19,86 @@ from repyability.rbd._tally import _CATEGORIES from repyability.rbd.results import ExpectedNPV from repyability.utils import checks +from repyability.value import _escalation as _money +from repyability.value._escalation import STREAMS as _STREAMS # noqa: F401 +from repyability.value._escalation import inflation as _inflation +from repyability.value.value_schedule import ValueSchedule, value_of + + +def _escalation(rbd, escalation) -> Dict[Any, float]: + """``escalation`` checked for ``rbd``'s components.""" + return _money.escalation(rbd.components, escalation) + + +def own_terms(rbd, horizon: float, salvage, escalation, retire_at): + """``salvage``, ``escalation`` and ``retire_at`` with the components' + own (their spec's or plan's ``"salvage"``, ``"escalation"`` and + ``"retire_at"``) added where the arguments leave them out: a salvage + or growth given for a node in the arguments is the node's. A unit's + retirement before the horizon retires the diagram when it is its only + component; in a diagram of several it is refused.""" + own = getattr(rbd, "_valuation", {}) + if not own: + return salvage, escalation, retire_at + salvages = {n: v["salvage"] for n, v in own.items() if "salvage" in v} + if salvages: + if salvage is None: + salvage = salvages + elif isinstance(salvage, dict): + salvage = {**salvages, **salvage} + else: + salvage = {None: salvage, **salvages} + growths = {n: v["escalation"] for n, v in own.items() if "escalation" in v} + if growths and (escalation is None or isinstance(escalation, dict)): + escalation = {**growths, **(escalation or {})} + retiring = {n: v["retire_at"] for n, v in own.items() if "retire_at" in v} + if retiring and retire_at is None: + node, at = next(iter(retiring.items())) + if len(rbd.components) > 1: + raise NotImplementedError( + f"Component {node!r} retires at {at:g}, and retiring one " + "unit of a diagram of several is not built: give the " + "valuation's retire_at to retire the whole system, or " + "value the unit's plan alone (UnitPlan.expected_npv)." + ) + if at < horizon: + retire_at = at + return salvage, escalation, retire_at + + +def own_escalation(rbd, escalation): + """``escalation`` with each component's own growth added where it + names none for the component (see ``own_terms``).""" + return own_terms(rbd, math.inf, None, escalation, None)[1] + + +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 + ``own_terms``): ``(stop, present, nominal, retired)``, the runs' end + (the retirement, or the horizon), the salvage credited then, + discounted and not, and whether the plan retires before the + horizon. Every run credits the same: a salvage given as a + number is worth that whatever happened. A salvage by age, which + depends on each run's unit in service, is refused.""" + salvage, _, retire_at = own_terms(rbd, horizon, None, None, None) + stop = _retirement(retire_at, horizon) + given = salvage if isinstance(salvage, dict) else {} + for node, worth in given.items(): + if callable(worth): + raise NotImplementedError( + f"Component {node!r} has a salvage by age, which the " + "valuations of simulated runs (npv_distribution, " + "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()) + total = float(sum(credits.values())) + growth = money.growth("salvage") + present = math.exp(-(money.rate - growth) * stop) * total + nominal = (math.exp(growth * stop) if growth else 1.0) * total + return stop, present, nominal, stop < horizon def _number(value, name: str, strict: bool) -> float: @@ -32,6 +112,69 @@ def _number(value, name: str, strict: bool) -> float: return number +class Money: + """How amounts are valued, checked from the arguments the NPV methods + share: the rate given (``given_rate``) and the one amounts are + discounted at (``rate``, with the inflation of real rates), the value + earned (a number, ``worth``, or a ``schedule``), each stream's growth + (``growth``), and whether anything is earned (``earns``). + + In real terms with inflation every amount is made nominal: the rate + and every stream's growth take the inflation too, which leaves the + present values as they are.""" + + def __init__( + self, + rbd, + discount_rate, + value_rate, + escalation=None, + rates: str = "nominal", + inflation=None, + ): + self.given_rate = _discount_rate(discount_rate) + value = value_of(value_rate) + self.schedule: Optional[ValueSchedule] = ( + value if isinstance(value, ValueSchedule) else None + ) + self.worth = 0.0 if self.schedule is not None else float(value) + self.escalation = _escalation(rbd, escalation) + self.basis = rates + self.lift = _inflation(inflation, rates) + self.inflation = None if inflation is None else self.lift + self.rate = self.given_rate + self.lift + self.earns = ( + bool(self.worth) + if self.schedule is None + else any(self.schedule.rates) + ) + + def growth(self, *keys) -> float: + """The growth of a stream, by the first of ``keys`` named.""" + return _money.growth(self.escalation, self.lift, *keys) + + def steps(self, stop: float): + """The value earned as steps before ``stop``: their starts, ends + and rates (one step of ``worth`` for a single rate).""" + if self.schedule is None: + return np.array([0.0]), np.array([stop]), np.array([self.worth]) + return self.schedule.steps(stop) + + @property + def value_rate(self) -> float: + """The single rate earned (NaN with a schedule).""" + return self.worth if self.schedule is None else math.nan + + def stated(self) -> Dict[str, Any]: + """The basis a result states.""" + return dict( + rate_basis=self.basis, + inflation=self.inflation, + escalation=dict(self.escalation), + value_schedule=self.schedule, + ) + + def _period_ends(periods, horizon: float) -> np.ndarray: """The ends of the periods of the cash-flow table: ``periods`` equal ones if a whole number, else the increasing ends given, the last the @@ -64,6 +207,124 @@ def _period_ends(periods, horizon: float) -> np.ndarray: return ends +def _retirement(retire_at, horizon: float) -> float: + """When the plan ends: the horizon, or ``retire_at`` (checked: more + than 0 and no later than the horizon), the time the system is + retired at.""" + if retire_at is None: + return horizon + stop = _number(retire_at, "retire_at", strict=True) + if math.isclose(stop, horizon, rel_tol=1e-12): + return horizon + if stop > horizon: + raise ValueError( + f"retire_at ({stop:g}) is past the horizon ({horizon:g}), " + "where the valuation ends anyway: leave it out, or value a " + "longer horizon." + ) + return stop + + +def _salvage(rbd, salvage, at: float, state, forced) -> Dict[Any, float]: + """The expected salvage credited at ``at`` (the retirement, or the + horizon), undiscounted, by component (None: the system's): + ``salvage`` checked, a number (the system's) or a dict of a number, + or a function of the age of the unit in service (see + ``_salvage_by_age``), for each component, and for None the + system's.""" + if salvage is None: + return {} + given = salvage if isinstance(salvage, dict) else {None: salvage} + out: Dict[Any, float] = {} + for component, worth in given.items(): + if component is not None and component not in rbd.components: + raise _requirements._not_a_component(rbd, component, "salvage") + whose = "the system" if component is None else f"{component!r}" + if callable(worth): + if component is None: + raise ValueError( + "The system's salvage must be a number: a salvage by " + "age is a component's, of the age of its unit in " + "service ({component: function})." + ) + out[component] = _salvage_by_age( + rbd, component, worth, at, state, forced + ) + continue + number = checks.number_or_nan(worth) + if not math.isfinite(number): + raise ValueError( + f"The salvage of {whose} must be a finite number (what it " + "is worth at the end; negative for a cost of disposal), or " + "for a component a function of the age of its unit in " + f"service; got {worth!r}." + ) + out[component] = number + return out + + +#: The cells the time to the end is cut into for a salvage by age. +_AGE_CELLS = 4000 + + +def _salvage_by_age(rbd, node, worth, at: float, state, forced) -> float: + """The expected salvage of a component at ``at``, ``worth(age)`` of + the unit in service then if it is up (a unit down then, in a repair, + is credited nothing): from the age of the unit in service, which is + the time since it was put in, at 0 (never failed since: ``R(at)``) or + at the end of a repair (the expected units put in over each cell of + the time, from the component's expected failures and its repair + time, each still up with probability ``R(age)``). + + That is a plain unit's, from new: one with a schedule, tests, + imperfect repair, a group, crews to wait for or a state at 0 has no + such age here, and is refused, asking for a number.""" + from repyability.rbd._block_replacement import _Duration + from repyability.rbd.non_repairable_rbd import NonRepairableRBD # noqa + + states = _curves._states(rbd, state, forced) + plain = ( + _curves._plain_unit(rbd, node) + and type(rbd.components[node]).__name__ == "NonRepairable" + and node not in forced + and node not in (states or {}) + and not rbd._crews_couple() + and not any(node in group.members for group in rbd.ccf_groups) + and not _shutdowns.holding(rbd, node) + ) + if not plain: + raise NotImplementedError( + f"Component {node!r}: a salvage by age needs the age of the " + "unit in service at the end, which is worked out for a plain " + "component from new (no maintenance, upgrade, tests, " + "imperfect repair, standby, group, shutdown, crews to wait " + "for or state at 0): give its salvage as a number." + ) + component = rbd.components[node] + curve = _curves._unit_curve(rbd, node, at, counts=True) + edges = np.linspace(0.0, at, _AGE_CELLS + 1) + middle = 0.5 * (edges[1:] + edges[:-1]) + failing = np.diff(curve.events(edges)["failures"]) + # The units put into service by each edge: those failed in each cell + # (at its middle) whose repair is over by then. + repair = _Duration(component.time_to_replace, "repair", node) + since = edges[:, None] - middle[None, :] + done = np.where(since > 0.0, repair.cdf(np.maximum(since, 0.0)), 0.0) + put_in = np.diff(done @ failing) + ages = np.concatenate(([at], at - middle)) + weights = np.concatenate(([1.0], put_in)) + alive = np.clip( + np.asarray(component.reliability.sf(ages), float), 0.0, 1.0 + ) + values = np.asarray(worth(ages), dtype=float) + if values.shape != ages.shape or not np.all(np.isfinite(values)): + raise ValueError( + f"The salvage of {node!r} by age must take an array of ages " + "and return a finite value for each." + ) + return float(np.sum(values * alive * weights)) + + def _uptime(rbd, ends, rate, working, broken, method, state) -> np.ndarray: """The integral from 0 to each of ``ends`` of ``exp(-rate t)`` times the system's point availability.""" @@ -90,68 +351,134 @@ def expected_npv( broken_nodes: Optional[Collection[Hashable]], method: str, state, + retire_at=None, + salvage=None, + rate_sensitivity: bool = False, + escalation=None, + rates: str = "nominal", + inflation=None, ) -> ExpectedNPV: """See ``RepairableRBD.expected_npv``.""" - rate = _discount_rate(discount_rate) + if not isinstance(rate_sensitivity, (bool, np.bool_)): + raise TypeError( + "rate_sensitivity must be True or False (whether to work out " + f"the NPV's derivative in the discount rate); got " + f"{rate_sensitivity!r}." + ) horizon = _number(horizon, "horizon", strict=True) - value_rate = _number(value_rate, "value_rate", strict=False) - ends = _period_ends(periods, horizon) - if not value_rate: + salvage, escalation, retire_at = own_terms( + rbd, horizon, salvage, escalation, retire_at + ) + money = Money(rbd, discount_rate, value_rate, escalation, rates, inflation) + given_rate, rate, schedule = money.given_rate, money.rate, money.schedule + growth, earns = money.growth, money.earns + table_ends = _period_ends(periods, horizon) + # Retired before the horizon, nothing is earned or spent after: every + # value is worked out to the retirement, and stays there. + stop = _retirement(retire_at, horizon) + ends = np.minimum(table_ends, stop) + if not earns: _requirements._require_costs(rbd) method = checks.structure_method(method) working, broken = rbd._held_nodes(working_nodes, broken_nodes) - starts = np.concatenate(([0.0], ends[:-1])) + starts = np.concatenate(([0.0], table_ends[:-1])) + credits = _salvage(rbd, salvage, stop, state, working | broken) present_cells: Dict[Any, Any] = {} nominal_cells: Dict[Any, Any] = {} systems: Dict[str, Any] = {} + worth = money.worth + value_growth = growth("value") with rbd._sharing_curves(): - if value_rate: - up_present = value_rate * _uptime( - rbd, ends, rate, working, broken, method, state + + def earned(effective: float) -> np.ndarray: + """The value earned to each end, each amount at ``t`` times + ``exp(-effective t)``: a steady rate's, or each step's.""" + if schedule is None: + return worth * _uptime( + rbd, ends, effective, working, broken, method, state + ) + starts, stops, step_rates = schedule.steps(stop) + knots = np.unique(np.concatenate([ends, starts[1:]])) + found = dict( + zip( + knots.tolist(), + _uptime( + rbd, knots, effective, working, broken, method, state + ).tolist(), + ) ) + found[0.0] = 0.0 + out = np.zeros(len(ends)) + for a, b, step in zip(starts, stops, step_rates): + if step: + upper = np.minimum(ends, b) + lower = np.minimum(ends, a) + out += step * np.array( + [found[u] - found[w] for u, w in zip(upper, lower)] + ) + return out + + if earns: + up_present = earned(rate - value_growth) up_nominal = ( - value_rate - * _uptime(rbd, ends, 0.0, working, broken, method, state) - if rate - else up_present + earned(-value_growth) if rate or value_growth else up_present ) else: up_present = up_nominal = np.zeros(len(ends)) if rbd.has_costs: # The costs, cumulative at each period's end, by component - # and category; discounted at their exact times, and not. - got = _windows.expected_cost( - rbd, - ends, - working, - broken, - method, - state, - discount_rate=rate, - cells=present_cells, - ) - if rate: - plain = _windows.expected_cost( - rbd, - ends, - working, - broken, - method, - state, - discount_rate=0.0, - cells=nominal_cells, - ) - else: - plain, nominal_cells = got, present_cells - # The system's downtime, a group's set-up and a shutdown's - # costs are no component's. - for category in ("system_downtime", "setup", "shutdown"): - a = np.atleast_1d(got.by_category[category]) + # and category; discounted at their exact times, and not: + # each at its stream's growth, worked out once for each rate + # less a growth (a growth above the rate is a rate below 0, + # valid over a horizon). + found_at: Dict[float, Any] = {} + + def costs_at(effective: float): + if effective not in found_at: + cells: Dict[Any, Any] = {} + if effective >= 0.0: + got = _windows.expected_cost( + rbd, + ends, + working, + broken, + method, + state, + discount_rate=effective, + cells=cells, + ) + else: + got = _windows._discounted_cost( + rbd, + ends, + effective, + working, + broken, + method, + state, + cells, + ) + found_at[effective] = (got, cells) + return found_at[effective] + + for node, category in costs_at(rate)[1]: + g = growth(node, category) + present_cells[(node, category)] = costs_at(rate - g)[1][ + (node, category) + ] + nominal_cells[(node, category)] = costs_at(-g)[1][ + (node, category) + ] + # The system's downtime, a group's set-up, a shutdown's and + # the repair crews' costs are no component's. + for category in ("system_downtime", "setup", "shutdown", "crews"): + g = growth(category) + a = np.atleast_1d(costs_at(rate - g)[0].by_category[category]) if np.any(a): systems[category] = ( a, - np.atleast_1d(plain.by_category[category]), + np.atleast_1d(costs_at(-g)[0].by_category[category]), ) elif rate: _present_horizon( @@ -172,7 +499,7 @@ def increments(cumulative) -> np.ndarray: def add(category, component, present, nominal) -> None: present, nominal = increments(present), increments(nominal) - sign = 1.0 if category == "value" else -1.0 + sign = 1.0 if category in ("value", "salvage") else -1.0 for k in range(len(ends)): if present[k] == 0.0 and nominal[k] == 0.0: continue @@ -180,14 +507,14 @@ def add(category, component, present, nominal) -> None: { "period": k + 1, "start": float(starts[k]), - "end": float(ends[k]), + "end": float(table_ends[k]), "category": category, "component": component, "present_value": sign * float(present[k]), "undiscounted": sign * float(nominal[k]), } ) - if category != "value": + if category not in ("value", "salvage"): total = float(present.sum()) cost_by_category[category] = ( cost_by_category.get(category, 0.0) + total @@ -207,7 +534,24 @@ def add(category, component, present, nominal) -> None: for category, (present, nominal) in systems.items(): add(category, None, present, nominal) add("value", None, up_present, up_nominal) - order = {name: i for i, name in enumerate(("acquisition",) + _CATEGORIES)} + # The salvage, credited at the retirement (or the horizon): in the + # period it falls in. + paid = table_ends >= stop + salvage_growth = growth("salvage") + worth_now = math.exp(-(rate - salvage_growth) * stop) + grown = math.exp(salvage_growth * stop) if salvage_growth else 1.0 + for component, amount in credits.items(): + if amount: + add( + "salvage", + component, + worth_now * amount * paid, + grown * amount * paid, + ) + order = { + name: i + for i, name in enumerate(("acquisition",) + _CATEGORIES + ("salvage",)) + } rows.sort( key=lambda r: ( r["period"], @@ -220,23 +564,86 @@ def add(category, component, present, nominal) -> None: cost = float(sum(cost_by_category.values())) undiscounted_value = float(up_nominal[-1]) undiscounted_cost = float( - -sum(r["undiscounted"] for r in rows if r["category"] != "value") + -sum( + r["undiscounted"] + for r in rows + if r["category"] not in ("value", "salvage") + ) ) + undiscounted_salvage = grown * float(sum(credits.values())) + salvaged = worth_now * float(sum(credits.values())) result = ExpectedNPV( horizon=horizon, - discount_rate=rate, - value_rate=value_rate, - npv=value - cost, + discount_rate=given_rate, + value_rate=money.value_rate, + npv=value - cost + salvaged, value=value, cost=cost, eac=0.0, - undiscounted_npv=undiscounted_value - undiscounted_cost, + undiscounted_npv=( + undiscounted_value - undiscounted_cost + undiscounted_salvage + ), undiscounted_value=undiscounted_value, undiscounted_cost=undiscounted_cost, cost_by_category=cost_by_category, cost_by_component=cost_by_component, - period_ends=[float(x) for x in ends], + period_ends=[float(x) for x in table_ends], cash_flows=rows, + salvage=salvaged, + undiscounted_salvage=undiscounted_salvage, + retire_at=None if retire_at is None else stop, + **money.stated(), ) result.eac = cost / result.annuity_factor + if rate_sensitivity: + + def npv_at(r: float) -> float: + return expected_npv( + rbd, + horizon, + discount_rate=r, + value_rate=value_rate, + periods=None, + working_nodes=working_nodes, + broken_nodes=broken_nodes, + method=method, + state=state, + retire_at=retire_at, + salvage=salvage, + escalation=escalation, + rates=rates, + inflation=inflation, + ).npv + + result.rate_sensitivity, result.rate_sensitivity_error = ( + _rate_derivative(npv_at, given_rate, result.npv, stop) + ) return result + + +#: The step of the discount rate the NPV's derivative is differenced on, +#: times the time valued: the rate's effect on an amount at ``t`` is +#: through ``r t``, so the step is a share of ``1 / stop`` whatever the +#: unit of time. +_RATE_STEP = 1e-2 + + +def _rate_derivative(npv_at, rate: float, base: float, stop: float): + """The derivative of the NPV in the discount rate at ``rate``, and an + estimate of its error: Richardson's extrapolation of differences on + steps ``h`` and ``2 h`` (``h = _RATE_STEP / stop``), central where the + rate stays at least 0 and one-sided (second order) from ``rate`` + otherwise; the error is a third of the two steps' difference, the + size of the smaller step's own error, which the extrapolation + removes the leading term of.""" + h = _RATE_STEP / stop + if rate >= 2.0 * h: + up1, down1 = npv_at(rate + h), npv_at(rate - h) + up2, down2 = npv_at(rate + 2.0 * h), npv_at(rate - 2.0 * h) + fine = (up1 - down1) / (2.0 * h) + coarse = (up2 - down2) / (4.0 * h) + else: + f1, f2, f4 = (npv_at(rate + k * h) for k in (1.0, 2.0, 4.0)) + fine = (-3.0 * base + 4.0 * f1 - f2) / (2.0 * h) + coarse = (-3.0 * base + 4.0 * f2 - f4) / (4.0 * h) + return (4.0 * fine - coarse) / 3.0, abs(fine - coarse) / 3.0 diff --git a/repyability/rbd/_npv_runs.py b/repyability/rbd/_npv_runs.py new file mode 100644 index 00000000..cb2a86a8 --- /dev/null +++ b/repyability/rbd/_npv_runs.py @@ -0,0 +1,636 @@ +"""The net present value of each simulated run of a ``RepairableRBD`` +(``RepairableRBD.npv_distribution``), and their spread. + +Each run is a history of ``simulate_timelines`` (the event loop's, on +every engine), priced with the diagram's own costs and discounted at the +times they fell (``_pricing``): each failure its repair and replace +costs, each planned outage its preventive cost, each component's and the +system's time down their downtime costs, and the system's time up its +value, the integral of ``value_rate * exp(-r t)`` over its spans up (each +step's rate over its part of them, for a ``ValueSchedule``), every amount +grown at its stream's escalation (``price * exp(g t)``, see +``_npv.Money``). The +acquisition costs are paid at 0 in every run, and each shutdown's cost at +each of its starts (its calendar's, the same in every run). A component a +shut holds off line shows a planned change in its history that is no +task: the Python loop marks those holds, and records the changes down a +hold hid (a failure in the shut, a renewal made in it), which are charged +as recorded ones are (``_timeline_runs.Hidden``). A cost charged at an event +the histories do not record (``_pricing.unrecorded``: a standby group's +units' failures, a test, a replacement that takes no time, a set-up) is +not left out: the method refuses the diagram, naming it. Only the runs' +present values are kept, not their histories. + +An ``AvailabilityContract`` adds, run by run, each period's penalty or +bonus, from the share of the period the system was up in that run (its +spans up, as for the value), paid at the period's end. ``compare_npv`` +prices two plans' runs from one seed: a component in the same place in +both draws the same random numbers in both (the streams, as ``compare`` +has them), so each run's difference comes from how the plans differ. +""" + +import math +from typing import Any, Dict, Hashable, List, Optional, Tuple + +import numpy as np + +from repyability.rbd import ( + _crews, +) +from repyability.rbd import _montecarlo as montecarlo +from repyability.rbd import _npv, _pricing, _requirements, _streams +from repyability.rbd.contracts import AvailabilityContract +from repyability.rbd.results import ( + ConfidenceInterval, + NPVComparison, + NPVDistribution, + _order_statistic, +) +from repyability.utils import checks + +#: Simulations priced at a time: only their present values are kept. +_CHUNK = 2000 + +_INSTEAD = ( + " expected_npv gives the expected value with it, and cost() the " + "spread of the undiscounted cost; to simulate the rest, leave the " + "cost out." +) + + +def refusal(rbd) -> Optional[Tuple[str, Tuple[Hashable, ...]]]: + """Why the runs of ``rbd`` cannot be priced from their histories, and + the components named, or None if they can.""" + if _crews._call_out_priced(rbd): + return ( + "The call-out crew's fee and rate are charged when it is " + "called and while it is engaged, which the simulated " + "histories do not record." + _INSTEAD, + (), + ) + for category, node, why in _pricing.unrecorded(rbd): + 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" + if node is None + else f"The {category} cost of component {node!r}" + ) + extra = ( + " Give its planned replacements a duration, and each leaves " + "an outage to price." + if why == _pricing._INSTANT + else "" + ) + return ( + f"{whose} is charged at events the simulated histories do not " + f"record: {why}{extra}" + _INSTEAD, + (node,) if node is not None else (), + ) + for node in rbd._restoring: + if "replacement_cost" in rbd.costs.get(node, {}): + return ( + f"The replacement cost of component {node!r} is charged at " + "every so many of its tasks, which the histories do not " + "count." + _INSTEAD, + (node,), + ) + for node, inspection in rbd._inspection.items(): + if inspection.duration is not None and "preventive_cost" in ( + rbd.costs.get(node, {}) + ): + return ( + f"Component {node!r} has tests that take it off line and a " + "preventive cost: its histories do not tell the two " + "planned outages apart." + _INSTEAD, + (node,), + ) + return None + + +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]) + + +def route(rbd, timelines_route): + """``npv_distribution``'s route: ``simulate_timelines``' (whose + histories it prices), unless a cost is not in them.""" + from repyability.rbd import routes as r + + if timelines_route.route == r.REFUSED: + return timelines_route + own = r.refusal( + lambda: _npv.own_end(rbd, math.inf, _npv.Money(rbd, 0.0, 0.0)) + ) + if own is not None: + return r.refused(own, tuple(rbd._valuation)) + found = refusal(rbd) + if found is not None: + return r.refused(*found) + return r.AnalysisRoute( + r.SIMULATED, + "The simulations simulate_timelines makes, each history priced " + "with the diagram's costs and discounted at the times they fell.", + engine=timelines_route.engine, + engine_reason=timelines_route.engine_reason, + ) + + +def compare_route(npv_route, rbd): + """``compare_npv``'s route, for this diagram against one like it: + ``npv_distribution``'s, the runs matched, unless its draws cannot + be.""" + from repyability.rbd import routes as r + + if npv_route.route == r.REFUSED: + return npv_route + why = r.refusal(lambda: _require_matched(rbd, "this plan", 1.0, None)) + if why is not None: + return r.refused(why, tuple(_unmatched(rbd, 1.0, None) or ())) + return r.AnalysisRoute( + r.SIMULATED, + "Both plans' npv_distribution runs from one seed, a component in " + "the same place in both drawing the same random numbers (as for " + "compare), each run's difference priced.", + engine=npv_route.engine, + engine_reason=npv_route.engine_reason, + ) + + +def _share(value, name: str) -> float: + number = checks.number_or_nan(value) + if not (0.0 < number <= 1.0): + raise ValueError( + f"{name} must be a share of the runs, more than 0 and at most " + f"1; got {value!r}." + ) + return number + + +def _contract(contract) -> Optional[AvailabilityContract]: + if contract is None or isinstance(contract, AvailabilityContract): + return contract + if isinstance(contract, dict): + return AvailabilityContract.from_dict(contract) + raise TypeError( + "contract must be an AvailabilityContract (or its to_dict()), or " + f"None; got {type(contract).__name__}." + ) + + +def _settings(rbd, horizon, money, contract, mc_samples): + """The checked settings both methods share.""" + horizon = _npv._number(horizon, "horizon", strict=True) + contract = _contract(contract) + ends = ( + None if contract is None else np.array(contract.period_ends(horizon)) + ) + if not money.earns and contract is None: + _requirements._require_costs(rbd) + n = checks.whole_number( + 10_000 if mc_samples is None else mc_samples, "mc_samples" + ) + return horizon, contract, ends, n + + +def _seed(seed): + # The run is made in parts, which share a seed: drawn here (from + # numpy's global RNG) if not given, and kept in the result to repeat + # the run. + return _streams.shared_seed(checks.seed(seed)) + + +def priced_chunk( + rbd, + horizon: float, + ends: np.ndarray, + money, + size: int, + seed: int, + engine: str, + first: int, + state, +): + """Simulations ``first`` to ``first + size - 1`` of the run ``seed`` + seeds, over ``horizon``, priced (``_pricing.priced``, by the periods + ending at ``ends``, valued by ``money``, an ``_npv.Money``) with each + shutdown's cost at its starts: the + ledger, the runs (a ``TimelineSimulation``).""" + from repyability.rbd import _timeline_runs + + runs, hidden = _timeline_runs.simulate( + rbd, + horizon, + size, + seed, + None, + None, + False, + engine, + None, + first, + state, + hidden=True, + ) + logs = {node: runs.components[node]._data for node in rbd.costs} + ledger = _pricing.priced( + rbd, + logs, + runs.system._data, + ends, + money, + (), + size, + hidden=hidden if rbd._shutdowns else None, + ) + for shut in rbd._shutdowns.values(): + # Its cost at each start, in every run (as the loop charges it). + starts = shut.starts(horizon) + ledger.events( + np.repeat(np.arange(size), starts.size), + np.tile(starts, size), + shut.cost, + "shutdown", + None, + money.growth("shutdown"), + ) + return ledger, runs + + +def _up_by_period(system, ends: np.ndarray, size: int) -> np.ndarray: + """Each history's availability in each period ending at ``ends``: the + share of the period it was up, ``(size, periods)``.""" + history, a, b = _pricing.spans(system, up=True) + starts = np.concatenate(([0.0], ends[:-1])) + out = np.zeros((size, ends.size)) + for k, (lo, hi) in enumerate(zip(starts, ends)): + inside = np.clip(np.minimum(b, hi) - np.maximum(a, lo), 0.0, None) + out[:, k] = np.bincount(history, inside, minlength=size) + return out / (ends - starts) + + +def npv_distribution( + rbd, + horizon, + *, + discount_rate: float, + value_rate: float, + mc_samples: Optional[int], + seed, + hurdle, + tail: float, + engine: str, + state, + contract=None, + escalation=None, + rates: str = "nominal", + inflation=None, +) -> NPVDistribution: + """See ``RepairableRBD.npv_distribution``.""" + escalation = _npv.own_escalation(rbd, escalation) + money = _npv.Money( + rbd, discount_rate, value_rate, escalation, rates, inflation + ) + horizon, contract, ends, n = _settings( + rbd, horizon, money, contract, mc_samples + ) + # The runs end at a retirement, and every run credits the salvage. + end = _npv.own_end(rbd, horizon, money) + if end[0] < horizon: + horizon, contract, ends, n = _settings( + rbd, end[0], money, contract, mc_samples + ) + if hurdle is not None: + hurdle = checks.number_or_nan(hurdle) + if not math.isfinite(hurdle): + raise ValueError( + f"hurdle must be a finite number; got {hurdle!r}." + ) + tail = _share(tail, "tail") + checks.one_of("engine", engine, ("auto", "python", "numba")) + seed = _seed(seed) + _require_priceable(rbd) + return _priced_runs( + rbd, + horizon, + money, + contract, + ends, + n, + seed, + engine, + state, + hurdle, + tail, + end, + ) + + +def _priced_runs( + rbd, + horizon: float, + money, + contract: Optional[AvailabilityContract], + contract_ends: Optional[np.ndarray], + n: int, + seed: int, + engine: str, + state, + hurdle: Optional[float], + tail: float, + end=None, +) -> NPVDistribution: + """The ``n`` runs of ``seed``, priced (settings checked); ``end``, + ``_npv.own_end``'s, credits each run the salvage.""" + salvage, plain_salvage, retired = ( + (0.0, 0.0, False) if end is None else (end[1], end[2], end[3]) + ) + ends = np.array([horizon]) + present: Dict[Tuple[str, Any], np.ndarray] = {} + nominal: Dict[Tuple[str, Any], np.ndarray] = {} + available = ( + None if contract_ends is None else np.zeros((n, contract_ends.size)) + ) + used = None + for first in range(0, n, _CHUNK): + size = min(_CHUNK, n - first) + ledger, runs = priced_chunk( + rbd, + horizon, + ends, + money, + size, + seed, + engine, + first, + state, + ) + used = used or runs.engine + for key, (pv, plain) in ledger.totals().items(): + present.setdefault(key, np.zeros(n))[first : first + size] = pv + nominal.setdefault(key, np.zeros(n))[first : first + size] = plain + if available is not None: + assert contract_ends is not None + available[first : first + size] = _up_by_period( + runs.system._data, contract_ends, size + ) + + zero = np.zeros(n) + values = present.pop(("value", None), zero) + plain_value = nominal.pop(("value", None), zero) + costs = np.zeros(n) + plain_cost = 0.0 + by_category: Dict[str, float] = {} + by_component: Dict[Hashable, float] = {} + + def add(category: str, node, amount: float) -> None: + by_category[category] = by_category.get(category, 0.0) + amount + if node is not None: + by_component[node] = by_component.get(node, 0.0) + amount + + for node, price in rbd.acquisition_costs.items(): + if price: + costs += float(price) + plain_cost += float(price) + add("acquisition", node, float(price)) + for (category, node), amounts in present.items(): + costs += amounts + plain_cost += float(nominal[(category, node)].mean()) + add(category, node, float(amounts.mean())) + + paid = zero + plain_paid = 0.0 + if contract is not None: + assert available is not None and contract_ends is not None + payments = contract.payoff(available) + # Its payments grow only with the inflation of real rates. + lift = money.growth() + paid = payments @ np.exp(-(money.rate - lift) * contract_ends) + plain_paid = float( + (payments @ np.exp(lift * contract_ends)).mean() + if lift + else payments.sum(axis=1).mean() + ) + + samples = values - costs + paid + salvage + ordered = np.sort(samples) + worst = max(1, math.ceil(round(tail * n, 9))) + priced_at_mean: List[Hashable] = [ + node + for node, node_costs in rbd.costs.items() + if any(not isinstance(c, float) for c in node_costs.values()) + ] + plain_value_mean = float(plain_value.mean()) + return NPVDistribution( + horizon=horizon, + discount_rate=money.given_rate, + value_rate=money.value_rate, + samples=samples, + value_samples=values, + cost_samples=costs, + mean=float(samples.mean()), + value=float(values.mean()), + cost=float(costs.mean()), + undiscounted_npv=( + plain_value_mean - plain_cost + plain_paid + plain_salvage + ), + undiscounted_value=plain_value_mean, + undiscounted_cost=plain_cost, + cost_by_category=by_category, + cost_by_component=by_component, + p10=_order_statistic(ordered, 0.1), + p50=_order_statistic(ordered, 0.5), + p90=_order_statistic(ordered, 0.9), + hurdle=hurdle, + probability_below_hurdle=( + None if hurdle is None else float(np.mean(samples < hurdle)) + ), + tail=tail, + cvar=float(ordered[:worst].mean()), + n_simulations=n, + seed=seed, + engine=used or engine, + priced_at_mean=priced_at_mean, + contract=None if contract is None else contract.to_dict(), + contract_samples=None if contract is None else paid, + contract_payoff=float(paid.mean()) if contract is not None else 0.0, + undiscounted_contract_payoff=plain_paid, + period_ends=( + None + if contract_ends is None + else [float(e) for e in contract_ends] + ), + period_availability=available, + salvage=salvage, + undiscounted_salvage=plain_salvage, + retire_at=horizon if retired else None, + **money.stated(), + ) + + +def _unmatched(rbd, horizon: float, state) -> Optional[List[Hashable]]: + """The components of ``rbd`` whose draws do not all come from a + stream of their own (so cannot be matched with another plan's), or + None if every draw does.""" + from repyability.rbd import _curves, _event_loop + from repyability.rbd.repairable_rbd import RepairableRBD + + states = _curves._simulation_states(rbd, state) + specs, complete = _event_loop._stream_specs(rbd, horizon, states=states) + if complete: + return None + named = [] + for name, component in rbd.components.items(): + if type(component) is RepairableRBD: + if not _event_loop._stream_specs( + component, horizon, (name,), {}, states.get(name) + )[1]: + named.append(name) + continue + own = [path for path, _ in specs if path[:1] == (name,)] + duration = _event_loop._duration_model(rbd, name) + if not own or ( + duration is not None and ((name,), _streams.DURATION) not in specs + ): + named.append(name) + return named + + +def _require_matched(rbd, which: str, horizon: float, state) -> None: + from repyability.rbd._runs import _UNSTREAMED + + named = _unmatched(rbd, horizon, state) + if named is None: + return + whose = f" (components {', '.join(map(repr, named))})" if named else "" + raise NotImplementedError( + f"The runs of {which} cannot be matched with the other plan's" + f"{whose}: {_UNSTREAMED} Compare their npv_distribution results " + "run independently instead, or model those components with " + "surpyval parametric distributions." + ) + + +def _own(escalation, rbd, other): + """``escalation`` without the components only ``other`` has.""" + if not isinstance(escalation, dict): + return escalation + return { + key: rate + for key, rate in escalation.items() + if key in rbd.components or key not in other.components + } + + +def compare_npv( + rbd, + other, + horizon, + *, + discount_rate: float, + value_rate: float, + contract, + mc_samples: Optional[int], + seed, + confidence: float, + engine: str, + state, + escalation=None, + rates: str = "nominal", + inflation=None, +) -> NPVComparison: + """See ``RepairableRBD.compare_npv``.""" + from repyability.rbd.repairable_rbd import RepairableRBD + + if not isinstance(other, RepairableRBD): + raise TypeError( + "other must be a RepairableRBD, the plan to compare with; got " + f"{type(other).__name__}." + ) + # Each plan's own: an escalation may name a component of either plan, + # which the other leaves out. + monies = [ + _npv.Money( + d, + discount_rate, + value_rate, + _npv.own_escalation(d, _own(escalation, d, o)), + rates, + inflation, + ) + for d, o in ((rbd, other), (other, rbd)) + ] + settings = [ + _settings(d, horizon, money, contract, mc_samples) + for d, money in zip((rbd, other), monies) + ] + # Each plan's runs end at its own retirement, crediting its salvage. + ends_of = [ + _npv.own_end(d, s[0], money) + for d, s, money in zip((rbd, other), settings, monies) + ] + settings = [ + _settings(d, end[0], money, contract, mc_samples) if end[3] else s + for d, s, money, end in zip((rbd, other), settings, monies, ends_of) + ] + n = settings[0][3] + montecarlo.check_confidence(confidence) + checks.one_of("engine", engine, ("auto", "python", "numba")) + seed = _seed(seed) + for diagram, which, s in zip( + (rbd, other), ("this plan", "the other plan"), settings + ): + _require_priceable(diagram) + _require_matched(diagram, which, s[0], state) + this, that = ( + _priced_runs( + diagram, + s[0], + money, + s[1], + s[2], + n, + seed, + engine, + state, + None, + 0.1, + end, + ) + for diagram, money, s, end in zip( + (rbd, other), monies, settings, ends_of + ) + ) + differences = this.samples - that.samples + estimate = float(differences.mean()) + se = montecarlo.standard_error(differences, False) + apart = math.sqrt( + montecarlo.standard_error(this.samples, False) ** 2 + + montecarlo.standard_error(that.samples, False) ** 2 + ) + z = montecarlo.z_value(confidence) + return NPVComparison( + differences=differences, + mean=estimate, + interval=ConfidenceInterval( + estimate=estimate, + lower=estimate - z * se, + upper=estimate + z * se, + confidence=confidence, + standard_error=se, + n_samples=n, + method="simulated", + ), + probability_other_better=float(np.mean(differences < 0.0)), + independent_standard_error=apart, + this=this, + other=that, + n_simulations=n, + seed=seed, + ) diff --git a/repyability/rbd/_plan_actual.py b/repyability/rbd/_plan_actual.py index beb8ff4a..1374190e 100644 --- a/repyability/rbd/_plan_actual.py +++ b/repyability/rbd/_plan_actual.py @@ -35,84 +35,11 @@ import numpy as np -from repyability.rbd import _npv, _requirements -from repyability.rbd._common import _discount_rate +from repyability.rbd import _npv, _pricing, _requirements from repyability.rbd._model_utils import is_fixed_probability -from repyability.rbd._spec import _mean_cost -from repyability.rbd._tally import _CATEGORIES from repyability.rbd.node_state import NodeState from repyability.rbd.results import ExpectedNPV, PlanVsActual - -_ORDER = { - name: i - for i, name in enumerate(("acquisition",) + _CATEGORIES + ("value",)) -} - -#: Why a cost the log does not determine is left out of the comparison. -_UNITS = ( - "A standby group's log is the group's: its units' failures, which " - "are charged, are not in it." -) -_HIDDEN = ( - "A hidden failure is charged when a test finds it, which the log " - "does not record." -) -_TESTS = "Tests that find nothing leave no outage in the log." -_INSPECTIONS = "Inspections that replace nothing leave no outage in the log." -_INSTANT = ( - "Its planned replacements take no time, so they leave no outage in " - "the log." -) -_CALENDAR = ( - "Its calendar policy prices each planned replacement at its " - "opportunity, which the log does not record." -) -_REPLACED = ( - "It is replaced, rather than repaired, at failures counted from its " - "last renewal, which the log does not mark." -) -_SETUP = ( - "A set-up cost is charged at each stop of a maintenance group, which " - "includes renewals the log does not mark." -) -_BOUGHT = "Paid at the start: the log does not record purchases." - - -def _not_compared(rbd) -> List[Tuple[str, Optional[Hashable], str]]: - """The priced cells, ``(category, component, reason)``, that the log - does not determine (see the module's notes), by the diagram's kinds - of component alone.""" - out: List[Tuple[str, Optional[Hashable], str]] = [] - for node, costs in rbd.costs.items(): - failure = [k for k in ("repair_cost", "replace_cost") if k in costs] - if node in rbd._standby: - out += [(k[:-5], node, _UNITS) for k in failure] - elif node in rbd._inspection: - out += [(k[:-5], node, _HIDDEN) for k in failure] - else: - imperfect = rbd._imperfect.get(node) - if ( - imperfect is not None - and imperfect.replace_after is not None - and "replace_cost" in costs - ): - out.append(("replace", node, _REPLACED)) - if node in rbd._inspection and "inspection_cost" in costs: - out.append(("inspection", node, _TESTS)) - schedule = rbd._preventive.get(node) - if schedule is not None: - if schedule.policy == "calendar": - out.append(("preventive", node, _CALENDAR)) - elif schedule.duration is None and "preventive_cost" in costs: - out.append(("preventive", node, _INSTANT)) - if "inspection_cost" in costs: - out.append(("inspection", node, _INSPECTIONS)) - if any(spec.setup_cost for spec in rbd._maintenance.values()): - out.append(("setup", None, _SETUP)) - for node, price in rbd.acquisition_costs.items(): - if price: - out.append(("acquisition", node, _BOUGHT)) - return out +from repyability.value.value_schedule import ValueSchedule def _log_state_refusal(rbd, node) -> Optional[str]: @@ -213,6 +140,29 @@ def _require_log_states(rbd, given=()) -> None: raise NotImplementedError(reason) +def _require_no_plans(rbd) -> None: + """Raise if a component is replaced at the times of a plan, which + are counted from 0: the rest from today is valued on the same + diagram from today, where they would be counted again.""" + if rbd._upgrades: + raise NotImplementedError( + f"{_requirements._upgraded(rbd)}, counted from 0, which the " + "rest from today is not valued with yet: value the plan with " + "expected_npv, and the rest on a diagram whose upgrade is at " + "the time still to come, counted from today (or, once it is " + "past, with the new life), with expected_npv(state=)." + ) + planned = _requirements._planned(rbd) + if planned: + raise NotImplementedError( + f"Component {planned[0]!r} is replaced at the times of a plan " + "(replace_at), counted from 0, which the rest from today is " + "not valued with yet: value the plan with expected_npv, and " + "the rest on a diagram whose replace_at holds the times still " + "to come, counted from today, with expected_npv(state=)." + ) + + def route(rbd, npv_route): """``plan_vs_actual``'s route: ``expected_npv``'s (it values the plan and the rest from today with it), unless a component's state now is @@ -221,6 +171,9 @@ def route(rbd, npv_route): if npv_route.route == r.REFUSED: return npv_route + planned = r.refusal(lambda: _require_no_plans(rbd)) + if planned: + return r.refused(planned) for node in rbd.components: reason = _log_state_refusal(rbd, node) if reason is not None: @@ -348,147 +301,21 @@ def _states_now(rbd, logs, now, given, start_state) -> Tuple[dict, list]: # -- pricing a log ---------------------------------------------------------- -def _discounted_span(a, b, rate: float): - """The integral of ``exp(-rate t)`` from ``a`` to ``b``.""" - a, b = np.asarray(a, float), np.asarray(b, float) - if not rate: - return b - a - return np.exp(-rate * a) * -np.expm1(-rate * (b - a)) / rate - - -class _Ledger: - """Amounts by (period, category, component), present and - undiscounted, as costs (positive) or value.""" - - def __init__(self, ends: np.ndarray, rate: float): - self.ends = ends - self.starts = np.concatenate(([0.0], ends[:-1])) - self.rate = rate - self.cells: Dict[tuple, List[float]] = {} - - def _add(self, k: int, category, component, present, nominal) -> None: - cell = self.cells.setdefault((k, category, component), [0.0, 0.0]) - cell[0] += float(present) - cell[1] += float(nominal) - - def events(self, times, price: float, category, component) -> None: - """``price`` charged at each of ``times``.""" - times = np.asarray(times, float) - if not price or not times.size: - return - periods = np.searchsorted(self.ends, times, side="right") - periods = np.minimum(periods, len(self.ends) - 1) - present = price * np.exp(-self.rate * times) - for k in np.unique(periods): - mask = periods == k - self._add( - int(k), - category, - component, - present[mask].sum(), - price * mask.sum(), - ) - - def spans(self, spans, per_time: float, category, component) -> None: - """``per_time`` over each span, ``(start, stop)`` rows.""" - spans = np.asarray(spans, float).reshape(-1, 2) - if not per_time or not spans.size: - return - for k, (lo, hi) in enumerate(zip(self.starts, self.ends)): - a = np.maximum(spans[:, 0], lo) - b = np.minimum(spans[:, 1], hi) - inside = b > a - if not np.any(inside): - continue - a, b = a[inside], b[inside] - self._add( - k, - category, - component, - per_time * _discounted_span(a, b, self.rate).sum(), - per_time * (b - a).sum(), - ) - - def rows(self) -> List[Dict[str, Any]]: - out = [] - for (k, category, component), (present, nominal) in self.cells.items(): - sign = 1.0 if category == "value" else -1.0 - out.append( - _row( - k + 1, - self.starts[k], - self.ends[k], - category, - component, - sign * present, - sign * nominal, - ) - ) - return _sorted(out) - - -def _row(period, start, end, category, component, present, nominal) -> dict: - return { - "period": int(period), - "start": float(start), - "end": float(end), - "category": category, - "component": component, - "present_value": float(present), - "undiscounted": float(nominal), - } - - -def _sorted(rows: List[dict]) -> List[dict]: - return sorted( - rows, - key=lambda r: ( - r["period"], - _ORDER.get(r["category"], len(_ORDER)), - str(r["component"]), - ), - ) - - -def _priced_log( - rbd, logs, ends: np.ndarray, rate: float, value_rate: float, skip -) -> List[dict]: +def _priced_log(rbd, logs, ends: np.ndarray, money, skip) -> List[dict]: """The cash flows the logs imply over ``[0, ends[-1]]``, by period, category and component, priced with the diagram's costs (a cost drawn from a distribution at its mean) at the times they fell, but for the - cells in ``skip``, ``{(category, component)}``.""" + cells in ``skip``, ``{(category, component)}``, valued by ``money`` + (an ``_npv.Money``, see ``_pricing``).""" from repyability.timelines import _system_timeline - ledger = _Ledger(ends, rate) - for node, costs in rbd.costs.items(): - log = logs[node] - changes, planned = log.changes, log.planned - after_up = np.arange(changes.size) % 2 == (0 if not log.up else 1) - down = ~after_up - failures = changes[down & ~planned] - outages = changes[down & planned] - charges = [("repair_cost", "repair", failures)] - if node not in rbd._imperfect: - charges.append(("replace_cost", "replace", failures)) - charges.append(("preventive_cost", "preventive", outages)) - for key, category, times in charges: - if key in costs and (category, node) not in skip: - ledger.events(times, _mean_cost(costs[key]), category, node) - rate_down = costs.get("downtime_cost", 0.0) - if rate_down: - ledger.spans( - log.down_intervals, rate_down, "component_downtime", node - ) - if rbd.downtime_cost_rate or value_rate: - system = _system_timeline(rbd, logs) - ledger.spans( - system.down_intervals, - rbd.downtime_cost_rate, - "system_downtime", - None, - ) - ledger.spans(system.up_intervals, value_rate, "value", None) - return ledger.rows() + system = ( + _system_timeline(rbd, logs)._data + if rbd.downtime_cost_rate or money.earns + else None + ) + data = {node: logs[node]._data for node in rbd.costs} + return _pricing.priced(rbd, data, system, ends, money, skip).rows() # -- the analysis ----------------------------------------------------------- @@ -557,7 +384,7 @@ def _variance(actual: List[dict], expected: List[dict]) -> List[dict]: key = (r["period"], r["category"], r["component"]) cell = cells.setdefault( key, - _row( + _pricing.row( r["period"], r["start"], r["end"], @@ -569,13 +396,36 @@ def _variance(actual: List[dict], expected: List[dict]) -> List[dict]: ) cell["present_value"] += sign * r["present_value"] cell["undiscounted"] += sign * r["undiscounted"] - return _sorted(list(cells.values())) + return _pricing.sort_rows(list(cells.values())) def _total(rows, key: str = "present_value") -> float: return float(sum(r[key] for r in rows)) +def _from(value_rate, now: float): + """The value earned from ``now`` on its own clock: a schedule's steps + from then (the step in force at ``now`` from 0), or the rate.""" + if not isinstance(value_rate, ValueSchedule): + return value_rate + times = np.asarray(value_rate.times) + later = times > now + first = int(np.flatnonzero(~later)[-1]) + return ValueSchedule( + np.concatenate(([0.0], times[later] - now)), + np.concatenate( + ([value_rate.rates[first]], np.asarray(value_rate.rates)[later]) + ), + ) + + +def _row_growth(money, category: str, component) -> float: + """The growth of a cash-flow row's stream (see ``_npv.Money``).""" + if component is None or category in ("value", "salvage"): + return money.growth(category) + return money.growth(component, category) + + def plan_vs_actual( rbd, timelines, @@ -583,14 +433,26 @@ def plan_vs_actual( horizon, *, discount_rate: float, - value_rate: float, + value_rate, periods, method: str, state, start_state, + escalation=None, + rates: str = "nominal", + inflation=None, ) -> PlanVsActual: """See ``RepairableRBD.plan_vs_actual``.""" - rate = _discount_rate(discount_rate) + escalation = _npv.own_escalation(rbd, escalation) + money = _npv.Money( + rbd, discount_rate, value_rate, escalation, rates, inflation + ) + valued = dict( + discount_rate=money.given_rate, + escalation=escalation, + rates=rates, + inflation=inflation, + ) now = _npv._number(now, "now", strict=True) horizon = _npv._number(horizon, "horizon", strict=True) if math.isclose(now, horizon, rel_tol=1e-12): @@ -600,7 +462,18 @@ def plan_vs_actual( f"now ({now:g}) is past the horizon ({horizon:g}): the plan " "ends before today." ) - value_rate = _npv._number(value_rate, "value_rate", strict=False) + # 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( @@ -616,14 +489,15 @@ def plan_vs_actual( plan = _npv.expected_npv( rbd, horizon, - discount_rate=rate, value_rate=value_rate, + **valued, periods=ends, working_nodes=None, broken_nodes=None, method=method, state=start_state, ) + _require_no_plans(rbd) given = dict(state or {}) states, derived = _states_now(rbd, logs, now, given, start_state) so_far = int(np.searchsorted(ends, now, side="right")) @@ -636,8 +510,8 @@ def plan_vs_actual( _npv.expected_npv( rbd, horizon - now, - discount_rate=rate, - value_rate=value_rate, + value_rate=_from(value_rate, now), + **valued, periods=rest_ends, working_nodes=None, broken_nodes=None, @@ -646,29 +520,31 @@ def plan_vs_actual( ) ) - left_out = _not_compared(rbd) + left_out = _pricing.unrecorded(rbd) skip = {(category, node) for category, node, _ in left_out} before = [r for r in plan.cash_flows if r["period"] <= so_far] expected = [ r for r in before if (r["category"], r["component"]) not in skip ] as_planned = [r for r in before if (r["category"], r["component"]) in skip] - actual = _priced_log(rbd, logs, ends[:so_far], rate, value_rate, skip) + actual = _priced_log(rbd, logs, ends[:so_far], money, skip) variance = _variance(actual, expected) - back = math.exp(-rate * now) rest_rows = [] if rest is not None: for r in rest.cash_flows: + # The rest's amounts are from now: each stream grown to now + # and discounted back to the start. + g = _row_growth(money, r["category"], r["component"]) rest_rows.append( - _row( + _pricing.row( r["period"] + so_far, r["start"] + now, r["end"] + now, r["category"], r["component"], - r["present_value"] * back, - r["undiscounted"], + r["present_value"] * math.exp(-(money.rate - g) * now), + r["undiscounted"] * math.exp(g * now), ) ) by_category: Dict[str, float] = {} @@ -689,8 +565,8 @@ def plan_vs_actual( return PlanVsActual( now=now, horizon=horizon, - discount_rate=rate, - value_rate=value_rate, + discount_rate=money.given_rate, + value_rate=money.value_rate, plan_npv=plan.npv, revalued_npv=revalued, change=revalued - plan.npv, @@ -719,4 +595,5 @@ def plan_vs_actual( derived_states=derived, plan=plan, rest=rest, + **money.stated(), ) diff --git a/repyability/rbd/_point_availability.py b/repyability/rbd/_point_availability.py index d7fa55c8..0c20ef69 100644 --- a/repyability/rbd/_point_availability.py +++ b/repyability/rbd/_point_availability.py @@ -2209,6 +2209,126 @@ def atoms(self, stop: float) -> Atoms: return Atoms(*kept) +class PlanCurve: + """A unit replaced at the times of a plan (its spec's + ``"replace_at"``), and after the last no more: ``stretches``, one + ``BlockCurve`` of a single interval for each stretch from one time to + the next (see ``_block_replacement.plan_availability``), the first + from 0 and the ``k``-th from ``starts[k]``. The last stretch reaches + as far as the curve was asked for; past its end the curve holds its + value there.""" + + #: Replaced no more after its plan's last time, it has no period, and + #: is followed as far as it is asked for. + settle = np.inf + period = None + + def __init__(self, stretches: list, starts): + self.stretches = stretches + self.starts = np.asarray(starts, dtype=float) + self.lengths = np.array([s.interval for s in stretches]) + self.end = float(self.starts[-1] + self.lengths[-1]) + # Each stretch's events by its end, and all those before it. + totals = [s.events(np.array([s.interval])) for s in self.stretches] + self._before = { + key: np.concatenate( + [[0.0], np.cumsum([float(t[key][0]) for t in totals])] + ) + for key in totals[0] + } + + def _each(self, x: np.ndarray, value: Callable) -> np.ndarray: + """``value(stretch, s, k)`` for the times ``x`` in each stretch, + ``s`` after its start (short of its end, where the next begins).""" + x = np.asarray(x, dtype=float) + out = np.empty(x.shape) + last = len(self.stretches) - 1 + k = np.clip(np.searchsorted(self.starts, x, side="right") - 1, 0, last) + for index in np.unique(k): + inside = k == index + length = self.lengths[index] + s = np.clip( + x[inside] - self.starts[index], 0.0, np.nextafter(length, 0.0) + ) + out[inside] = value(self.stretches[index], s, index) + return out + + def at(self, x: np.ndarray) -> np.ndarray: + return self._each(x, lambda stretch, s, _: stretch.at(s)) + + def failed_at(self, x: np.ndarray) -> np.ndarray: + """Each stretch's probability of being in a repair.""" + return self._each(x, lambda stretch, s, _: stretch.failed_at(s)) + + def derivative(self, x: np.ndarray, scale: float) -> np.ndarray: + """Each stretch's rate of change (see ``BlockCurve.derivative``).""" + return self._each( + x, lambda stretch, s, _: stretch.derivative(s, scale) + ) + + def events(self, x: np.ndarray) -> Dict[str, np.ndarray]: + """The unit's expected events before each time ``x`` (see + ``GridCurve.events``): those of the stretches before its own, and + its own stretch's up to it (the replacement at a time of the plan + is its stretch's first event, counted after that time).""" + x = np.minimum(np.asarray(x, dtype=float), self.end) + last = len(self.stretches) - 1 + k = np.clip(np.searchsorted(self.starts, x, side="right") - 1, 0, last) + out = {key: before[k] for key, before in self._before.items()} + for index in np.unique(k): + inside = k == index + s = np.clip( + x[inside] - self.starts[index], 0.0, self.lengths[index] + ) + own = self.stretches[index].events(s) + for key in out: + out[key][inside] += own[key] + return out + + def atoms(self, stop: float) -> Atoms: + """The replacements at the plan's times before ``stop`` (see + ``Atoms``).""" + parts = [ + Atoms(own.times + start, *own[1:]) + for own, start in ( + (stretch.atoms(min(stop - start, stretch.interval)), start) + for stretch, start in zip(self.stretches, self.starts) + if start < stop + ) + ] + if not parts: + return Atoms.none() + return Atoms(*(np.concatenate(column) for column in zip(*parts))) + + def _joined(self, start: float, stop: float, times_of) -> np.ndarray: + """``times_of(stretch, a, b)`` of each stretch within ``[start, + stop]``, with the plan's times.""" + parts = [self.starts, np.array([self.end])] + for stretch, begin in zip(self.stretches, self.starts): + a = max(start - begin, 0.0) + b = min(stop - begin, stretch.interval) + if a <= b: + parts.append(times_of(stretch, a, b) + begin) + times = np.concatenate(parts) + return times[(times >= start) & (times <= stop)] + + def knots(self, start: float, stop: float) -> np.ndarray: + return self._joined(start, stop, lambda curve, a, b: curve.knots(a, b)) + + def breaks(self, start: float, stop: float) -> np.ndarray: + return self._joined(start, stop, curve_breaks) + + def grids(self) -> list: + """Each stretch's grid, to its end (see ``curve_grids``), the + earliest last (``_rates.differences`` takes the last that + applies).""" + ends = self.starts + self.lengths + return [ + (stretch.step, float(end)) + for stretch, end in zip(self.stretches[::-1], ends[::-1]) + ] + + class StartedBlockCurve: """A unit under block replacement started from a state: ``head``, its own curve up to its first block time, ``length`` after the start, and diff --git a/repyability/rbd/_pricing.py b/repyability/rbd/_pricing.py new file mode 100644 index 00000000..e0fb41a0 --- /dev/null +++ b/repyability/rbd/_pricing.py @@ -0,0 +1,239 @@ +"""Up/down histories priced with a diagram's own costs: each failure its +repair and replace costs, each planned outage its preventive cost, each +component's and the system's time down their downtime costs, the repair +crews' salaries over the whole time and the system's time up its value +(a rate, or each step's of a ``ValueSchedule``), each grown at its +stream's escalation (``price * exp(g t)``) and discounted at the time it +fell (a rate over a span exactly), by period, category and component, +and history by history. + +``plan_vs_actual`` prices one history (an outage log, ``_plan_actual``) +and ``npv_distribution`` every simulated one (``_npv_runs``); what a +history does not determine (a cost charged at an event it does not +record) is each caller's to leave out or refuse. +""" + +from typing import Any, Hashable, List, Mapping, Optional, Tuple + +import numpy as np + +from repyability.rbd._common import _crew_salaries +from repyability.rbd._spec import _mean_cost +from repyability.value._flows import ( # noqa: F401 + ORDER, + Ledger, + row, + sort_rows, +) +from repyability.value._rates import discounted_span # noqa: F401 + +#: Why a cost the log does not determine is left out of the comparison. +_UNITS = ( + "A standby group's log is the group's: its units' failures, which " + "are charged, are not in it." +) +_HIDDEN = ( + "A hidden failure is charged when a test finds it, which the log " + "does not record." +) +_TESTS = "Tests that find nothing leave no outage in the log." +_INSPECTIONS = "Inspections that replace nothing leave no outage in the log." +_INSTANT = ( + "Its planned replacements take no time, so they leave no outage in " + "the log." +) +_CALENDAR = ( + "Its calendar policy prices each planned replacement at its " + "opportunity, which the log does not record." +) +_REPLACED = ( + "It is replaced, rather than repaired, at failures counted from its " + "last renewal, which the log does not mark." +) +_SETUP = ( + "A set-up cost is charged at each stop of a maintenance group, which " + "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]]: + """The priced cells, ``(category, component, reason)``, that an + up/down history does not determine (see ``_plan_actual``'s notes), by + the diagram's kinds of component alone.""" + out: List[Tuple[str, Optional[Hashable], str]] = [] + for node, costs in rbd.costs.items(): + failure = [k for k in ("repair_cost", "replace_cost") if k in costs] + if node in rbd._standby: + out += [(k[:-5], node, _UNITS) for k in failure] + elif node in rbd._inspection: + out += [(k[:-5], node, _HIDDEN) for k in failure] + else: + imperfect = rbd._imperfect.get(node) + if ( + imperfect is not None + and imperfect.replace_after is not None + and "replace_cost" in costs + ): + out.append(("replace", node, _REPLACED)) + if node in rbd._inspection and "inspection_cost" in costs: + out.append(("inspection", node, _TESTS)) + schedule = rbd._preventive.get(node) + if schedule is not None: + if schedule.policy == "calendar": + out.append(("preventive", node, _CALENDAR)) + elif schedule.duration is None and "preventive_cost" in costs: + out.append(("preventive", node, _INSTANT)) + if "inspection_cost" in costs: + out.append(("inspection", node, _INSPECTIONS)) + if any(spec.setup_cost for spec in rbd._maintenance.values()): + out.append(("setup", None, _SETUP)) + 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 + + +def changes(data) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + """Each change of the histories ``data`` (a ``timelines._Data``): its + history, its time, whether it is a change down, and whether planned.""" + history, j = data.positions + up_after = (data.start[history].astype(np.int64) ^ ((j + 1) & 1)) == 1 + return history, data.times, ~up_after, data.planned + + +def spans(data, up: bool) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: + """The spans up (or down) of the histories ``data``: each span's + history, start and stop.""" + history, j = data.positions + times = data.times + previous = np.zeros(times.size) + later = j > 0 + previous[later] = times[np.flatnonzero(later) - 1] + up_before = (data.start[history].astype(np.int64) ^ (j & 1)) == 1 + counts = np.diff(data.offsets) + last = np.zeros(data.size) + some = counts > 0 + last[some] = times[data.offsets[1:][some] - 1] + final_up = (data.start.astype(np.int64) ^ (counts & 1)) == 1 + chosen = up_before == up + final = final_up == up + return ( + np.concatenate((history[chosen], np.flatnonzero(final))), + np.concatenate((previous[chosen], last[final])), + np.concatenate((times[chosen], np.full(int(final.sum()), data.end))), + ) + + +def priced( + rbd, + logs: Mapping[Any, Any], + system: Optional[Any], + ends: np.ndarray, + money, + skip, + size: int = 1, + hidden: Optional[Mapping[Any, Any]] = None, +) -> Ledger: + """The cash flows the histories imply over ``[0, ends[-1]]``, by + period, category and component, history by history, priced with the + diagram's costs (a cost drawn from a distribution at its mean) at the + times they fell, but for the cells in ``skip``, ``{(category, + component)}``. ``money`` (an ``_npv.Money``) gives the rate, the + value earned (a rate or steps) and each stream's growth: an amount at + ``t`` is its price times ``exp(g t)``. ``logs`` are each component's + histories and ``system`` the system's (``timelines._Data``); + ``system`` is needed only for a system downtime cost or a value. + ``hidden`` gives, under shutdowns, each component's holds and the + changes down they hid + (``_timeline_runs.Hidden``): a hold is no task, and a hidden change + is charged as a recorded one would be.""" + ledger = Ledger(ends, money.rate, size) + for node, costs in rbd.costs.items(): + data = logs[node] + history, times, down, planned = changes(data) + tasks = down & planned + left_out = None if hidden is None else hidden[node] + if left_out is not None: + tasks &= ~left_out.held + history = np.concatenate((history, left_out.history)) + times = np.concatenate((times, left_out.times)) + down = np.concatenate((down, np.ones(left_out.times.size, bool))) + planned = np.concatenate((planned, left_out.planned)) + tasks = np.concatenate((tasks, left_out.planned)) + failures = down & ~planned + charges = [("repair_cost", "repair", failures)] + if node not in rbd._imperfect: + charges.append(("replace_cost", "replace", failures)) + charges.append(("preventive_cost", "preventive", tasks)) + for key, category, mask in charges: + if key in costs and (category, node) not in skip: + ledger.events( + history[mask], + times[mask], + _mean_cost(costs[key]), + category, + node, + money.growth(node, category), + ) + rate_down = costs.get("downtime_cost", 0.0) + if rate_down: + ledger.spans( + *spans(data, up=False), + rate_down, + "component_downtime", + node, + money.growth(node, "component_downtime"), + ) + if rbd.downtime_cost_rate or money.earns: + ledger.spans( + *spans(system, up=False), + rbd.downtime_cost_rate, + "system_downtime", + None, + money.growth("system_downtime"), + ) + history, a, b = spans(system, up=True) + for lo, hi, worth in zip(*money.steps(ledger.ends[-1])): + # Each step of the value earned, over the spans up within it. + inside = (b > lo) & (a < hi) + ledger.spans( + history[inside], + np.maximum(a[inside], lo), + np.minimum(b[inside], hi), + worth, + "value", + None, + money.growth("value"), + ) + for node, upgrade in getattr(rbd, "_upgrades", {}).items(): + # An upgrade's capital cost, at its time, in every history. + if upgrade.cost and ("capital", node) not in skip: + at = np.full(size, upgrade.at) + keep = at < ledger.ends[-1] + ledger.events( + np.arange(size)[keep], + at[keep], + upgrade.cost, + "capital", + node, + money.growth(node, "capital"), + ) + # The repair crews' salaries, the same in every history. + ledger.spans( + np.arange(size), + np.zeros(size), + np.full(size, ledger.ends[-1]), + _crew_salaries(rbd), + "crews", + None, + money.growth("crews"), + ) + return ledger diff --git a/repyability/rbd/_repairable_allocation.py b/repyability/rbd/_repairable_allocation.py index 067e23f5..8eac646c 100644 --- a/repyability/rbd/_repairable_allocation.py +++ b/repyability/rbd/_repairable_allocation.py @@ -31,11 +31,13 @@ from repyability.rbd import ( _ccf_groups, _costs, + _crew_allocation, _crews, _long_run, _requirements, ) from repyability.rbd._common import ( + _crew_salaries, _discount_rate, _horizons, _present_horizon, @@ -61,10 +63,27 @@ if TYPE_CHECKING: from repyability.rbd.repairable_rbd import RepairableRBD +#: What the allocations of availability targets say of limited crews: +#: they move components' own availabilities, which the crews' queue ties +#: together (``allocate_redundancy`` works its copies out with the crews). _ALLOCATION_CREWS = ( - "the allocations assume", - "Compare designs by their long-run values, or simulate them with " - "compare().", + "the allocations of availability targets assume", + "allocate_redundancy chooses copies with the crews; compare other " + "designs by their long-run values, or simulate them with compare().", +) + + +#: What ``allocate_redundancy`` can choose a design by. +OBJECTIVES = ("cost", "npv", "eac") + +#: What a design's net present value is made of (``basis``). +_VALUED = ( + "The copies are bought at the start; the running costs, the cost of " + "the system's downtime and the value earned are their long-run rates " + "over the horizon's present value, as total_cost counts them. " + "Approximate: a system new at 0 fails less and is up more often at " + "first than in the long run; expected_npv values a design drawn out " + "from new." ) @@ -152,11 +171,27 @@ def allocate_redundancy( max_units: Union[int, Dict[Hashable, int], None], method: str, discount_rate: float, + objective: str, + value_rate: float, ) -> TotalCostAllocation: """See ``RepairableRBD.allocate_redundancy``.""" from repyability.rbd.repairable_rbd import RepairableRBD rate = _discount_rate(discount_rate) + one_of("objective", objective, OBJECTIVES) + worth = number_or_nan(value_rate) + if not (math.isfinite(worth) and worth >= 0.0): + raise ValueError( + "value_rate must be a finite number, at least 0 (the value " + f"earned per unit time while the system works); got " + f"{value_rate!r}." + ) + if worth and objective == "cost": + raise ValueError( + "value_rate needs an objective that takes it: " + 'objective="npv" (the net present value over the horizon) or ' + 'objective="eac" (the same as a steady cost per unit time).' + ) if np.ndim(horizon) != 0: raise ValueError( f"horizon must be a number for allocate_redundancy, got " @@ -210,8 +245,27 @@ def allocate_redundancy( ) max_unavailability = 1.0 - target - # Adding copies adds jobs for the crews: the search assumes none waits. - _crews._require_unlimited_crews(rbd, *_ALLOCATION_CREWS) + if rbd._crews_couple(): + # Adding copies adds jobs for the crews: each design is worked + # out whole, from the crews' chain (see _crew_allocation). + _require_crewed_redundancy(rbd, bool(drawn)) + counts, design = _crew_allocation.search( + rbd, chosen, caps, max_unavailability, method, present, worth + ) + return _redundancy_result( + dict(zip(chosen, counts)), + design.acquisition, + design.cost_rate, + design.unavailability, + present, + horizon, + method, + discount_rate, + objective, + worth, + drawn, + _crew_allocation.BASIS, + ) grouped = _require_groups_allocated(rbd, chosen, drawn) # Every node's availability (and unavailability) over the times the # long-run values average over, and each component's own cost. @@ -387,10 +441,21 @@ def train_gain(train): # theirs times the rest's: the exact search is then a dynamic # program over the nodes. series = [(lambda n, q=float(down[node][0]): q**n) for node in chosen] + # A value earned while the system works is a cost of its downtime: + # worth ``v`` a unit time up, a design earns ``v * present * (1 - U)``, + # the same for every design but for ``v * present * U``. So the design + # with the highest net present value (and, over one horizon, the + # lowest equivalent annual cost) is the total cost's with the downtime + # costing ``downtime_cost_rate + v``, and the search's two bounds, + # which hold for any downtime cost, hold as they are: a copy's cost + # is not changed by the value, and its gain is its fall in the + # unavailability times that cost. Discounting changes neither: the + # copies are bought at 0, and every running term is its long-run + # rate times the one ``present`` (which only shrinks with the rate). counts, _, u = lowest_total_cost( unavailability, item_cost, - present * rbd.downtime_cost_rate, + present * (rbd.downtime_cost_rate + worth), [gain(node) for node in chosen] + [train_gain(train) for train in drawn], caps, @@ -416,10 +481,89 @@ def train_gain(train): for node in rbd.components ) + rbd.downtime_cost_rate * u + # The crews' salaries, which the copies do not change. + + _crew_salaries(rbd) ) + return _redundancy_result( + units, + acquisition, + cost_rate, + u, + present, + horizon, + method, + discount_rate, + objective, + worth, + drawn, + ) + + +def _require_crewed_redundancy(rbd, trains: bool = False) -> None: + """Raise unless the redundancy allocation is worked out with limited + repair crews (see ``_crew_allocation``): the crews' chain covers the + diagram, which has no common-cause groups, maintenance groups or + shutdowns, and no ``trains`` are asked for.""" + advice = ( + " Compare designs by their long-run values, or simulate them " + "with compare()." + ) + for found, what in ( + (trains, "copies of whole trains"), + ( + rbd.ccf_groups, + "copies of the diagram's common-cause groups' members, which " + "would join their groups", + ), + (rbd._maintenance, "the diagram's maintenance groups"), + (rbd._shutdowns, "the diagram's shutdowns"), + ): + if found: + raise NotImplementedError( + f"With {rbd.repair_crews} repair crew(s) a copy is one " + "more job that can wait for a crew, so each design is " + "worked out from the crews' Markov chain, which does not " + f"take {what}." + advice + ) + _crews._require_crew_chain(rbd) + + +def _redundancy_result( + units: Dict[Hashable, int], + acquisition: float, + cost_rate: float, + u: float, + present: float, + horizon: float, + method: str, + discount_rate: float, + objective: str, + worth: float, + drawn: list, + basis: Optional[str] = None, +) -> TotalCostAllocation: + """``allocate_redundancy``'s result, from the design found: its + copies, what they cost to buy, its running cost per unit time (the + system's downtime's in it) and its unavailability. ``basis`` says how + the designs were worked out, where that is not from independent + components.""" + total = acquisition + present * cost_rate + valued: Dict[str, Any] = {"basis": basis} if basis else {} + if objective != "cost": + value = worth * present * (1.0 - u) + valued = dict( + objective=objective, + value_rate=worth, + value=value, + running_cost=present * cost_rate, + npv=value - total, + # (Over no time at all, there is no rate to spread it at.) + eac=(total - value) / present if present else math.nan, + basis=_VALUED if basis is None else f"{_VALUED} {basis}", + ) return TotalCostAllocation( units=units, - total_cost=acquisition + present * cost_rate, + total_cost=total, acquisition_cost=acquisition, cost_rate=cost_rate, availability=1.0 - u, @@ -431,6 +575,7 @@ def train_gain(train): if drawn else None ), + **valued, ) diff --git a/repyability/rbd/_repairable_importance.py b/repyability/rbd/_repairable_importance.py index 79e6b47e..c3f226ec 100644 --- a/repyability/rbd/_repairable_importance.py +++ b/repyability/rbd/_repairable_importance.py @@ -162,10 +162,10 @@ def _failure_importance( window, state, ) - if rbd.ccf_groups: - return _ccf_groups._ccf_long_run_measure(rbd, name, working, broken) if rbd._crews_couple(): return _crew_held_importance(rbd, name, working, broken) + if rbd.ccf_groups: + return _ccf_groups._ccf_long_run_measure(rbd, name, working, broken) node_probabilities, node_failures, weights, _ = _importance_probabilities( rbd, working, broken ) @@ -287,7 +287,7 @@ def criticality_importance( window, state, ) - if rbd.ccf_groups: + if _ccf_groups._own_chains(rbd): return _ccf_groups._ccf_long_run_measure( rbd, "criticality", working_nodes, broken_nodes, kind=kind ) @@ -331,7 +331,7 @@ def fussell_vesely( window, state, ) - if rbd.ccf_groups: + if _ccf_groups._own_chains(rbd): return _ccf_groups._ccf_long_run_measure( rbd, "fussell_vesely", @@ -474,7 +474,10 @@ def _crew_rates( independent components, and their jumps are split likewise.""" nested = _curves._require_crew_over_time(rbd, frozenset(working | broken)) chain = _crews._crew_chain(rbd, frozenset(working | broken)) - size, count = len(chain.probabilities), len(chain.nodes) + # (A column for each component, then one for each common-cause + # group's shared causes: see _crew_chain.CrewChain.split.) + keys = _curves._cause_keys(rbd, chain) + size, count = len(chain.probabilities), len(keys) patterns = 2 ** len(nested) ups = [ _curves._crew_vectors( @@ -524,7 +527,7 @@ def importances(values: dict, times: np.ndarray) -> dict: [available[node] for node in nested] ) parts: Dict[Hashable, np.ndarray] = {} - for k, node in enumerate(chain.nodes): + for k, node in enumerate(keys): own = columns[:, patterns + k + count * np.arange(patterns)] parts[node] = np.sum(own * weights, axis=1) importance = importances(available, flat) @@ -866,7 +869,7 @@ def joint_importance( for key, value in (("x", x), ("window", window), ("state", state)) if value is not None } - if rbd.ccf_groups: + if _ccf_groups._own_chains(rbd): # Each pair conditioned on its states through the groups' chains # (#317, see ``RepairableRBD._ccf_measure``), as the other measures # are: refused where their chains do not cover the groups. diff --git a/repyability/rbd/_repairable_routes.py b/repyability/rbd/_repairable_routes.py index 202dd6ea..f681afae 100644 --- a/repyability/rbd/_repairable_routes.py +++ b/repyability/rbd/_repairable_routes.py @@ -6,6 +6,7 @@ """ import dataclasses +import math from functools import partial from typing import ( Dict, @@ -21,6 +22,8 @@ _first_failure, _intervals, _long_run, + _npv, + _npv_runs, _plan_actual, _repairable_allocation, _repairable_capacity, @@ -30,10 +33,12 @@ _runs, _shutdowns, _spares, + _switch_runs, _timeline_runs, _unplanned, ) from repyability.rbd._bayesian_life import PosteriorPredictive +from repyability.rbd._covariate_schedule import on_clock from repyability.rbd._runs import ( # noqa: E402,F401 _UNSTREAMED, failure_criticality_index_per_component_failures, @@ -126,9 +131,17 @@ def from_long_run(route, reason): ) ), ) - # The allocations assume independent components, which limited - # repair crews make them not; the common-cause groups' chains take - # theirs in. + # The allocations of targets assume independent components, which + # limited repair crews make them not (the redundancy allocation works + # each design out from the crews' chain); the common-cause groups' + # chains take theirs in. + redundancy = ( + r.refusal( + partial(_repairable_allocation._require_crewed_redundancy, rbd) + ) + if rbd._crews_couple() + else r.refusal(partial(_ccf_groups._require_ccf_long_run, rbd)) + ) allocation = r.refusal( partial( _crews._require_unlimited_crews, @@ -176,7 +189,7 @@ def from_long_run(route, reason): "The system's availability given each of the pair up " "and down, a common-cause group's members conditioned " "on their states through the groups' chains. " - if rbd.ccf_groups + if _ccf_groups._own_chains(rbd) else "Each component's Birnbaum importance with the " "other held up, less with it held down. " ) @@ -362,6 +375,11 @@ def from_long_run(route, reason): ) else: out["expected_npv"] = uptime + retiring = r.refusal( + lambda: _npv.own_terms(rbd, math.inf, None, None, None) + ) + if retiring is not None: + out["expected_npv"] = r.refused(retiring, tuple(rbd._valuation)) out["plan_vs_actual"] = _plan_actual.route(rbd, out["expected_npv"]) # A group's members' MTTF and MTTR are their group's: the # availability allocations hold them, and a member's copies join its @@ -373,11 +391,18 @@ def from_long_run(route, reason): else "" ) out["allocate_redundancy"] = ( - r.refused(allocation) - if allocation + r.refused(redundancy) + if redundancy else from_long_run( r.EXACT, "A search over the exact long-run values of the candidates." + + ( + " With limited repair crews each candidate's come from " + "the crews' Markov chain of its components and their " + "copies, which queue for the crews together." + if rbd._crews_couple() + else "" + ) + ( " A common-cause group member's copies join its group, " "whose chain takes them in: a BetaFactor group's (an MGL " @@ -439,7 +464,10 @@ def from_long_run(route, reason): else from_long_run( r.NUMERICAL, "An optimiser over the age-replacement intervals, with the " - "exact long-run values at each.", + 'exact long-run values at each (objective="eac": each ' + "component's renewal cycle discounted too, the system's " + 'terms at its long-run availability; objective="npv": ' + "expected_npv over the horizon at each).", ) ) refusal = ( @@ -471,7 +499,10 @@ def from_long_run(route, reason): else from_long_run( r.NUMERICAL, "An optimiser over the inspection interval, with the exact " - "long-run values at each.", + 'long-run values at each (objective="eac": each ' + "component's renewal cycle discounted too, the system's " + 'terms at its long-run availability; objective="npv": ' + "expected_npv over the horizon at each).", ) ) # Spares: each component's replacements, counted as a renewal @@ -591,6 +622,22 @@ def from_long_run(route, reason): engine_reason=why, ) ) + out["npv_distribution"] = _npv_runs.route(rbd, out["simulate_timelines"]) + out["best_switch_time"] = _switch_runs.route(rbd, out["npv_distribution"]) + out["compare_npv"] = _npv_runs.compare_route(out["npv_distribution"], rbd) + out["least_spend_for_downtime"] = ( + out["availability"] + if out["availability"].route == r.REFUSED + else r.AnalysisRoute( + r.SIMULATED, + "Each design's availability runs on one seed, its downtime per " + "run (planned and unplanned) taken against the limit by an " + "upper bound on its risk measure; a greedy search over the " + "levers.", + engine=out["availability"].engine, + engine_reason=out["availability"].engine_reason, + ) + ) engine, why = _runs._engine_choice(rbd, capacity=False) if unpriced: out["cost"] = r.refused(unpriced) @@ -732,12 +779,22 @@ def from_long_run(route, reason): "simulate_chunk", "availability_from_chunks", "shards", + # Each design's availability runs. + "least_spend_for_downtime", ): out[name] = r.refused(meshed) # A run of windows: the exact values over time (the window's own # route), and for the cost its spread simulated from one seeded run. out["expected_events_by_window"] = out["expected_events"] - if out["expected_cost"].route not in (r.EXACT, r.NUMERICAL): + if on_clock(rbd) and out["cost"].route == r.SIMULATED: + out["cost_by_window"] = dataclasses.replace( + out["cost"], + reason="A life on the diagram's clock has no exact values: each " + "window's mean and spread come from the simulations cost runs, " + "one seeded set of histories cut at every window's end.", + twin="", + ) + elif out["expected_cost"].route not in (r.EXACT, r.NUMERICAL): out["cost_by_window"] = out["expected_cost"] elif out["cost"].route == r.REFUSED: out["cost_by_window"] = out["cost"] @@ -789,6 +846,7 @@ def from_long_run(route, reason): ("point_availability_uncertainty", "point_availability"), ("mission_availability_uncertainty", "mission_availability"), ("expected_cost_rate_uncertainty", "expected_cost_rate"), + ("expected_npv_uncertainty", "expected_npv"), ): own = out[method] out[name] = ( @@ -893,4 +951,18 @@ def from_long_run(route, reason): # What the plan does (planned against unplanned, failures avoided): # from the routes above, the plan's and running to failure's. out["maintenance_effect"] = _unplanned.effect_route(rbd, out) + if rbd._upgrades: + # The long run is the diagram's after its upgrades: its methods + # are asked of it (see _long_run.follows_upgrades). + after = _long_run.after_upgrades(rbd).analysis_routes() + for name in _long_run.ROUTED_AFTER_UPGRADES: + route = after[name] + if route.route != r.REFUSED: + route = dataclasses.replace( + route, + reason="The long run once upgraded (each upgraded " + "component with its new life, the time before its " + f"upgrade ignored): {route.reason}", + ) + out[name] = route return r.AnalysisRoutes(sorted(out.items())) diff --git a/repyability/rbd/_repairable_uncertainty.py b/repyability/rbd/_repairable_uncertainty.py index 9d874a60..25b11674 100644 --- a/repyability/rbd/_repairable_uncertainty.py +++ b/repyability/rbd/_repairable_uncertainty.py @@ -44,6 +44,7 @@ import numpy as np from repyability.rbd.results import ( + NPVUncertainty, UncertaintyImportance, UncertaintyResult, ) @@ -668,15 +669,20 @@ def _sensitivities(rbd, of: str, x, state, rel_step) -> dict: return rbd.parameter_sensitivity(**kwargs) -def delta(rbd, of: str, x, state, inputs, groups, rel_step) -> list: +def delta( + rbd, of: str, x, state, inputs, groups, rel_step, derivatives=None +) -> list: """Each input's part of the quantity's variance by the delta method: ``g^T Sigma g`` over its uncertain roles, ``g`` the quantity's derivatives in a role's parameters (``parameter_sensitivity``'s levers, summed over a population's nodes: they move together) and ``Sigma`` - their covariance (see ``uncertainty.varied_parameters``).""" + their covariance (see ``uncertainty.varied_parameters``); or, given, + ``derivatives`` of another quantity, as ``parameter_sensitivity`` + gives them (by key, a mapping of lever names to derivatives).""" from ._model_utils import parametric_spec - derivatives = _sensitivities(rbd, of, x, state, rel_step) + if derivatives is None: + derivatives = _sensitivities(rbd, of, x, state, rel_step) size = int(np.size(x)) if x is not None else 1 def gradient(keys, names) -> np.ndarray: @@ -951,3 +957,158 @@ def shaped(values): first_order={key: shaped(v) for key, v in first.items()}, total={key: shaped(v) for key, v in total.items()}, ) + + +class _LeverDerivatives: + """The derivatives of ``quantity(diagram)`` in the levers of ``rbd``, + as ``parameter_sensitivity`` gives its own (``get(key)``, a mapping of + lever names to derivatives), each worked out when it is asked for, by + the central difference ``parameter_sensitivity`` takes on its + lever (``_sensitivity._difference``).""" + + def __init__(self, rbd, quantity, rel_step: float): + from . import _sensitivity + + self._rbd = rbd + self._quantity = quantity + self._rel_step = rel_step + self._levers: Dict[Any, Dict[str, Any]] = {} + for lever in _sensitivity._levers(rbd): + self._levers.setdefault(lever.key, {})[lever.name] = lever + self._base = quantity(rbd) + + def get(self, key, default=None): + if key not in self._levers: + return default if default is not None else {} + return _OneKey(self, self._levers[key]) + + def derivative(self, lever) -> np.ndarray: + from . import _sensitivity + + def at(value): + changed = _sensitivity._rebuilt(self._rbd, lever, value) + if changed is None: + return None + try: + return self._quantity(changed) + except (ValueError, NotImplementedError): + return None + + return _sensitivity._difference(at, lever, self._rel_step, self._base) + + +class _OneKey(Mapping): + """One key's levers, their derivatives worked out when read.""" + + def __init__(self, owner: _LeverDerivatives, levers: dict): + self._owner = owner + self._levers = levers + self._found: Dict[str, Any] = {} + + def __getitem__(self, name): + if name not in self._found: + self._found[name] = self._owner.derivative(self._levers[name]) + return self._found[name] + + def __iter__(self): + return iter(self._levers) + + def __len__(self): + return len(self._levers) + + +def held_fixed(rbd, inputs: List[Source], groups) -> List[Dict[str, Any]]: + """The models every draw keeps as they are: each component's role + with a model that no input draws, and each common-cause group whose + model is not drawn (role ``"ccf"``, under its members).""" + drawn = { + (node, role) + for item in inputs + for node in item.members + for role in item.specs + } + out: List[Dict[str, Any]] = [] + for node in rbd.components: + if _spec(rbd, node) is None: + continue + for role, model in _models(rbd, node).items(): + if model is not None and (node, role) not in drawn: + out.append({"node": node, "role": role}) + for i, group in enumerate(rbd.ccf_groups): + if i not in groups: + out.append({"node": tuple(group.members), "role": "ccf"}) + return out + + +#: The relative step of a model's parameter the NPV is differenced on for +#: the delta method's shares: the NPV over a horizon is numerical, so a +#: smaller step would difference its error (``parameter_sensitivity``'s +#: step over time). +NPV_STEP = 1e-2 + + +def expected_npv_uncertainty( + rbd, + horizon, + uncertainty: Optional[Dict[Hashable, Any]], + *, + n_draws: int, + seed, + sampling: str, + shares: bool, + **valued, +) -> NPVUncertainty: + """See ``RepairableRBD.expected_npv_uncertainty``: ``valued``, the + arguments of ``expected_npv``.""" + + def npv(diagram) -> np.ndarray: + return np.array([diagram.expected_npv(horizon, **valued).npv]) + + if not isinstance(shares, (bool, np.bool_)): + raise TypeError( + "shares must be True or False (whether to split the NPV's " + f"variance among the inputs); got {shares!r}." + ) + # The diagram's own value first: what it refuses, every draw would. + nominal = rbd.expected_npv(horizon, **valued) + inputs, groups = sources(rbd, uncertainty) + models, group_models = draws(rbd, inputs, groups, n_draws, seed, sampling) + values = np.array( + [ + npv(build(rbd, inputs, models, group_models, i))[0] + for i in range(n_draws) + ] + ) + keys = [item.key for item in inputs] + [ + groups[i][0] for i in sorted(groups) + ] + split: Dict[Hashable, float] = {} + variance = None + if shares: + parts = delta( + rbd, + "expected_npv", + None, + None, + inputs, + groups, + NPV_STEP, + derivatives=_LeverDerivatives(rbd, npv, NPV_STEP), + ) + variance = float(np.sum(parts)) + split = { + key: (float(part[0]) / variance if variance > 0.0 else np.nan) + for key, part in zip(keys, parts) + } + return NPVUncertainty( + samples=values, + nominal=float(nominal.npv), + n_draws=n_draws, + band=band_of(rbd, inputs, groups), + horizon=float(nominal.horizon), + discount_rate=float(nominal.discount_rate), + value_rate=float(nominal.value_rate), + variance_shares=split, + delta_variance=variance, + held_fixed=held_fixed(rbd, inputs, groups), + ) diff --git a/repyability/rbd/_requirements.py b/repyability/rbd/_requirements.py index 3954ce3b..ef384c2c 100644 --- a/repyability/rbd/_requirements.py +++ b/repyability/rbd/_requirements.py @@ -28,7 +28,7 @@ _constant_rate, _sf_values, ) -from repyability.rbd._covariate_schedule import ScheduledLife +from repyability.rbd._covariate_schedule import ClockLife from repyability.rbd._hidden_life import ( TestedLife, ) @@ -91,7 +91,8 @@ def _require_costs(rbd) -> None: "Nothing is priced: give the components a repair_cost, " "replace_cost, downtime_cost or acquisition_cost, their " "maintenance or tests a cost, a maintenance group a " - "setup_cost, or the system a downtime_cost_rate." + "setup_cost, the system a downtime_cost_rate, or its repair " + "crews a crew_cost_rate or a call_out with a fee or a rate." ) @@ -134,7 +135,7 @@ def _require_reliabilities(rbd, node) -> None: getattr(component, "time_to_replace", None), ): if ( - isinstance(model, (StandbyModel, LoadSharingModel, ScheduledLife)) + isinstance(model, (StandbyModel, LoadSharingModel, ClockLife)) and model.is_simulated ): raise model._no_reliability() @@ -168,6 +169,22 @@ def _require_times(rbd, node) -> None: ) +def _require_own_failures(rbd, node, simulate: str) -> None: + """Raise if a component also fails at shocks of a ``Shocks`` group: + its own models do not give its failures, which the group's shocks + add to. ``simulate`` says what to run instead.""" + from repyability.rbd.ccf import Shocks + + for group in rbd.ccf_groups: + if node in group.members and isinstance(group.model, Shocks): + raise NotImplementedError( + f"Component {node!r} is in common-cause group " + f"{list(group.members)}, whose shocks fail it too, at a " + "rate of their own, so its own life does not give its " + f"failures: {simulate}" + ) + + def _require_unscheduled_stages(rbd, node) -> None: """Raise if a degrading component is maintained or inspected on a schedule: its long-run time in each stage has no exact value.""" @@ -206,8 +223,11 @@ def _repairs_take_time(component) -> bool: def _restoration_phrase(rbd, node) -> str: """How a component's preventive maintenance restores it, in words.""" restoration = rbd._restoring[node] - kind = "I" if restoration.kijima == "kijima1" else "II" - phrase = f"Kijima {kind}, q = {restoration.q:g}" + if restoration.kijima == "to_age": + phrase = f"to a virtual age of {restoration.q:g}" + else: + kind = "I" if restoration.kijima == "kijima1" else "II" + phrase = f"Kijima {kind}, q = {restoration.q:g}" if restoration.replace_every is not None: phrase += ( f", replaced at task {restoration.replace_every} since it was " @@ -300,7 +320,7 @@ def _minimal_cycle_blocker(rbd, node) -> Optional[str]: life = component.reliability if ( is_mixture(life) - or isinstance(life, ScheduledLife) + or isinstance(life, ClockLife) or not callable(getattr(life, "Hf", None)) ): return "its life has no cumulative hazard to count its failures by" @@ -463,6 +483,79 @@ def _on_a_clock(rbd, node) -> bool: return bool(np.ravel(survives)[0] >= 1.0) +def _planned(rbd) -> list: + """The components replaced at the times of a plan (a + ``"replace_at"``).""" + return [ + node + for node, schedule in rbd._preventive.items() + if schedule.plan is not None + ] + + +def _upgraded(rbd) -> str: + """The first upgraded component, in words, for a refusal.""" + node, upgrade = next(iter(rbd._upgrades.items())) + return f"Component {node!r} is upgraded at {upgrade.at:g}" + + +def _require_no_plans(rbd) -> None: + """Raise if a component is replaced at the times of a plan, which + ends, or upgraded at a time: the diagram has then no long run (nor a + long-run state).""" + if rbd._upgrades: + raise NotImplementedError( + f"{_upgraded(rbd)} (its units have another life from then), " + "so the diagram has no long run with it: ask for its values " + "over a horizon (expected_npv(horizon), expected_cost(T), " + "mission_availability(T), point_availability(t)); the " + "long-run methods (mean_availability(), expected_cost_rate() " + "and the others) give the long run once upgraded." + ) + from ._shutdowns import require_no_several + + require_no_several(rbd) + planned = _planned(rbd) + if planned: + raise NotImplementedError( + f"Component {planned[0]!r} is replaced at the times of a plan " + "(replace_at), which ends, so the diagram has no long run " + "with it: ask for its values over a horizon " + "(expected_npv(horizon), expected_cost(T), " + "mission_availability(T), point_availability(t)), or give the " + "component an interval, block replacement for ever, for the " + "long run." + ) + + +def _check_plan_state(rbd, node, state) -> None: + """Refuse a state that a component replaced at the times of a plan + cannot be given: a ``since_scheduled`` (its plan's times, from now, + place its replacements) and the long-run state (it has none).""" + schedule = rbd._preventive.get(node) + if schedule is None or ( + schedule.plan is None and node not in rbd._upgrades + ): + return + what = "is replaced at the times of a plan (replace_at), which ends" + whose = "is replaced at the times of its plan (replace_at)" + places = "which place its replacements" + if node in rbd._upgrades: + what = "is upgraded at a time" + whose = "is upgraded at the time of its upgrade (at)" + places = "which places it" + if state.stationary: + raise ValueError( + f"Component {node!r} {what}, so it has no long-run state: give " + "its age now (NodeState(age=...)), or leave it out (new)." + ) + if state.since_scheduled is not None: + raise ValueError( + f"Component {node!r} {whose}, counted from now, {places}: " + "leave its since_scheduled out." + ) + + def _require_block_models(rbd, node) -> None: """Raise unless the exact block-replacement values cover the component's models (the checks ``block_cycle`` makes first); replaced diff --git a/repyability/rbd/_runs.py b/repyability/rbd/_runs.py index 5fb58eea..38821e3a 100644 --- a/repyability/rbd/_runs.py +++ b/repyability/rbd/_runs.py @@ -10,6 +10,7 @@ import hashlib import json +import math from functools import partial from typing import ( TYPE_CHECKING, @@ -1673,6 +1674,9 @@ def _modules_rbd(diagram, modules: list) -> "RepairableRBD": input_node=diagram.input_node, output_node=diagram.output_node, repair_crews=args["repair_crews"], + # (A call-out crew comes for the modules' jobs, the only ones the + # crews have: its costs are among the modules' own.) + call_out=args.get("call_out"), maintenance_groups=groups or None, ) @@ -1730,7 +1734,16 @@ def _crew_free(diagram) -> "RepairableRBD": if not _crews._crews_limited(diagram): return diagram - return RepairableRBD(**{**diagram._init_args, "repair_crews": None}) + # (With as many crews as are needed, none is paid: a conditional run + # adds the crews' salaries itself.) + return RepairableRBD( + **{ + **diagram._init_args, + "repair_crews": None, + "crew_cost_rate": 0.0, + "call_out": None, + } + ) def _conditional_given( @@ -2385,9 +2398,10 @@ def rounded(totals) -> list: antithetic=antithetic, opportunistic_renewals=( dict(zip(nodes, tally.opportunistic)) - if diagram._maintenance + if diagram._maintenance or diagram._outage_members else None ), + outage_jobs=_outage_jobs(diagram, tally, t_simulation, N), control_variate=controls[0], conditional=conditional, shutdowns=int( @@ -2395,6 +2409,11 @@ def rounded(totals) -> list: ), system_planned_downtime=system_planned, system_unplanned_downtime=system_unplanned, + unplanned_downtimes=( + np.asarray(tally.unplanned_times, dtype=float) + if len(tally.unplanned_times) == len(tally.uptimes) + else None + ), **capacity_fields, ) @@ -2457,3 +2476,32 @@ def cost( ).cost assert result is not None # something is priced return result + + +def _outage_jobs(rbd, tally, t_simulation: float, n: int): + """Each start of a shutdown that renews components opportunistically, + with the mean count renewed there per simulation and its 95% interval + (see ``AvailabilityResult.outage_jobs``); None without such shuts.""" + if not rbd._outage_members: + return None + from repyability.rbd._event_loop import outage_starts + + starts = outage_starts(rbd, t_simulation) + jobs = tally.outage_jobs or [0] * len(starts) + squares = tally.outage_squares or [0] * len(starts) + out = [] + for (name, start), total, square in zip(starts, jobs, squares): + mean = total / n + variance = (square - n * mean * mean) / (n - 1) if n > 1 else 0.0 + error = math.sqrt(max(variance, 0.0) / n) + out.append( + { + "shutdown": name, + "start": start, + "mean": mean, + "standard_error": error, + "lower": max(mean - 1.96 * error, 0.0), + "upper": mean + 1.96 * error, + } + ) + return out diff --git a/repyability/rbd/_sensitivity.py b/repyability/rbd/_sensitivity.py index a0da7cf5..e042c648 100644 --- a/repyability/rbd/_sensitivity.py +++ b/repyability/rbd/_sensitivity.py @@ -72,6 +72,24 @@ } +#: The levers of a plan's times (``preventive.replace_at.0``, ...), which +#: move its curve's breaks too. +_PLAN_TIME = "preventive.replace_at." + + +#: The lever of an upgrade's time, which moves its curve's breaks too. +_UPGRADE_TIME = "upgrade.at" + + +def _moves_breaks(name: str) -> bool: + """Whether the lever ``name`` moves its component's curve's breaks.""" + return ( + name in _MOVES_BREAKS + or name.startswith(_PLAN_TIME) + or name == _UPGRADE_TIME + ) + + #: The range of a probability, a fraction or a share. _UNIT = (0.0, 1.0) @@ -222,6 +240,27 @@ def moved(v, key=key, option=option, options=options): float(value), ) ) + plan = options.get("replace_at") if key == "preventive" else None + if plan is not None: + # Each time of a plan, between the times either side of it. + times = [float(t) for t in np.atleast_1d(plan)] + edges = [0.0] + times + [math.inf] + for k, time in enumerate(times): + + def moved_time(v, k=k, times=times, key=key, options=options): + changed = times[:k] + [float(v)] + times[k + 1 :] # noqa + return {**spec, key: {**options, "replace_at": changed}} + + out.append( + ( + f"{_PLAN_TIME}{k}", + time, + moved_time, + False, + (edges[k], edges[k + 2]), + time, + ) + ) restoration = options.get("restoration") if isinstance(restoration, dict) and "q" in restoration: # The restoration factor of a task that restores partly. @@ -232,7 +271,15 @@ def moved_restoration(v, key=key, options=options): q = float(restoration["q"]) out.append( - (f"{key}.restoration.q", q, moved_restoration, False, _UNIT, q) + ( + f"{key}.restoration.q", + q, + moved_restoration, + False, + # Above 1, a task that ages the unit (harmful). + (0.0, math.inf), + q, + ) ) duration = options.get("duration") if duration is not None and not isinstance(duration, str): @@ -245,6 +292,17 @@ def moved_restoration(v, key=key, options=options): }, ): out.append((name, value, moved, False, bounds, scale)) + upgrade = spec.get("upgrade") + if isinstance(upgrade, dict) and is_number(upgrade.get("at")): + # When the component is upgraded. + + def moved_upgrade(v, upgrade=upgrade): + return {**spec, "upgrade": {**upgrade, "at": v}} + + at = float(upgrade["at"]) + out.append( + (_UPGRADE_TIME, at, moved_upgrade, False, (0.0, math.inf), at) + ) standby = spec.get("standby") if isinstance(standby, dict): for option in ("dormancy_factor", "switching_probability"): @@ -307,6 +365,7 @@ def _levers(rbd) -> List[_Lever]: of its components, then its common-cause groups and its repair crews.""" from .ccf import CCFGroup + from .ccf import parameter_bounds as ccf_parameter_bounds from .ccf import parameters as ccf_parameters from .ccf import with_parameters as with_ccf_parameters @@ -423,7 +482,7 @@ def build_ccf(v, g=g, letter=letter, group=group): False, build_ccf, None, - _UNIT, + ccf_parameter_bounds(group.model, letter), value, ) ) @@ -1007,7 +1066,7 @@ def sensitivity( quantity == "availability" and alone is not None and lever.node is not None - and (x is not None or lever.name not in _MOVES_BREAKS) + and (x is not None or not _moves_breaks(lever.name)) ): at = alone.at(lever) change = _difference(at, lever, rel_step, at(lever.value)) diff --git a/repyability/rbd/_shutdowns.py b/repyability/rbd/_shutdowns.py index abff1c79..f8b25d20 100644 --- a/repyability/rbd/_shutdowns.py +++ b/repyability/rbd/_shutdowns.py @@ -53,6 +53,7 @@ "scope", "cost", "idle_ageing", + "opportunistic", ) #: What a task bound to a shutdown takes from it, and so may not give. @@ -69,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, @@ -78,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())) @@ -144,10 +164,125 @@ def _validate_one(name, spec) -> _Shutdown: "nodes it holds off line, or None for the whole system." ) return _Shutdown( - name, period, offset, times, duration, scope, cost, bool(idle) + name, + period, + offset, + times, + duration, + scope, + cost, + bool(idle), + _opportunistic(name, spec.get("opportunistic")), ) +def _opportunistic(name, given): + """A shutdown's ``"opportunistic"`` checked: None, an age (for every + component in its scope under age replacement) or a dict of an age by + component; each age 0 or more (``inf``: never).""" + if given is None: + return None + + def age(value, whose: str) -> float: + number = number_or_nan(value) + if not number >= 0.0: + raise ValueError( + f"Shutdown {name!r}: the opportunistic age of {whose} must " + "be a number, 0 or more (inf for never): a component at " + f"least that old is renewed at the shut; got {value!r}." + ) + return number + + if isinstance(given, dict): + if not given: + raise ValueError( + f"Shutdown {name!r}: opportunistic names no component; " + "give {component: age}, or an age for every component in " + "its scope under age replacement." + ) + return tuple( + (node, age(value, f"component {node!r}")) + for node, value in given.items() + ) + return age(given, "its components") + + +def resolve_opportunistic(rbd, shut: _Shutdown) -> Tuple[tuple, ...]: + """The components ``shut`` renews if old enough, each with its age: + the dict given, or for an age every component in its scope under age + replacement, checked against the diagram (each in the scope, under + age replacement on its own calendar, renewed in full).""" + given = shut.opportunistic + if given is None: + return () + if not isinstance(given, tuple): + rules = tuple( + (node, given) + for node in scope(rbd, shut) + if getattr(rbd._preventive.get(node), "policy", None) == "age" + and rbd._preventive[node].shutdown is None + ) + if not rules: + raise ValueError( + f"Shutdown {shut.name!r} renews components opportunistically, " + "but no component in its scope is under age replacement: " + "give them a 'preventive' schedule with 'policy': 'age' " + "(whose cost and duration the renewal takes)." + ) + return rules + for node, _ in given: + schedule = rbd._preventive.get(node) + if node not in rbd.components: + raise ValueError( + f"Shutdown {shut.name!r}: opportunistic names {node!r}, " + "which is not a component of the diagram." + ) + if shut.scope is not None and node not in shut.scope: + raise ValueError( + f"Shutdown {shut.name!r} renews {node!r} opportunistically, " + f"so it must be in its scope {list(shut.scope)}." + ) + if ( + schedule is None + or schedule.policy != "age" + or schedule.shutdown is not None + ): + raise ValueError( + f"Shutdown {shut.name!r} renews {node!r} opportunistically, " + "as its own age replacement would, at its cost and in its " + "duration: give it a 'preventive' schedule with 'policy': " + "'age' of its own (one bound to a shutdown renews it there " + "already, with older_than)." + ) + if node in rbd._restoring or node in rbd._standby: + what = ( + "restored partly by its maintenance" + if node in rbd._restoring + else "a standby group" + ) + raise ValueError( + f"Shutdown {shut.name!r} renews {node!r} opportunistically, " + f"which is {what}: the opportunistic renewal takes a plain " + "unit renewed in full." + ) + return given + + +def opportunistic_at(rbd, node) -> List[Hashable]: + """The shutdowns that renew a component if it is old enough.""" + return [ + name + for name, rules in getattr(rbd, "_outage_rules", {}).items() + if any(member == node for member, _ in rules) + ] + + +def worked_on(rbd, node) -> List[Hashable]: + """The shutdowns a component is worked on at: its tasks bound to + them, and the ones that renew it if it is old enough.""" + return bound_to(rbd, node) + opportunistic_at(rbd, node) + + def _calendar(name, spec: dict, duration: float): """A shutdown's ``period`` and ``offset``, or its ``times``, checked: the shuts must not overlap one another.""" @@ -257,7 +392,23 @@ def bound_preventive(node, spec: dict, shutdowns: dict) -> Tuple[dict, dict]: as the schedule it is: the spec with the shut's interval, the policy and its fixed duration (for ``_spec._validate_preventive``), and the ``_Preventive``'s fields the shut gives (its offset or times, the - shut's name and an ``"older_than"``).""" + shut's name and an ``"older_than"``). A list of shutdowns' names + (see ``_bound_to_several``) renews the unit at each of theirs.""" + names = spec["shutdown"] + try: + one_name = names in shutdowns # a tuple may name one shutdown + except TypeError: + one_name = False + if not one_name and isinstance(names, (list, tuple)): + names = list(dict.fromkeys(names)) + if len(names) > 1: + return _bound_to_several(node, spec, names, shutdowns) + if not names: + raise ValueError( + f"Component {node!r}: its preventive names no shutdown; " + "give one shutdown's name, or a list of them." + ) + spec = {**spec, "shutdown": names[0]} shut = _named(node, spec["shutdown"], shutdowns, "preventive") _refuse_given(node, spec, "preventive", shut) policy = spec.get("policy", "block") @@ -281,7 +432,7 @@ def bound_preventive(node, spec: dict, shutdowns: dict) -> Tuple[dict, dict]: "it is older than older_than, or on its condition (a " "threshold): give one or the other." ) - if spec.get("restoration") is not None: + if spec.get("restoration") is not None or spec.get("restore_to"): raise ValueError( f"Component {node!r}: older_than replaces the unit at a " "shut by its age since new, which a restoration does not " @@ -308,6 +459,78 @@ def bound_preventive(node, spec: dict, shutdowns: dict) -> Tuple[dict, dict]: } +def _bound_to_several( + node, spec: dict, names: list, shutdowns: dict +) -> Tuple[dict, dict]: + """A ``"preventive"`` spec bound to several shutdowns: block + replacement at every start of each, each renewal taking its own + shut's length (``_Preventive.shuts``). The unit is renewed in full + there: a task kept unless due, or restoring part-way, is at one + shutdown. Two of the shutdowns may not start at one time.""" + shuts = [_named(node, name, shutdowns, "preventive") for name in names] + for shut in shuts: + _refuse_given(node, spec, "preventive", shut) + listed = ", ".join(repr(name) for name in names) + policy = spec.get("policy", "block") + given = [ + key + for key in ("older_than", "threshold", "restoration", "restore_to") + if spec.get(key) is not None + ] + if given or policy != "block": + what = given[0] if given else f"policy {policy!r}" + raise ValueError( + f"Component {node!r} is renewed at several shutdowns " + f"({listed}), at every start of each (the 'block' policy); " + f"{what} is taken at one shutdown: give one shutdown, or " + "leave it out." + ) + for i, a in enumerate(shuts): + for b in shuts[i + 1 :]: # noqa: E203 + shared = _shared_start(a, b) + if shared is not None: + raise ValueError( + f"Component {node!r} is renewed at shutdowns {a.name!r} " + f"and {b.name!r}, which both start at {shared:g}: " + "which one's renewal is done there is not said. Move " + "one (its offset or times), or make them one shutdown." + ) + view = { + key: value + for key, value in spec.items() + if key not in ("shutdown", "older_than") + } + view["policy"] = "block" + view["interval"] = min(_interval(shut) for shut in shuts) + view["duration"] = _fixed(max(shut.duration for shut in shuts)) + return view, { + "shutdown": tuple(names), + "shuts": tuple((shut, _fixed(shut.duration)) for shut in shuts), + } + + +def _shared_start(a: _Shutdown, b: _Shutdown) -> Optional[float]: + """The first time two shutdowns both start at (to rounding), or None: + over a common period of theirs, or their given times.""" + if a.periodic and b.periodic: + try: + period = _common_period([a.period, b.period]) + except NotImplementedError: + return None # periods with no common one never meet exactly + stop = period + max(a.offset, b.offset) + 1.0 + else: + given = [s for s in (a, b) if not s.periodic] + stop = max(float(s.times[-1]) for s in given) + 1.0 # type: ignore + a_starts, b_starts = a.starts(stop), b.starts(stop) + if not a_starts.size or not b_starts.size: + return None + scale = max(float(a_starts.max()), float(b_starts.max()), 1.0) + close = np.abs(a_starts[:, None] - b_starts[None, :]) <= 1e-12 * scale + if not close.any(): + return None + return float(a_starts[np.flatnonzero(close.any(axis=1))[0]]) + + def bound_inspection(node, spec: dict, shutdowns: dict) -> Tuple[dict, dict]: """An ``"inspection"`` spec bound to a shutdown, as ``bound_preventive`` gives a preventive one: the tests take the shut.""" @@ -400,6 +623,14 @@ def check(rbd) -> None: f"Shutdown {shut.name!r}: its scope names {node!r}, " f"which is {what}." ) + rbd._outage_rules = { + shut.name: resolve_opportunistic(rbd, shut) + for shut in rbd._shutdowns.values() + if shut.opportunistic is not None + } + rbd._outage_members = { + node for rules in rbd._outage_rules.values() for node, _ in rules + } for node in rbd.components: for name in bound_to(rbd, node): shut = rbd._shutdowns[name] @@ -445,7 +676,9 @@ def _pause_refusal(rbd, node, shut: _Shutdown) -> Optional[str]: ) schedule = rbd._preventive.get(node) inspection = rbd._inspection.get(node) - if schedule is not None and schedule.shutdown == shut.name: + if shut.name in opportunistic_at(rbd, node): + return None # worked on there, so not idle + if schedule is not None and shut.name in _task_shuts(schedule): if schedule.policy == "condition": return ( f"{lead} is inspected there and kept unless it is due " @@ -480,14 +713,21 @@ def _pause_refusal(rbd, node, shut: _Shutdown) -> Optional[str]: # -- what a diagram's shutdowns do to its nodes ------------------------------- +def _task_shuts(task) -> Tuple[Hashable, ...]: + """The shutdowns a task (a ``_Preventive`` or ``_Inspection``) is + done at: none, one, or several.""" + name = getattr(task, "shutdown", None) + if getattr(task, "shuts", None) is not None: + return tuple(name) # type: ignore[arg-type] + return () if name is None else (name,) + + def bound_to(rbd, node) -> List[Hashable]: """The shutdowns a component is worked on at (its maintenance or tests bound to them).""" - out = [] + out: List[Hashable] = [] for schedule in (rbd._preventive.get(node), rbd._inspection.get(node)): - name = getattr(schedule, "shutdown", None) - if name is not None: - out.append(name) + out.extend(_task_shuts(schedule)) return out @@ -506,7 +746,7 @@ def holding(rbd, node) -> List[Tuple[_Shutdown, bool]]: out = [] for shut in rbd._shutdowns.values(): if shut.duration > 0.0 and node in scope(rbd, shut): - paused = not shut.idle_ageing and shut.name not in bound_to( + paused = not shut.idle_ageing and shut.name not in worked_on( rbd, node ) out.append((shut, paused)) @@ -1048,22 +1288,104 @@ def refuse(rbd, method: str) -> None: require_none(rbd, f"{method}()") +def several_at(rbd, node) -> str: + """The shutdowns a component is renewed at, in words, if several + (see ``_bound_to_several``); else the empty string.""" + schedule = rbd._preventive.get(node) + if getattr(schedule, "shuts", None) is None: + return "" + return ", ".join(repr(name) for name in schedule.shutdown) + + +def require_no_several(rbd) -> None: + """Raise if a component is renewed at several shutdowns, which the + long-run methods do not follow (its renewals repeat on no one + interval of its own).""" + for node in rbd.components: + several = several_at(rbd, node) + if several: + raise NotImplementedError( + f"Component {node!r} is renewed at several shutdowns " + f"({several}), whose renewals the long-run methods do not " + "follow: ask for its values over a horizon " + "(expected_npv(horizon), expected_cost(T), " + "mission_availability(T), point_availability(t)), or " + "estimate the long run by simulation over a long horizon, " + "with availability() or cost()." + ) + + def require_exact(rbd) -> None: - """Raise if the exact methods cannot take the diagram's shutdowns: - at given times (they take shuts on a period), or with what ties the - blocks together (repair crews, common-cause groups, maintenance - groups), or a nested RBD with a calendar of its own beside them.""" + """Raise if the exact long-run methods cannot take the diagram's + shutdowns: at given times (which end: no long run), or what the + values over time refuse too (``require_over_time``).""" + if not rbd._shutdowns: + return + given = [s.name for s in rbd._shutdowns.values() if not s.periodic] + if given: + raise NotImplementedError( + f"Shutdown {given[0]!r} is at given times, which end, so the " + "diagram has no long run with it: ask for its values over a " + "horizon (expected_npv(horizon), expected_cost(T), " + "mission_availability(T), point_availability(t)), or give the " + "shutdown a period for the long run." + ) + require_no_several(rbd) + require_over_time(rbd) + + +def _given_times_refusal(rbd) -> Optional[str]: + """Why the values over time cannot take a task done at a shutdown at + given times, or None: they take a block renewed at each shut, or + inspected there and kept unless due (stretch by stretch between its + times), not one tested there for a hidden failure, which they follow + on a period.""" + for node in rbd.components: + inspection = rbd._inspection.get(node) + if ( + inspection is None + or inspection.shutdown is None + or inspection.times is None + ): + continue + return ( + f"Component {node!r} is tested at each shut of shutdown " + f"{inspection.shutdown!r}, which is at given times; the exact " + "methods follow such a block at shuts on a period (and a " + "block renewed, or kept unless it is due, at every shut at " + "given times too). Estimate its values by simulation, with " + "availability() or cost()." + ) + return None + + +def require_over_time(rbd) -> None: + """Raise if the exact values over time cannot take the diagram's + shutdowns: with what ties the blocks together (repair crews, + common-cause groups, maintenance groups), a nested RBD with a + calendar of its own beside them, or a block inspected or tested at + shuts at given times (see ``_given_times_refusal``).""" if not rbd._shutdowns: return from repyability.rbd import _crews, _long_run from repyability.rbd.repairable_rbd import RepairableRBD - given = [s.name for s in rbd._shutdowns.values() if not s.periodic] + given = _given_times_refusal(rbd) if given: + raise NotImplementedError(given) + opportunistic = [ + name + for name, rules in getattr(rbd, "_outage_rules", {}).items() + if any(math.isfinite(age) for _, age in rules) + ] + if opportunistic: raise NotImplementedError( - f"Shutdown {given[0]!r} is at given times; the exact methods " - "take shutdowns on a period. Estimate its values by " - "simulation, with availability() or cost()." + f"Shutdown {opportunistic[0]!r} renews components " + "opportunistically, each one only if it is old enough then, " + "which ties its renewals to its age at each shut: the exact " + "methods do not follow that. Estimate its values by " + "simulation, with availability() or cost() (which count the " + "renewals made at each shut)." ) tie = None if rbd._crews_couple() or _crews._crews_limited(rbd): @@ -1097,6 +1419,21 @@ def require_exact(rbd) -> None: def check_state(rbd, node, state) -> None: """Refuse a state that places the calendar of a task bound to a shutdown: the shut's calendar places it (given relative to now).""" + several = several_at(rbd, node) + if several and state.stationary: + raise ValueError( + f"Component {node!r} is renewed at several shutdowns " + f"({several}), whose renewals the long run does not follow, so " + "it has no long-run state: give its age now " + "(NodeState(age=...)), or leave it out (new)." + ) + if several and state.maintenance: + raise ValueError( + f"Component {node!r} is renewed at several shutdowns " + f"({several}), each taking its own time, so which renewal it " + "is in now, and what is left of it, is not known: give it up " + "(NodeState(age=...)) or in a repair (NodeState(alive=False))." + ) if bound_to(rbd, node) and state.since_scheduled is not None: raise ValueError( f"Component {node!r} is worked on at shutdown " diff --git a/repyability/rbd/_spares.py b/repyability/rbd/_spares.py index deb36d14..f5cbbb27 100644 --- a/repyability/rbd/_spares.py +++ b/repyability/rbd/_spares.py @@ -1950,6 +1950,7 @@ def _replacements(rbd, node, long_run: bool = False): "spares_demand(method='simulate')." ) _requirements._require_reliabilities(rbd, node) + _requirements._require_own_failures(rbd, node, simulate) if node in rbd._standby: raise NotImplementedError( f"Component {node!r} is a standby group, whose units' " @@ -1966,6 +1967,19 @@ def _replacements(rbd, node, long_run: bool = False): f"{simulate}" ) schedule = rbd._preventive.get(node) + if node in rbd._upgrades: + raise NotImplementedError( + f"Component {node!r} is upgraded at a time, from which its " + "units have another life, which its replacements are not " + "counted across yet: count its failures over a horizon with " + "expected_events(T)." + ) + if schedule is not None and schedule.plan is not None: + raise NotImplementedError( + f"Component {node!r} is replaced at the times of a plan " + "(replace_at), not on a period, which its replacements are " + f"not counted for exactly yet: {simulate}" + ) if schedule is not None and schedule.policy == "block": component = rbd.components[node] duration = schedule.duration diff --git a/repyability/rbd/_spec.py b/repyability/rbd/_spec.py index e6121dd2..7d0ee4ba 100644 --- a/repyability/rbd/_spec.py +++ b/repyability/rbd/_spec.py @@ -12,6 +12,7 @@ Any, Dict, Hashable, + NamedTuple, Optional, Tuple, ) @@ -36,11 +37,14 @@ _Preventive, _Restoration, _Standby, + _Upgrade, ) from repyability.utils.checks import ( is_number, number_or_nan, + real_array, unfitted_distribution, + whole_number, ) from repyability.utils.wrappers import outside_level @@ -66,9 +70,20 @@ "replace_after", "duty", "covariates", + "upgrade", + "salvage", + "escalation", + "retire_at", ) ) +#: The keys of a component's own money, taken by a valuation +#: (``expected_npv``) as its arguments of the same names for the node. +VALUATION_KEYS = ("salvage", "escalation", "retire_at") + +#: The keys of a component's ``"upgrade"`` spec. +UPGRADE_KEYS = ("at", "reliability", "cost") + #: The models of imperfect repair a spec's ``"repair"`` can name. REPAIR_MODELS = ("kijima1", "kijima2") @@ -84,16 +99,23 @@ "level", "calendar", "restoration", + "restore_to", "replace_every", "replacement_cost", "shutdown", "older_than", "basis", + "replace_at", ) #: The keys of a ``"preventive"`` spec that make its task restore the unit #: only partly (Kijima), and replace it as new at every so many tasks. -RESTORATION_KEYS = ("restoration", "replace_every", "replacement_cost") +RESTORATION_KEYS = ( + "restoration", + "restore_to", + "replace_every", + "replacement_cost", +) #: The policies a ``"preventive"`` spec can name: replacement at an #: age, on a calendar (block), on the condition an inspection finds, or @@ -229,6 +251,7 @@ def saved(member): "must be identical components, with the same life and " "repair models." ), + shocks=True, ) @@ -282,6 +305,7 @@ def _validate_imperfect(rbd, node, spec: dict) -> Optional[_Imperfect]: if process is not None: if isinstance(preventive, dict) and ( preventive.get("restoration") is not None + or preventive.get("restore_to") ): raise ValueError( f"Component {node!r} is repaired by its fitted " @@ -342,12 +366,15 @@ def _validate_process(node, spec: dict): def _kijima_factor( - node, given, what: str, at_one: str, also: str = "" + node, given, what: str, at_one: str, also: str = "", harmful=False ) -> Tuple[str, float]: """A Kijima ``(model, q)`` given as a dict of a ``"model"`` and its - restoration factor ``"q"`` in [0, 1], checked: ``what`` names it - ("repair", "the preventive restoration"), ``at_one`` says what - ``q = 1`` is, and ``also`` what else it may be given as.""" + restoration factor ``"q"``, checked: ``what`` names it ("repair", + "the preventive restoration"), ``at_one`` says what ``q = 1`` is, + and ``also`` what else it may be given as. ``q`` is in [0, 1], or, + with ``harmful`` (a preventive task's restoration), any finite number + from 0: above 1, a task that leaves the unit older than it was + (harmful or invasive maintenance).""" if ( not isinstance(given, dict) or set(given) != {"model", "q"} @@ -359,19 +386,47 @@ def _kijima_factor( f"and its restoration factor 'q'{also}, got {given!r}." ) q = given["q"] - if ( - isinstance(q, bool) - or not isinstance(q, (int, float, np.number)) - or not 0.0 <= float(q) <= 1.0 - ): + number = not isinstance(q, bool) and isinstance(q, (int, float, np.number)) + most = math.inf if harmful else 1.0 + if not (number and 0.0 <= float(q) <= most and math.isfinite(float(q))): + if harmful: + raise ValueError( + f"Component {node!r}: the restoration factor q must be " + f"a finite number, 0 or more (0 renews the unit, 1 " + f"{at_one}, above 1 leaves it older: harmful " + f"maintenance), got {q!r}." + ) raise ValueError( f"Component {node!r}: the restoration factor q must be " f"a number in [0, 1] (0 renews the unit, 1 {at_one}), " - f"got {q!r}." + f"got {q!r}. Only a preventive task's restoration may be " + "above 1 (harmful maintenance): a repair cannot leave a unit " + "older than it was." ) return given["model"], float(q) +#: A ``_Restoration``'s ``kijima`` for a task that restores the unit to +#: a virtual age (``"restore_to"``), whose ``q`` is the age. +TO_AGE = "to_age" + + +def _restore_to(node, preventive: dict) -> Optional[float]: + """A ``"preventive"`` spec's ``"restore_to"``, checked: the virtual + age a task leaves the unit at (0 renews it), or None.""" + to = preventive.get("restore_to") + if to is None: + return None + age = number_or_nan(to) + if not (age >= 0.0 and math.isfinite(age)): + raise ValueError( + f"Component {node!r}: restore_to is the virtual age a task " + "leaves the unit at, in the models' unit: a finite number, 0 " + f"or more (0 renews it); got {to!r}." + ) + return age + + def _validate_restoration( node, spec: dict, @@ -391,6 +446,16 @@ def _validate_restoration( given = preventive.get("restoration") every = preventive.get("replace_every") cost = preventive.get("replacement_cost") + to = _restore_to(node, preventive) + if to is not None and given is not None: + raise ValueError( + f"Component {node!r}: a task restores the unit by a Kijima " + "factor ('restoration') or to an age ('restore_to'), not both: " + "give one." + ) + if to: + # To a virtual age (0 renews the unit: the default, below). + given = to if cost is not None and every is None: raise ValueError( f"Component {node!r}: a replacement_cost is the cost of the " @@ -404,13 +469,17 @@ def _validate_restoration( "anyway." ) return None, None - model, q = _kijima_factor( - node, - given, - "the preventive restoration", - "leaves it as old as it was", - ", or a fitted surpyval GeneralizedRenewal (Kijima I or II)", - ) + if to: + model, q = TO_AGE, to + else: + model, q = _kijima_factor( + node, + given, + "the preventive restoration", + "leaves it as old as it was", + ", or a fitted surpyval GeneralizedRenewal (Kijima I or II)", + harmful=True, + ) if every is not None: if ( isinstance(every, bool) @@ -738,12 +807,20 @@ def _validate_preventive( if spec.get("shutdown") is not None: from repyability.rbd import _shutdowns + if spec.get("replace_at") is not None: + raise ValueError( + f"Component {node!r}: its preventive task is done at " + f"shutdown {spec['shutdown']!r}, whose times apply, so it " + "takes no replace_at: give the times to the shutdown." + ) spec, bound = _shutdowns.bound_preventive(node, spec, shutdowns or {}) elif spec.get("older_than") is not None: raise ValueError( f"Component {node!r}: older_than replaces the unit at a " "shutdown if it is that old, so it needs a shutdown." ) + if spec.get("replace_at") is not None: + spec, bound = _replaced_at(node, spec) policy = spec.get("policy", "age") if policy not in PREVENTIVE_POLICIES: raise ValueError( @@ -818,15 +895,9 @@ def _validate_preventive( f"{within}, got {opportunity!r}." ) opportunity = float(opportunity) - duration = spec.get("duration", "instant") - if isinstance(duration, str) and duration == "instant": - duration = None - elif not hasattr(duration, "random"): - raise ValueError( - f"Component {node!r}: the preventive duration must be a " - "time-to-maintain model (such as a fitted surpyval " - f"distribution) or 'instant', got {duration!r}." - ) + duration = _duration( + node, "preventive", "time-to-maintain", spec.get("duration") + ) costs = [] for key, name in ( ("cost", "preventive_cost"), @@ -851,6 +922,51 @@ def _validate_preventive( return schedule, costs[0], costs[1] +def _replaced_at(node, spec: dict) -> Tuple[dict, dict]: + """A ``"preventive"`` spec with a plan (its ``"replace_at"``: the + times, from 0, at which the unit is replaced if it is up, and after + the last no more), checked, as the block replacement it is: the spec + with that policy and an interval (the shortest gap between the times, + which only sizes the simulation's streams: the times place the + replacements), and the ``_Preventive``'s ``times``.""" + given = spec["replace_at"] + policy = spec.get("policy", "block") + if policy != "block": + raise ValueError( + f"Component {node!r}: replace_at replaces the unit at each of " + "its times if it is up, which is the 'block' policy at given " + f"times, so its policy cannot be {policy!r}: leave the policy " + "out, or give that policy an interval and no replace_at." + ) + if spec.get("interval") is not None: + raise ValueError( + f"Component {node!r}: give its preventive task an interval " + "(replaced every so often, for ever) or replace_at (replaced " + "at those times and no more), not both." + ) + try: + times = np.atleast_1d(real_array(given, "replace_at")) + except (TypeError, ValueError): + times = np.array([math.nan]) + if ( + times.ndim != 1 + or not times.size + or not np.all(np.isfinite(times)) + or not times[0] > 0.0 + or np.any(np.diff(times) <= 0.0) + ): + raise ValueError( + f"Component {node!r}: replace_at must be the times at which " + "the unit is replaced, in the diagram's time from 0: positive, " + f"finite and increasing, got {given!r}." + ) + gaps = np.diff(np.concatenate(([0.0], times))) + view = {key: value for key, value in spec.items() if key != "replace_at"} + view["policy"] = policy + view["interval"] = float(gaps.min()) + return view, {"times": tuple(float(t) for t in times)} + + def _validate_level(node, spec: dict, policy: str, life) -> Optional[float]: """A ``"preventive"`` spec's ``"level"`` (#271), checked: a number below the failure threshold of the degradation process the @@ -887,6 +1003,91 @@ def _validate_level(node, spec: dict, policy: str, life) -> Optional[float]: return level +def _validate_upgrade(node, spec: dict) -> _Upgrade: + """A component spec's ``"upgrade"``, validated: the time (in the + diagram's time from 0) from which its units have another life, that + life, and the capital cost charged then. An upgraded component is a + plain one: its schedule is the upgrade.""" + from repyability.utils.checks import no_distribution + + upgrade = spec["upgrade"] + if not isinstance(upgrade, dict): + raise ValueError( + f"Component {node!r}: upgrade must be a dict of " + f"{', '.join(UPGRADE_KEYS)}, got {upgrade!r}." + ) + unknown = set(upgrade) - set(UPGRADE_KEYS) + if unknown: + raise ValueError( + f"Component {node!r}: unknown upgrade key(s) " + f"{sorted(map(str, unknown))}; it takes " + f"{', '.join(UPGRADE_KEYS)}." + ) + task = spec.get("preventive") + if task is not None and not ( + isinstance(task, dict) + and task.get("policy") == "block" + and not any( + task.get(key) is not None + for key in ( + "shutdown", + "replace_at", + "restoration", + "restore_to", + "replace_every", + "basis", + ) + ) + ): + raise ValueError( + f"Component {node!r} has an upgrade and a preventive task " + "other than block replacement on its own interval ('policy': " + "'block'), which are not taken together yet: give it block " + "replacement, or one or the other." + ) + for key, what in ( + ("inspection", "an inspection"), + ("standby", "standby units"), + ("repair", "an imperfect repair"), + ("replace_after", "an imperfect repair"), + ("group", "a maintenance group"), + ("duty", "a duty"), + ("covariates", "a covariate schedule"), + ): + if spec.get(key) is not None: + raise ValueError( + f"Component {node!r} has an upgrade and {what} ({key!r}), " + "which are not taken together yet: give it one or the " + "other." + ) + for key in ("at", "reliability"): + if key not in upgrade: + raise ValueError( + f"Component {node!r}: an upgrade needs {key!r}: the time " + "from which its units have the new life (at), and that " + "life (reliability)." + ) + at = number_or_nan(upgrade["at"]) + if not (at > 0.0 and math.isfinite(at)): + raise ValueError( + f"Component {node!r}: the upgrade's time (at) must be a " + "positive, finite number, in the diagram's time from 0, got " + f"{upgrade['at']!r}." + ) + life = upgrade["reliability"] + no_distribution(life, f"Component {node!r}: the upgrade's reliability") + if not (hasattr(life, "sf") and hasattr(life, "ff")): + raise ValueError( + f"Component {node!r}: the upgrade's reliability must be a " + "lifetime model (such as a fitted surpyval distribution), got " + f"{life!r}." + ) + cost = 0.0 + if upgrade.get("cost") is not None: + cost = _validate_cost(node, "the upgrade's cost", upgrade["cost"]) + return _Upgrade(at, life, cost) + + def _validate_standby(node, spec: dict) -> _Standby: """A component spec's ``"standby"``, validated: the group of units it makes the component (see ``_StandbyGroup``).""" @@ -991,15 +1192,9 @@ def _validate_inspection( f"positive, finite number, got {spec['interval']!r}. (A " "hidden failure is found only by an inspection.)" ) - duration = spec.get("duration", "instant") - if isinstance(duration, str) and duration == "instant": - duration = None - elif not hasattr(duration, "random"): - raise ValueError( - f"Component {node!r}: the inspection duration must be a " - "time-to-test model (such as a fitted surpyval distribution) " - f"or 'instant', got {duration!r}." - ) + duration = _duration( + node, "inspection", "time-to-test", spec.get("duration") + ) cost = spec.get("cost") if cost is not None: cost = _validate_component_cost(node, "inspection_cost", cost) @@ -1054,6 +1249,79 @@ def _validate_inspection( return schedule, cost +def _duration(node, task: str, model: str, duration): + """A preventive or inspection task's ``duration``: ``None`` for + ``'instant'`` (the default) or 0, a fixed time for a number (a point + mass, surpyval's ``ExactEventTime``), else a model of the time.""" + if duration is None or ( + isinstance(duration, str) and duration == "instant" + ): + return None + if isinstance(duration, (int, float, np.number)) and not isinstance( + duration, (bool, np.bool_) + ): + value = float(duration) + if not (math.isfinite(value) and value >= 0.0): + raise ValueError( + f"Component {node!r}: the {task} duration must be a time " + f"0 or more (a fixed time in the models' unit), a {model} " + f"model, or 'instant'; got {duration!r}." + ) + if value == 0.0: + return None + from surpyval import ExactEventTime + + return ExactEventTime.from_params([value]) + if not hasattr(duration, "random"): + raise ValueError( + f"Component {node!r}: the {task} duration must be a {model} " + "model (such as a fitted surpyval distribution), a fixed time " + f"(a number), or 'instant', got {duration!r}." + ) + return duration + + +def _validate_valuation(node, spec: dict) -> Dict[str, Any]: + """A component's own money (``VALUATION_KEYS``), checked: a salvage a + finite number or a function of age, an escalation a finite growth + rate, a retirement a time more than 0.""" + out: Dict[str, Any] = {} + salvage = spec.get("salvage") + if salvage is not None: + if not callable(salvage): + number = number_or_nan(salvage) + if not math.isfinite(number): + raise ValueError( + f"The salvage of component {node!r} must be a finite " + "number (what the unit is worth at the end; negative " + "for a cost of disposal) or a function of its age; got " + f"{salvage!r}." + ) + salvage = number + out["salvage"] = salvage + escalation = spec.get("escalation") + if escalation is not None: + number = number_or_nan(escalation) + if not math.isfinite(number): + raise ValueError( + f"The escalation of component {node!r} must be a finite " + "growth rate per unit time of the models (continuous; 3% " + "a year with models in hours is math.log(1.03) / 8760); " + f"got {escalation!r}." + ) + out["escalation"] = number + retire_at = spec.get("retire_at") + if retire_at is not None: + number = number_or_nan(retire_at) + if not (math.isfinite(number) and number > 0.0): + raise ValueError( + f"The retire_at of component {node!r} must be a time more " + f"than 0 (when the unit is retired); got {retire_at!r}." + ) + out["retire_at"] = number + return out + + def _validate_cost(node, key: str, value) -> float: """Coerce a cost to a finite, non-negative float.""" if hasattr(value, "qf"): @@ -1074,6 +1342,67 @@ def _validate_cost(node, key: str, value) -> float: return cost +def _validate_crew_cost(value, crews: Optional[int]) -> float: + """``crew_cost_rate``, validated: a finite, non-negative number, and + above 0 only with a number of ``crews`` to pay.""" + rate = _validate_cost("", "crew_cost_rate", value) + if rate and crews is None: + raise ValueError( + f"crew_cost_rate ({rate:g}) prices each repair crew per unit " + "time, but repair_crews is None: as many crews as are needed, " + "which cannot be priced. Give repair_crews, the number of " + "crews paid, or leave crew_cost_rate out." + ) + return rate + + +#: The keys of a ``call_out`` (see ``RepairableRBD``). +CALL_OUT_KEYS = ("when_waiting", "fee", "rate") + + +class _CallOut(NamedTuple): + """A call-out crew: how many waiting jobs call it, its fee each time + it comes and its cost per unit time while engaged.""" + + when_waiting: int + fee: float + rate: float + + +def _validate_call_out(value, crews: Optional[int]) -> Optional[_CallOut]: + """``call_out``, validated: None, or a dict with ``"when_waiting"`` + (a whole number of jobs, 1 or more) and optionally a ``"fee"`` and a + ``"rate"`` (finite, non-negative numbers), given with a number of + ``crews`` for jobs to wait for.""" + if value is None: + return None + if not isinstance(value, dict): + raise ValueError( + "call_out must be a dict with the keys " + f"{', '.join(map(repr, CALL_OUT_KEYS))}, or None; got {value!r}." + ) + unknown = [key for key in value if key not in CALL_OUT_KEYS] + if unknown or "when_waiting" not in value: + raise ValueError( + "call_out takes 'when_waiting' (how many waiting jobs call the " + "crew) and optionally 'fee' and 'rate'; got the keys " + f"{sorted(map(str, value))}." + ) + when = whole_number(value["when_waiting"], "call_out's 'when_waiting'") + fee = _validate_cost("", "call_out's 'fee'", value.get("fee", 0.0)) + rate = _validate_cost( + "", "call_out's 'rate'", value.get("rate", 0.0) + ) + if crews is None: + raise ValueError( + "call_out brings a crew more when jobs wait for the " + "repair_crews crews, but repair_crews is None: as many crews " + "as are needed, so that no job waits. Give repair_crews, or " + "leave call_out out." + ) + return _CallOut(when, fee, rate) + + def _validate_component_cost(node, key: str, value): """Validate a per-component cost: a number (coerced to float) or, for the per-action costs, a distribution of the cost -- anything with diff --git a/repyability/rbd/_streams.py b/repyability/rbd/_streams.py index e274bc80..9aa7092f 100644 --- a/repyability/rbd/_streams.py +++ b/repyability/rbd/_streams.py @@ -261,6 +261,19 @@ def entropy_of(seed) -> int: return int(np.random.RandomState(seed).randint(0, 2**62, dtype=np.int64)) +def shared_seed(seed): + """The seed for a result made of several runs that must draw the same + random numbers (the runs to each window's end, cut from one set of + histories): ``seed`` itself, or, if None, one drawn from numpy's + global RNG as an unseeded run draws its entropy (seed it for a + reproducible one). Each run is then the seeded run of that seed, so + an unseeded result is a seeded one of a seed drawn at random, where + runs left unseeded each drew their own histories.""" + if check_seed(seed) is None: + return int(np.random.randint(0, 2**32, dtype=np.int64)) + return seed + + def seed_entropy(seed: Optional[int] = None) -> int: """The entropy a [`RepairableRBD`][repyability.RepairableRBD] run's random streams are seeded from, given its seed. diff --git a/repyability/rbd/_switch_runs.py b/repyability/rbd/_switch_runs.py new file mode 100644 index 00000000..66e3ef12 --- /dev/null +++ b/repyability/rbd/_switch_runs.py @@ -0,0 +1,274 @@ +"""The best time to switch blocks of a ``RepairableRBD`` from one way of +running them to another (``RepairableRBD.best_switch_time``): is it worth +running hot, for a whole diagram? + +The blocks that switch run on covariate schedules (``_covariate_schedule``: +a regression life under covariates on the diagram's clock). For a switch +time ``s``, each of them runs at its first row of covariates until ``s`` +and at its second after, and the system earns the first value rate per +unit of time up until ``s`` and the second after. Each candidate ``s`` is +a twin of the diagram with those schedules (the schedule is plain data, +so the twin is the diagram built again with it), simulated with the same +seed: its streams are named as the diagram's, so every candidate's runs +draw the same uniforms (common random numbers), and the differences +between candidates are far less noisy than their values. Each run is +priced as ``npv_distribution`` prices it (``_pricing``), the value split +at ``s`` between the two rates. + +The NPV against ``s`` is scanned on a grid from 0 (switch at once) to the +horizon (never switch), and refined on a finer grid between the best's +neighbours; the scan is returned to audit the answer. +""" + +from typing import Any, Dict, Hashable, List, Optional, Tuple + +import numpy as np + +from repyability.rbd import _npv, _npv_runs, _requirements, _streams +from repyability.rbd.results import SimulatedSwitchTime +from repyability.utils import checks + +#: Switch times added between the best scanned one's neighbours. +_REFINE = 6 +#: Simulations priced at a time: only their present values are kept. +_CHUNK = 2000 + +_NONE = ( + "No block of the diagram runs on a covariate schedule, so none can " + "switch from one way of running to another: give each block that can " + "a fitted surpyval regression model as its reliability and a " + '"covariates" schedule in its spec (e.g. surpyval.StepSchedule.' + "from_changepoints([0], [[1.0]])), or, for one unit, use " + "repyability.best_switch_time." +) + + +def scheduled_blocks(rbd) -> List[Hashable]: + """The diagram's blocks on a covariate schedule, as built.""" + return [ + node + for node, spec in rbd._init_args["components"].items() + if isinstance(spec, dict) + and spec.get("covariates") is not None + and node in rbd.components + ] + + +def _require_scheduled(rbd) -> None: + from repyability.rbd.routes import Refused + + if not scheduled_blocks(rbd): + raise Refused(_NONE) + + +def route(rbd, npv_route): + """``best_switch_time``'s route: refused if no block can switch, else + ``npv_distribution``'s (whose runs it prices).""" + from repyability.rbd import routes as r + + if not scheduled_blocks(rbd): + return r.refused(_NONE) + if npv_route.route == r.REFUSED: + return npv_route + return r.AnalysisRoute( + r.SIMULATED, + "The diagram simulated with each candidate switch time on its " + "scheduled blocks, every candidate from the same seed (common " + "random numbers), each run priced as npv_distribution prices it.", + engine=npv_route.engine, + engine_reason=npv_route.engine_reason, + ) + + +def _rows(rbd, covariates) -> Dict[Hashable, np.ndarray]: + """Each switching block's two rows of covariates, checked.""" + if not isinstance(covariates, dict) or not covariates: + raise ValueError( + "covariates must be a dict giving, for each block that " + "switches, its two rows of covariates: before the switch and " + f"after (e.g. {{'pump': [[60.0], [85.0]]}}); got {covariates!r}." + ) + blocks = scheduled_blocks(rbd) + out = {} + for node, rows in covariates.items(): + if node not in blocks: + raise ValueError( + f"Component {node!r} does not run on a covariate schedule, " + "so it cannot switch: the blocks that do are " + f"{', '.join(repr(b) for b in blocks)}." + ) + Z = checks.real_array(rows, f"covariates[{node!r}]").astype(float) + if Z.ndim == 1 and Z.size == 2: + Z = Z.reshape(2, 1) + if Z.ndim != 2 or Z.shape[0] != 2 or not np.all(np.isfinite(Z)): + raise ValueError( + f"covariates[{node!r}] must be two rows of finite " + "covariates, before the switch and after (two numbers for " + f"a model with one covariate); got {rows!r}." + ) + out[node] = Z + return out + + +def _schedule(Z: np.ndarray, switch: float, horizon: float): + """The covariate schedule of a block switching at ``switch``.""" + from surpyval.univariate.regression import StepSchedule + + if switch <= 0.0: + return StepSchedule.from_changepoints([0.0], Z[1:]) + if switch >= horizon: + return StepSchedule.from_changepoints([0.0], Z[:1]) + return StepSchedule.from_changepoints([0.0, switch], Z) + + +def _twin(rbd, rows: Dict[Hashable, np.ndarray], switch, horizon): + """The diagram with its switching blocks switched at ``switch``.""" + from repyability.rbd.repairable_rbd import RepairableRBD + + components = dict(rbd._init_args["components"]) + for node, Z in rows.items(): + components[node] = { + **components[node], + "covariates": _schedule(Z, switch, horizon), + } + return RepairableRBD(**{**rbd._init_args, "components": components}) + + +def _runs(twin, horizon, switch, rates, money, n, seed, engine, state): + """Each run's NPV, value and cost (present values) of ``twin`` over + ``horizon``, the value at ``rates[0]`` until ``switch`` and + ``rates[1]`` after (``money`` valuing 1 per unit time up, its growth + and rate); and the engine that ran them.""" + _npv_runs._require_priceable(twin) + ends = np.array([min(switch, horizon), horizon]) + value = np.zeros(n) + cost = np.zeros(n) + used = None + for first in range(0, n, _CHUNK): + size = min(_CHUNK, n - first) + ledger, runs = _npv_runs.priced_chunk( + twin, horizon, ends, money, size, seed, engine, first, state + ) + used = used or runs.engine + part = slice(first, first + size) + for (k, category, _), (present, _) in ledger.cells.items(): + if category == "value": + value[part] += rates[k] * present + else: + cost[part] += present + cost += sum(float(p) for p in twin.acquisition_costs.values() if p) + return value - cost, value, cost, used + + +def best_switch_time( + rbd, + covariates, + value_rates, + horizon, + *, + discount_rate: float, + mc_samples: Optional[int], + seed, + scan: int, + engine: str, + state, + escalation=None, + rates: str = "nominal", + inflation=None, +) -> SimulatedSwitchTime: + """See ``RepairableRBD.best_switch_time``.""" + rates_basis = rates + _require_scheduled(rbd) + _npv_runs._require_priceable(rbd) + rows = _rows(rbd, covariates) + earned = np.atleast_1d(checks.real_array(value_rates, "value_rates")) + if ( + earned.shape != (2,) + or not np.all(np.isfinite(earned)) + or np.any(earned < 0.0) + ): + raise ValueError( + "value_rates must be two finite numbers, at least 0: what the " + "system earns per unit of time up before the switch, and " + f"after; got {value_rates!r}." + ) + earned = earned.astype(float) + if not np.any(earned): + _requirements._require_costs(rbd) + money = _npv.Money( + rbd, + discount_rate, + 1.0, + _npv.own_escalation(rbd, escalation), + rates_basis, + 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" + ) + count = checks.whole_number(scan, "scan", minimum=3) + checks.one_of("engine", engine, ("auto", "python", "numba")) + # Every candidate shares a seed (common random numbers): drawn here + # (from numpy's global RNG) if not given, and kept in the result to + # repeat the search. + seed = _streams.shared_seed(checks.seed(seed)) + + valued: Dict[float, Tuple[np.ndarray, Any]] = {} + + def at(s: float) -> np.ndarray: + if s not in valued: + twin = _twin(rbd, rows, s, H) + samples, _, _, used = _runs( + twin, H, s, earned, money, n, seed, engine, state + ) + valued[s] = (samples + salvage, used) + return valued[s][0] + + grid = np.linspace(0.0, H, count) + means = [float(at(float(s)).mean()) for s in grid] + i = int(np.argmax(means)) + lo, hi = grid[max(i - 1, 0)], grid[min(i + 1, count - 1)] + for s in np.linspace(lo, hi, _REFINE + 2)[1:-1]: + at(float(s)) + times = sorted(valued) + npvs = [float(valued[s][0].mean()) for s in times] + best_s = times[int(np.argmax(npvs))] + best = valued[best_s][0] + never, at_once = valued[H][0], valued[0.0][0] + if best_s <= 0.0: + choice = "switch at once" + elif best_s >= H: + choice = "never switch" + else: + choice = "switch" + npv = float(best.mean()) + return SimulatedSwitchTime( + switch_time=float(best_s), + choice=choice, + npv=npv, + never_switch_npv=float(never.mean()), + switch_at_once_npv=float(at_once.mean()), + gain=max(npv - max(float(never.mean()), float(at_once.mean())), 0.0), + samples=best, + never_switch_samples=never, + switch_at_once_samples=at_once, + times=[float(s) for s in times], + npvs=npvs, + horizon=H, + discount_rate=money.given_rate, + value_rates=[float(v) for v in earned], + n_simulations=n, + seed=seed, + engine=valued[best_s][1] or engine, + 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/_tally.py b/repyability/rbd/_tally.py index 43ea14f6..eb12f4eb 100644 --- a/repyability/rbd/_tally.py +++ b/repyability/rbd/_tally.py @@ -33,6 +33,7 @@ _timeline_runs, _windows, ) +from repyability.rbd._common import _crew_salaries from repyability.rbd._exact import ( ExactSum, add_columns, @@ -48,6 +49,7 @@ ControlVariate, CostResult, ) +from repyability.value._categories import CATEGORIES as _CATEGORIES if TYPE_CHECKING: from repyability.rbd.repairable_rbd import RepairableRBD @@ -187,6 +189,9 @@ def __init__( T = simulation_window(t_simulation) self.rbd = rbd self.T = T + # The crews' salaries over the window, the same in every + # simulation: the system's, not the modules' or the other nodes'. + self.salaries = _crew_salaries(rbd) * T self.working, self.broken, self.method = working, broken, method self.antithetic, self.n_jobs = antithetic, n_jobs states = _curves._simulation_states(rbd, state, working | broken) @@ -320,13 +325,15 @@ def prepare(self) -> None: if self.priced else None ) + # (The diagram worked out given the modules may have no crews to + # pay: their salaries are added on their own.) self.others = ( 0.0 if self.exact_cost is None else math.fsum( float(np.ravel(value)[0]) for key, value in self.exact_cost.by_category.items() - if key != "system_downtime" + if key not in ("system_downtime", "crews") ) ) self.x = _conditional.grid( @@ -465,13 +472,14 @@ def uptimes(self) -> np.ndarray: def costs(self) -> np.ndarray: """Each simulation's expected cost given its modules: their own - costs, the other nodes' expected costs, and the system's expected - down time's.""" - return ( + costs, the other nodes' expected costs, the system's expected + down time's and the crews' salaries.""" + costs = ( np.concatenate(self.own_costs) + self.others + self.rbd.downtime_cost_rate * (self.T - self.uptimes()) ) + return costs + self.salaries if self.salaries else costs def breakdown(self) -> _Breakdown: """The expected cost of a window given the modules' histories (the @@ -484,7 +492,7 @@ def breakdown(self) -> _Breakdown: key: self.own_categories[key] / n + ( 0.0 - if key == "system_downtime" + if key in ("system_downtime", "crews") else float(np.ravel(exact_cost.by_category.get(key, 0.0))[0]) ) for key in _CATEGORIES @@ -492,6 +500,8 @@ def breakdown(self) -> _Breakdown: by_category["system_downtime"] = float( np.mean(self.rbd.downtime_cost_rate * (self.T - self.uptimes())) ) + # (A call-out crew's costs are among the modules' own.) + by_category["crews"] = self.own_categories["crews"] / n + self.salaries by_component = { node: float(np.ravel(value)[0]) for node, value in exact_cost.by_component.items() @@ -778,21 +788,6 @@ def _shard_bytes(template: dict, start: int, stop: int) -> bytes: return json.dumps({**template, "start": start, "stop": stop}).encode() -#: The cost categories, in the order ``CostResult.by_category`` lists them. -_CATEGORIES = ( - "repair", - "replace", - "preventive", - "inspection", - "component_downtime", - "system_downtime", - "setup", - # Appended: the categories' places index the engines' - # arrays and seeded costs, so a new one goes at the end. - "shutdown", -) - - # The category of a repair's own cost (all an imperfect repair is charged). _REPAIR = _CATEGORIES.index("repair") # The category of a shutdown's own cost, charged at each of its starts. @@ -839,6 +834,7 @@ class _Replication: "delivered", "replacements", "opportunistic", + "outage_jobs", "history", ) uptime: float @@ -860,6 +856,7 @@ class _Replication: delivered: Optional[float] replacements: List[int] opportunistic: List[int] + outage_jobs: Optional[List[int]] history: Optional[tuple] @@ -920,6 +917,8 @@ def __init__( # each simulation's until it is folded in. self.system_unplanned: Optional[ExactSum] = None self._unplanned_rows: list = [] + # Each simulation's time down unplanned, in order (as uptimes). + self.unplanned_times: list = [] self.node_uptime = [ExactSum() for _ in range(n)] self.node_downtime = [ExactSum() for _ in range(n)] self.intersection_uptime = [ExactSum() for _ in range(n)] @@ -966,6 +965,11 @@ def __init__( self.replacements: Optional[List[List[int]]] = None # Per node: its early renewals at stops of its maintenance group. self.opportunistic = [0] * n + # Per start of a shutdown that renews components opportunistically + # (see _event_loop.outage_starts): the renewals made there, summed + # over the simulations, and their squares summed; None with none. + self.outage_jobs: Optional[List[int]] = None + self.outage_squares: Optional[List[int]] = None # The simulations' histories, when asked for (see # RepairableRBD.simulate_timelines): kept, in order, in place of # every total. @@ -1024,6 +1028,22 @@ def add(self, rec: _Replication) -> None: for c, count in enumerate(rec.opportunistic): if count: self.opportunistic[c] += count + self._add_outage_jobs( + rec.outage_jobs, [c * c for c in rec.outage_jobs or ()] + ) + + def _add_outage_jobs(self, jobs, squares) -> None: + """Add renewals at the outages (see ``outage_jobs``), and their + squares.""" + if jobs is None: + return + if self.outage_jobs is None: + self.outage_jobs = [0] * len(jobs) + self.outage_squares = [0] * len(jobs) + assert self.outage_squares is not None + for k, (count, square) in enumerate(zip(jobs, squares)): + self.outage_jobs[k] += count + self.outage_squares[k] += square def add_changes(self, times: np.ndarray, deltas: np.ndarray) -> None: """Add simulations' changes of state (times, and +1 or -1), as an @@ -1174,6 +1194,7 @@ def add_unplanned(self, values) -> None: if self.system_unplanned is None: self.system_unplanned = ExactSum() self.system_unplanned.add(values) + self.unplanned_times.extend(np.ravel(values).tolist()) def unplanned_downtime(self) -> ExactSum: """The time the systems were down unplanned, exactly: all their @@ -1195,6 +1216,17 @@ def fold_costs(self, table) -> None: table, ) + def charge_crews(self, count: int, amount: float) -> None: + """Charge each of the last ``count`` simulations ``amount``, the + repair crews' salaries over the window (see ``_crew_salaries``), + which are the same in every simulation, under ``"crews"``.""" + if not (amount and count): + return + samples = self.cost_samples + first = len(samples) - count + samples[first:] = [cost + amount for cost in samples[first:]] + self.cost_by_category["crews"].add(np.full(count, amount)) + def state_changes(self) -> Tuple[np.ndarray, np.ndarray]: """Every time a simulated system changed state (``-0.0`` made ``0.0``), and +1 for a restoration or -1 for a failure or planned @@ -1285,7 +1317,12 @@ def merge(self, other: "_Tally") -> None: self.system_uptime.add(other.system_uptime) self.system_downtime.add(other.system_downtime) if other.system_unplanned is not None: - self.add_unplanned(other.system_unplanned) + # The exact total, and each simulation's time after this + # tally's, in order (as uptimes). + if self.system_unplanned is None: + self.system_unplanned = ExactSum() + self.system_unplanned.add(other.system_unplanned) + self.unplanned_times.extend(other.unplanned_times) for name in self._COUNTS: setattr(self, name, getattr(self, name) + getattr(other, name)) for name in self._NODE_SUMS: @@ -1296,6 +1333,7 @@ def merge(self, other: "_Tally") -> None: totals[c] += count for c, count in enumerate(other.opportunistic): self.opportunistic[c] += count + self._add_outage_jobs(other.outage_jobs, other.outage_squares) if self.binned is not None: assert other.binned is not None # chunks of one run self.binned += other.binned @@ -1351,6 +1389,7 @@ def to_dict(self) -> dict: for name in self._NODE_SUMS }, "uptimes": list(self.uptimes), + "unplanned_times": list(self.unplanned_times), "cost_samples": list(self.cost_samples), "cost_by_category": { key: amount.partials @@ -1386,6 +1425,11 @@ def to_dict(self) -> dict: ), "delivered": list(self.delivered), "opportunistic": list(self.opportunistic), + "outage_jobs": ( + None + if self.outage_jobs is None + else [list(self.outage_jobs), list(self.outage_squares or ())] + ), } @classmethod @@ -1419,6 +1463,9 @@ def from_dict(cls, data: dict) -> "_Tally": for name in cls._NODE_SUMS: setattr(tally, name, [_exact_total(v) for v in data[name]]) tally.uptimes = [float(v) for v in data["uptimes"]] + tally.unplanned_times = [ + float(v) for v in data.get("unplanned_times", ()) + ] tally.cost_samples = [float(v) for v in data["cost_samples"]] tally.cost_by_category.update( { @@ -1450,6 +1497,11 @@ def from_dict(cls, data: dict) -> "_Tally": ) tally.delivered = [float(v) for v in data["delivered"]] tally.opportunistic = [int(c) for c in data["opportunistic"]] + if data.get("outage_jobs") is not None: + jobs, squares = data["outage_jobs"] + tally._add_outage_jobs( + [int(c) for c in jobs], [int(c) for c in squares] + ) return tally def criticality_counts(self) -> Tuple[dict, dict]: diff --git a/repyability/rbd/_timeline_runs.py b/repyability/rbd/_timeline_runs.py index 467c9602..e1eaeae6 100644 --- a/repyability/rbd/_timeline_runs.py +++ b/repyability/rbd/_timeline_runs.py @@ -32,7 +32,11 @@ class Block(NamedTuple): happened); the system's state at 0 (``up``); and each simulation's changes of the system's (``system_offsets``: the time, the component whose change made it, which of that component's changes it was, and - whether it was planned).""" + whether it was planned). With shutdowns, the Python loop's also say + which changes were a shut's holds (``held``, beside ``planned``) and + the changes down a hold hid (``hidden``: bounds, offsets, times and + whether planned, laid out as the changes); numba's loop holds + nothing (``None``).""" start: np.ndarray bounds: np.ndarray @@ -45,6 +49,20 @@ class Block(NamedTuple): causes: np.ndarray nth: np.ndarray system_planned: np.ndarray + held: Optional[np.ndarray] = None + hidden: Optional[tuple] = None + + +class Hidden(NamedTuple): + """What a component's histories leave out under shutdowns: which of + its changes (aligned with its ``_Data.times``) were a shut's holds, + and the changes down a hold hid, each with its history, time and + whether planned.""" + + held: np.ndarray + history: np.ndarray + times: np.ndarray + planned: np.ndarray class Records: @@ -131,6 +149,41 @@ def data(self, t_end: float) -> Tuple[List[_Data], _Data]: ) return components, system + def hidden(self) -> List[Hidden]: + """Each component's holds and hidden changes (see ``Hidden``), in + the order of the components.""" + self.compact() + blocks = self.blocks or [_block([], self.m)] + out = [] + for c in range(self.m): + held, history, times, planned = [], [], [], [] + first = 0 + for b in blocks: + lo, hi = b.bounds[c], b.bounds[c + 1] + n = b.up.size + held.append( + np.zeros(hi - lo, bool) + if b.held is None + else b.held[lo:hi] + ) + if b.hidden is not None: + bounds, offsets, at, flags = b.hidden + a, z = bounds[c], bounds[c + 1] + counts = np.diff(offsets[c]) + history.append(first + np.repeat(np.arange(n), counts)) + times.append(at[a:z]) + planned.append(flags[a:z]) + first += n + out.append( + Hidden( + np.concatenate(held), + np.concatenate(history or [np.zeros(0, np.int64)]), + np.concatenate(times or [np.zeros(0)]), + np.concatenate(planned or [np.zeros(0, bool)]), + ) + ) + return out + def _block(histories: list, m: int) -> Block: """The Python loop's records of simulations (see ``_replicate``) as a @@ -163,6 +216,34 @@ def offsets(counts) -> np.ndarray: if places: planned[bounds[c] + grouped[c, s] + np.asarray(places)] = True system = offsets([len(h[4][0]) for h in histories]) + held = hidden = None + if any(h[5] is not None for h in histories): + # Under shutdowns: the holds, by their places as the planned + # changes, and the changes down they hid, laid out as the changes. + held = np.zeros(times.size, bool) + for s, h in enumerate(histories): + for c, places in enumerate(h[5]): + if places: + at = bounds[c] + grouped[c, s] + np.asarray(places) + held[at] = True + hidden_offsets = np.zeros((m, n + 1), np.int64) + np.cumsum( + np.array( + [[len(h[6][c]) for h in histories] for c in range(m)], + np.int64, + ).reshape(m, n), + axis=1, + out=hidden_offsets[:, 1:], + ) + hidden_bounds = np.zeros(m + 1, np.int64) + np.cumsum(hidden_offsets[:, n], out=hidden_bounds[1:]) + changes = [x for c in range(m) for h in histories for x in h[6][c]] + hidden = ( + hidden_bounds, + hidden_offsets, + np.array([t for t, _ in changes], float), + np.array([p for _, p in changes], bool), + ) def system_changes(field: int, dtype) -> np.ndarray: lists = (h[4][field] for h in histories) @@ -180,6 +261,8 @@ def system_changes(field: int, dtype) -> np.ndarray: system_changes(1, np.int64), system_changes(2, np.int64), system_changes(3, bool), + held, + hidden, ) @@ -195,9 +278,11 @@ def simulate( n_jobs, start: int, state=None, + hidden: bool = False, ): """``simulate_timelines``: validated, run, and returned as a - ``TimelineSimulation``.""" + ``TimelineSimulation``; with ``hidden``, with each component's holds + and hidden changes too (``Records.hidden``, for pricing the runs).""" from repyability.rbd._runs import _UNSTREAMED from repyability.rbd.results import TimelineSimulation @@ -275,9 +360,14 @@ def simulate( parts, recorded = tally.histories.data(t_simulation) data = dict(zip(rbd.components, parts)) system = _named(rbd, recorded) + left_out = ( + dict(zip(rbd.components, tally.histories.hidden())) + if hidden + else None + ) finally: np.random.set_state(after) - return TimelineSimulation( + result = TimelineSimulation( system=Timelines._from_data(system), components={ node: Timelines._from_data(d, node) for node, d in data.items() @@ -289,6 +379,7 @@ def simulate( method="event loop", start=start, ) + return (result, left_out) if hidden else result def with_costs( diff --git a/repyability/rbd/_window_report.py b/repyability/rbd/_window_report.py index 3548543f..52a33bc6 100644 --- a/repyability/rbd/_window_report.py +++ b/repyability/rbd/_window_report.py @@ -6,9 +6,10 @@ difference of the values at its two ends. The spread of a cost cannot be differenced: it comes from simulated histories, each cut at every window's end. The simulations of a seeded run draw the same lives -whatever the window, so the runs to each end are the same histories cut -off there, and a simulation's cost in a window is its cost to the -window's end less its cost to the window's start. +whatever the window (an unseeded call draws one seed for all its +runs), so the runs to each end are the same histories cut off there, +and a simulation's cost in a window is its cost to the window's end +less its cost to the window's start. """ import math @@ -137,13 +138,28 @@ def cost_by_window( raise ValueError( f"levels must be percentiles, 0 to 100; got {levels!r}." ) - exact = rbd.expected_cost( - stops, - working_nodes=working_nodes, - broken_nodes=broken_nodes, - method=method, - state=state, - ).mean + from ._covariate_schedule import on_clock + from ._streams import shared_seed + + # Every run below must draw the same histories, so that a window's + # cost is one history's cost to its end less its cost to its start: + # left unseeded, each run drew its own, and their differences could + # be below 0. + seed = shared_seed(seed) + + # A life on the diagram's clock has no exact values: the means are + # then the simulations' own. + exact = ( + None + if on_clock(rbd) + else rbd.expected_cost( + stops, + working_nodes=working_nodes, + broken_nodes=broken_nodes, + method=method, + state=state, + ).mean + ) cumulative = [] for stop in stops: run = rbd.cost( @@ -167,7 +183,7 @@ def cost_by_window( return CostByWindow( starts=np.concatenate(([0.0], stops[:-1])), ends=stops, - mean=_between(exact), + mean=samples.mean(axis=1) if exact is None else _between(exact), simulated_mean=samples.mean(axis=1), standard_error=samples.std(axis=1, ddof=1) / math.sqrt(n), samples=samples, diff --git a/repyability/rbd/_windows.py b/repyability/rbd/_windows.py index 60f5d91c..453476b7 100644 --- a/repyability/rbd/_windows.py +++ b/repyability/rbd/_windows.py @@ -32,10 +32,11 @@ _unplanned, ) from repyability.rbd._common import ( - _DISCOUNT_ROUNDS, - _DISCOUNT_TOLERANCE, + _crew_salaries, + _crew_salaries_to, _discount_pieces, _discount_rate, + _discounted_accrual, _horizons, _matched, _present_horizon, @@ -57,8 +58,6 @@ structure_method, ) -from ._mean_lifetime import _G7_W, _GK_W, _GK_X - if TYPE_CHECKING: pass @@ -127,7 +126,7 @@ def _system_at( over ``[0, horizon]``, as a function of the times; the curves whose bends its integral's pieces follow; and the crews' curve, where a component can wait for a crew (else None).""" - _shutdowns.require_exact(rbd) + _shutdowns.require_over_time(rbd) if rbd._crews_couple(): crew = _curves._crew_curve( rbd, horizon, working_nodes, broken_nodes, method, states @@ -347,7 +346,7 @@ def _window( ``causes``, the system failures each node (or common cause) causes.""" method = structure_method(method) - _shutdowns.require_exact(rbd) + _shutdowns.require_over_time(rbd) windows = nonnegative_times(t) working, broken = rbd._held_nodes(working_nodes, broken_nodes) forced = working | broken @@ -562,6 +561,11 @@ def expected_cost( _mean_cost(node_costs[key]) * events[kind], ) ) + if "capital_cost" in node_costs: + # An upgrade's capital cost, charged at its time whatever the + # unit's state. + paid = ends > rbd._upgrades[node].at + charges.append(("capital", node_costs["capital_cost"] * paid)) rate = node_costs.get("downtime_cost", 0.0) if rate: down = ( @@ -584,6 +588,13 @@ def expected_cost( if rbd._shutdowns: # Each shut's cost, at its start (see _shutdowns). categories["shutdown"] = _shutdowns.cost_before(rbd, ends) + if _crew_salaries(rbd): + # The repair crews' salaries, paid from 0 whatever happens. + categories["crews"] = _crew_salaries_to(rbd, ends) + if "call_out" in counts: + # A call-out crew's fees and its rate while engaged, from the + # crews' chain (see _curves._crew_window). + categories["crews"] = categories["crews"] + counts["call_out"] for name, spec in rbd._maintenance.items(): if not spec.setup_cost: continue @@ -629,9 +640,11 @@ def _discounted_cost( The pieces whose two rules differ most are halved until the differences add up to ``_DISCOUNT_TOLERANCE`` of the integral: ``C`` jumps at scheduled events (tests, block replacements), where - a piece's error only halves with it.""" + a piece's error only halves with it. The crews' salaries, paid at a + steady rate, are discounted in closed form, outside the integral.""" windows = nonnegative_times(t) ends = windows.ravel() + salaries = _crew_salaries(rbd) horizon = float(ends.max()) if ends.size else 0.0 keys: list = [] cell_keys: list = [] @@ -657,6 +670,14 @@ def values(times: np.ndarray) -> np.ndarray: cell_keys.extend(own) rows = [got.mean] rows += [got.by_category[category] for category in _CATEGORIES] + if salaries: + # (Their present value is added in closed form below.) + # (A call-out crew's costs, in the same category, vary with + # the time, and are discounted with the others.) + paid = _crew_salaries_to(rbd, np.append(times, horizon)) + crews = 1 + _CATEGORIES.index("crews") + rows[0] = rows[0] - paid + rows[crews] = rows[crews] - paid rows += [got.by_component[node] for node in keys] if own is not None: rows += [ @@ -664,45 +685,17 @@ def values(times: np.ndarray) -> np.ndarray: ] return np.vstack([np.ravel(row)[:-1] for row in rows]) - def rules(a: np.ndarray, b: np.ndarray): - """The pieces' integrals of ``exp(-r s) C(s)`` by the Kronrod - rule, as rows, and the mean's error, against the Gauss rule.""" - half = 0.5 * (b - a) - x = (0.5 * (a + b))[:, None] + half[:, None] * _GK_X - g = np.exp(-rate * x) * values(x.ravel()).reshape(-1, *x.shape) - kronrod = (g @ _GK_W) * half - return kronrod, np.abs(kronrod[0] - (g[0] @ _G7_W) * half) - with rbd._sharing_curves(): - at_ends = values(ends) - a, b = _discount_pieces(ends, horizon) - pieces, error = rules(a, b) - for _ in range(_DISCOUNT_ROUNDS): - budget = _DISCOUNT_TOLERANCE * abs(float(pieces[0].sum())) - if error.sum() <= budget: - break - # Halve the pieces over their share of the error allowed. - split = error > budget / error.size - middle = 0.5 * (a + b)[split] - halves, errors = rules( - np.concatenate([a[split], middle]), - np.concatenate([middle, b[split]]), - ) - a = np.concatenate([a[~split], a[split], middle]) - b = np.concatenate([b[~split], middle, b[split]]) - pieces = np.concatenate([pieces[:, ~split], halves], axis=1) - error = np.concatenate([error[~split], errors]) - order = np.argsort(b, kind="stable") - running = np.concatenate( - [np.zeros((len(at_ends), 1)), np.cumsum(pieces[:, order], axis=1)], - axis=1, - ) - # Every window is a piece's end: the pieces up to it are within it. - upto = np.searchsorted(b[order], ends, side="right") - present = np.exp(-rate * ends) * at_ends + rate * running[:, upto] + present, _ = _discounted_accrual( + values, ends, rate, _discount_pieces(ends, horizon) + ) rows = iter(present) mean = next(rows) categories = {category: next(rows) for category in _CATEGORIES} + if salaries: + paid = _crew_salaries_to(rbd, ends, rate) + categories["crews"] = categories["crews"] + paid + mean = mean + paid components = {node: next(rows) for node in keys} if cells is not None: cells.update({k: next(rows) for k in cell_keys}) diff --git a/repyability/rbd/bdd.py b/repyability/rbd/bdd.py index c943747b..c18b375f 100644 --- a/repyability/rbd/bdd.py +++ b/repyability/rbd/bdd.py @@ -35,6 +35,7 @@ from typing import ( Any, + Callable, Dict, Hashable, Iterable, @@ -57,7 +58,10 @@ #: about five seconds (a meshed diagram of 60 nodes and 345 edges takes #: ten million). A core that needs more is too meshed to work out #: exactly, and is simulated (see ``modular.GraphStructure``). Raise it to -#: try harder. +#: try harder. The search keeps every state it has met, a few hundred +#: bytes each as Python: at this limit some hundreds of thousands of them, +#: 250 MB at most on the diagrams of ``scripts/bdd_benchmark.py``, so the +#: steps stop a core before its memory does. STEP_LIMIT = 25_000_000 @@ -85,14 +89,18 @@ def order( ) -> List[int]: """A topological order of ``vertices`` that keeps the frontier narrow. - Two orders are tried: a greedy one, which at each step takes the ready - vertex (every predecessor decided) that leaves the smallest frontier, - and the breadth-first one. The one whose frontiers would give the - smaller diagram (the sum over the steps of two to the frontier's size) - is kept.""" + Three orders are tried (``CANDIDATES``): a greedy one, which at each + step takes the ready vertex (every predecessor decided) that leaves + the smallest frontier; the breadth-first one; and a greedy one that + looks a vertex ahead, taking the ready vertex that leaves the smallest + frontier after the best vertex to follow it. The one whose frontiers + would give the smallest diagram (the sum over the steps of two to the + frontier's size) is kept.""" vertices = sorted(vertices) - candidates = [_greedy(vertices, pred, succ, source, sink)] - candidates.append(_breadth_first(vertices, pred, succ, source)) + candidates = [ + candidate(vertices, pred, succ, source, sink) + for candidate in CANDIDATES.values() + ] return min(candidates, key=lambda o: _cost(o, pred, succ, source, sink)) @@ -126,7 +134,7 @@ def _cost(sequence, pred, succ, source, sink) -> float: ) -def _breadth_first(vertices, pred, succ, source) -> List[int]: +def _breadth_first(vertices, pred, succ, source, sink=None) -> List[int]: waiting = {v: sum(1 for u in pred[v] if u != source) for v in vertices} ready = [v for v in vertices if waiting[v] == 0] out: List[int] = [] @@ -143,7 +151,12 @@ def _breadth_first(vertices, pred, succ, source) -> List[int]: return out -def _greedy(vertices, pred, succ, source, sink) -> List[int]: +def _greedy( + vertices, pred, succ, source, sink, ahead: bool = False +) -> List[int]: + """The order that takes, at each step, the ready vertex that leaves + the smallest frontier; with ``ahead``, the smallest after the best + vertex to follow it.""" waiting = {v: sum(1 for u in pred[v] if u != source) for v in vertices} # How many successors each vertex still feeds that are undecided (the # output stays undecided to the end). @@ -153,30 +166,62 @@ def _greedy(vertices, pred, succ, source, sink) -> List[int]: } to_sink = {u for u in [source, *vertices] if sink in succ.get(u, ())} ready = {v for v in vertices if waiting[v] == 0} - out: List[int] = [] - while ready: - def score(v: int) -> tuple: - # The frontier's change: v joins it (it feeds something), and - # each predecessor whose last undecided successor v is leaves. - closes = sum( - 1 for u in pred[v] if feeding[u] == 1 and u not in to_sink - ) - return (1 - closes, v) + def change(v: int) -> int: + # The frontier's change: v joins it (it feeds something), and + # each predecessor whose last undecided successor v is leaves. + closes = sum( + 1 for u in pred[v] if feeding[u] == 1 and u not in to_sink + ) + return 1 - closes - v = min(ready, key=score) - ready.discard(v) - out.append(v) + def decide(v: int, step: int) -> None: + # Decide v (step 1), or take the decision back (step -1). for u in pred[v]: - feeding[u] -= 1 + feeding[u] -= step for w in succ.get(v, ()): if w in waiting: - waiting[w] -= 1 + waiting[w] -= step if waiting[w] == 0: ready.add(w) + else: + ready.discard(w) + + def score(v: int) -> tuple: + first = change(v) + if not ahead: + return (first, v) + ready.discard(v) + decide(v, 1) + then = min((change(w) for w in ready), default=0) + decide(v, -1) + ready.add(v) + return (first + then, first, v) + + out: List[int] = [] + while ready: + # A list of them: looking ahead takes vertices from the set and + # puts them back. + v = min(sorted(ready), key=score) + ready.discard(v) + out.append(v) + decide(v, 1) return out +def _look_ahead(vertices, pred, succ, source, sink) -> List[int]: + return _greedy(vertices, pred, succ, source, sink, ahead=True) + + +#: The orders ``order`` chooses from, by name; of equal costs it keeps +#: the earlier one. +CANDIDATES: Dict[str, Callable[..., List[int]]] = { + "greedy": _greedy, + "breadth first": _breadth_first, + "look ahead": _look_ahead, +} + + def build( sequence: Sequence[int], pred: Mapping[int, Iterable[int]], diff --git a/repyability/rbd/ccf.py b/repyability/rbd/ccf.py index 06ffd1ee..89d52b8d 100644 --- a/repyability/rbd/ccf.py +++ b/repyability/rbd/ccf.py @@ -65,6 +65,10 @@ VALIDITY = 0.1 +#: The most members a ``Shocks`` group may have (``shocks.MAX_MEMBERS``). +MAX_SHOCKED = 10 + + def _check_basis(basis: str) -> str: if basis not in BASES: raise ValueError( @@ -333,6 +337,14 @@ class BetaFactor(_Model): any size. Use it through a [`CCFGroup`][repyability.CCFGroup]; models with equal ``beta`` and ``basis`` compare equal. + **Which basis.** The default, ``basis="probability"``, splits each + member's probability of failing over a mission or a proof-test + interval, where it is small. For a whole life, pass + ``basis="rate"``: the RBD's exact ``mean`` (MTTF) refuses the + probability split, its simulated lifetimes leave such a group out, + and its ``sf`` warns once a member's probability of failing passes + 0.1. + ``basis`` says what ``beta`` is a fraction of. By default, ``"probability"``, of each member's probability of failing ``Q``: the shared cause fails the group with ``beta * Q``, and each member fails @@ -968,11 +980,138 @@ def __repr__(self) -> str: ) +class Shocks(_Model): + """Shocks from outside a group, at a rate of their own. + + Shocks arrive at ``rate``, whatever the members' ages, and each fails + each member of the group independently with probability ``p`` (the + binomial failure rate model); shocks of a second kind, at + ``lethal_rate``, fail every member. Unlike the other models, which + split the failures the members' own model describes, the shocks are + added to them: each member keeps its own life, of any kind, for its + other failures, and the members need not be alike. + + By thinning, the shocks are an independent cause for each set of + members: the cause that fails exactly a set of ``j`` of the ``m`` + members strikes at rate ``rate * p**j * (1 - p)**(m - j)`` (plus + ``lethal_rate`` for the set of all of them). + + A [`NonRepairableRBD`][repyability.NonRepairableRBD] writes each + cause into its structure as an exponential component after every + member it fails, exactly as + [`shock_nodes`][repyability.shock_nodes] does, so every analysis + takes the shocks, given each member's own age too, and the causes are + named among its nodes. A [`RepairableRBD`][repyability.RepairableRBD] + simulates them (its exact methods refuse, naming the simulation): a + strike fails the members it names that are up, in the group's order, + each then repaired, or found at its test, on its own. + + Parameters + ---------- + rate : float + Shocks per unit of time; 0 or more. + p : float, optional + The probability that a shock fails a member, in (0, 1]; by + default 1 (every shock fails every member). + lethal_rate : float, optional + Shocks per unit of time that fail every member; by default 0. + + Raises + ------ + ValueError + If a rate is negative or not a number, both rates are 0, or + ``p`` is not in (0, 1]. + + Examples + -------- + >>> from repyability import CCFGroup, Shocks + >>> CCFGroup(["p1", "p2"], Shocks(rate=2e-5, p=0.6)) + CCFGroup(members=['p1', 'p2'], model=Shocks(rate=2e-05, p=0.6)) + """ + + basis = "shocks" + + def __init__(self, rate: float, p: float = 1.0, lethal_rate: float = 0.0): + from .shocks import checked + + self.rate, self.p, self.lethal_rate = checked(rate, p, lethal_rate) + if self.rate == 0.0 and self.lethal_rate == 0.0: + raise ValueError( + "Shocks needs a rate above 0 (rate, or lethal_rate): with " + "both 0 no shock ever comes." + ) + + def required_group_size(self) -> Any: + """Any group of two or more (up to ``shocks.MAX_MEMBERS``).""" + return None + + def _no_split(self) -> NotImplementedError: + """What asks for the model's split of its members' failures + gets: it has none.""" + return NotImplementedError( + f"{self!r} adds shocks at a rate of their own to its members' " + "own lives and splits nothing, so no chain or split of the " + "group follows it. Estimate a repairable diagram's values by " + "simulation, with availability() or cost()." + ) + + def _causes(self, members) -> Tuple[float, list]: + raise self._no_split() + + def _split(self, members, Q, R) -> tuple: + raise self._no_split() + + def _by_rate(self) -> "_Model": + raise self._no_split() + + def causes(self, members) -> List[Tuple[tuple, float]]: + """The independent causes the shocks are, by thinning. + + Parameters + ---------- + members : sequence of hashable + The group's members, in its order. + + Returns + ------- + list of (tuple, float) + Each cause, as the members it fails (in the group's order) + and the rate it strikes at: every set of members a shock can + fail exactly, smaller sets first; those of rate 0 left out. + """ + from .shocks import causes + + return causes(tuple(members), self.rate, self.p, self.lethal_rate) + + def __eq__(self, other: object) -> bool: + return isinstance(other, Shocks) and ( + other.rate, + other.p, + other.lethal_rate, + ) == (self.rate, self.p, self.lethal_rate) + + def __hash__(self) -> int: + return hash(("Shocks", self.rate, self.p, self.lethal_rate)) + + def __repr__(self) -> str: + lethal = ( + f", lethal_rate={self.lethal_rate}" if self.lethal_rate else "" + ) + return f"Shocks(rate={self.rate}, p={self.p}{lethal})" + + def parameters(model) -> Dict[str, float]: """A common-cause model's parameters by name: a ``BetaFactor``'s ``beta``, an ``MGL`` model's letters (``beta``, ``gamma``, ``delta``, ...), an ``AlphaFactor`` model's ``alpha_2``, ..., ``alpha_m`` - (``alpha_1`` being the remainder).""" + (``alpha_1`` being the remainder), a ``Shocks`` model's ``rate``, ``p`` + and ``lethal_rate``.""" + if isinstance(model, Shocks): + return { + "rate": model.rate, + "p": model.p, + "lethal_rate": model.lethal_rate, + } if isinstance(model, BetaFactor): return {"beta": model.beta} if isinstance(model, AlphaFactor): @@ -985,11 +1124,20 @@ def parameters(model) -> Dict[str, float]: } +def parameter_bounds(model, name: str) -> Tuple[float, float]: + """The range of a common-cause model's parameter ``name`` (see + ``parameters``): ``[0, 1]`` for a fraction or a probability, 0 and up + for a ``Shocks`` model's rates.""" + if isinstance(model, Shocks) and name != "p": + return (0.0, float("inf")) + return (0.0, 1.0) + + def with_parameters(model, values: Dict[str, float]) -> "_Model": """``model`` with the parameters ``values`` names changed (see ``parameters``), its basis kept: a ``ValueError`` for one outside - ``[0, 1]``, a name it does not have, or alpha factors summing past - 1.""" + its range (``parameter_bounds``), a name it does not have, or alpha + factors summing past 1.""" current = parameters(model) unknown = [name for name in values if name not in current] if unknown: @@ -998,6 +1146,8 @@ def with_parameters(model, values: Dict[str, float]) -> "_Model": f"parameters are {list(current)}." ) current.update({name: float(v) for name, v in values.items()}) + if isinstance(model, Shocks): + return Shocks(**current) if isinstance(model, BetaFactor): return BetaFactor(current["beta"], basis=model.basis) if isinstance(model, AlphaFactor): @@ -1028,13 +1178,15 @@ def validity_warning(group: "CCFGroup", Q: float) -> None: model = group.model rate = model._by_rate() warnings.warn( - f"Common-cause group {list(group.members)} ({model!r}): its " - f"members' probability of failing reaches Q = {Q:.3g} at the times " - f"evaluated, beyond the {VALIDITY} the probability split is meant " - "for. It is a rare-event model: about 3.5% off a rate-based split " - "at Q = 0.1 and further beyond, and from about Q = 0.5 it makes a " - "redundant group more reliable than an independent one. Over a " - f"lifetime, split the failure rate: {rate!r}.", + f"Common-cause group {list(group.members)} ({model!r}) splits " + "each member's probability of failing (basis='probability', the " + f"default): its members' probability of failing reaches Q = " + f"{Q:.3g} at the times evaluated, beyond the {VALIDITY} that split " + "is meant for. It is a rare-event model: about 3.5% off a " + "rate-based split at Q = 0.1 and further beyond, and from about " + "Q = 0.5 it makes a redundant group more reliable than an " + "independent one. Over a lifetime (Q past 0.1, an MTTF, a " + f"simulation), split the failure rate: {rate!r}.", UserWarning, # Point at the first caller outside the package. stacklevel=outside_level(), @@ -1132,7 +1284,8 @@ def __init__(self, members: Collection[Hashable], model: Any): ) if not isinstance(model, _Model): raise ValueError( - "CCFGroup model must be a BetaFactor, MGL or AlphaFactor, " + "CCFGroup model must be a BetaFactor, MGL, AlphaFactor or " + "Shocks, " f"got {model!r}." ) required = model.required_group_size() @@ -1164,7 +1317,9 @@ def as_groups(groups) -> list: return list(groups) -def checked_groups(groups, check_member, saved, unlike, noun="Node") -> list: +def checked_groups( + groups, check_member, saved, unlike, noun="Node", shocks=False +) -> list: """The common-cause ``groups``, checked as every diagram and tree checks them: each a ``CCFGroup``, each member passing ``check_member(member, group)`` (which raises for one that cannot be in @@ -1182,6 +1337,14 @@ def checked_groups(groups, check_member, saved, unlike, noun="Node") -> list: "ccf_groups must contain CCFGroup instances, got " f"{type(group).__name__}." ) + if isinstance(group.model, Shocks) and not shocks: + raise ValueError( + f"{group!r}: shocks at a rate of their own are taken by a " + "NonRepairableRBD, which writes their causes into its " + "structure, and simulated by a RepairableRBD, not here. " + "For a shock that fails every member, add an event or a " + "node in series with them." + ) for member in group.members: check_member(member, group) if member in seen: @@ -1189,6 +1352,15 @@ def checked_groups(groups, check_member, saved, unlike, noun="Node") -> list: f"{noun} {member!r} appears in more than one CCF group." ) seen.add(member) + if isinstance(group.model, Shocks): + # Shocks add to the members' own lives, which may differ. + if len(group.members) > MAX_SHOCKED: + raise ValueError( + f"{group!r}: a shock process has a cause for each set " + f"of its members, so it takes up to {MAX_SHOCKED}, " + f"got {len(group.members)}." + ) + continue try: forms = [saved(member) for member in group.members] except SAVE_ERRORS: diff --git a/repyability/rbd/contracts.py b/repyability/rbd/contracts.py new file mode 100644 index 00000000..b49686c5 --- /dev/null +++ b/repyability/rbd/contracts.py @@ -0,0 +1,232 @@ +"""Contract terms that pay on how a system performed, as plain data: an +:class:`AvailabilityContract` pays a bonus or charges a penalty in each +period by the system's availability in it (see +``RepairableRBD.npv_distribution``).""" + +import dataclasses +import math +from typing import Any, Dict, Optional, Tuple, Union + +import numpy as np + +from repyability.utils.checks import is_number + + +def _amount(value, name: str) -> float: + if not is_number(value) or not (math.isfinite(value) and value >= 0.0): + raise ValueError( + f"{name} must be a finite number, 0 or more; got {value!r}." + ) + return float(value) + + +@dataclasses.dataclass(frozen=True) +class AvailabilityContract: + """An availability contract: in each period, a penalty for every point + of availability below a target, and a bonus for every point above it. + + In plain terms: the system's availability in a period is the share of + the period it was up. A point is one percentage point of it (0.01): + a period at 93% against a target of 95% falls 2 points short, and + costs ``2 * penalty_per_point``; at 96% it is 1 point over, and earns + ``bonus_per_point``. Part points pay in proportion. ``cap`` limits + what one period can charge or pay, either way. Each period's payment + falls at the period's end. An expected value cannot price such terms, + as they pay on thresholds; ``npv_distribution(contract=...)`` prices + them run by run. + + Parameters + ---------- + periods : float or sequence of float + A number: the length of each period, the periods back to back from + 0 (the time after the last whole period within the horizon is not + measured). A sequence: the periods' ends, increasing from more + than 0, each period from the end of the one before (the first + from 0); every end must be within the horizon valued. In the + component models' unit. + target : float + The availability the contract asks for, from 0 to 1. + penalty_per_point : float + What each point below ``target`` costs in a period, 0 or more. + bonus_per_point : float, optional + What each point above ``target`` earns in a period, 0 or more, by + default 0. + cap : float, optional + The most one period's penalty, or bonus, can be, more than 0. By + default None: no limit. + + Raises + ------ + ValueError + If ``periods`` is not a positive length or an increasing sequence + of positive ends, ``target`` is not from 0 to 1, a price is + negative or not finite, or ``cap`` is not more than 0. + + Examples + -------- + Monthly periods of 730 hours, a target of 95%, 1,000 for each point + short and 400 for each point over, at most 10,000 a month: + + >>> from repyability import AvailabilityContract + >>> terms = AvailabilityContract( + ... 730.0, target=0.95, penalty_per_point=1000.0, + ... bonus_per_point=400.0, cap=10_000.0, + ... ) + >>> [round(float(x), 6) for x in terms.payoff([0.93, 0.96, 0.5])] + [-2000.0, 400.0, -10000.0] + >>> terms.period_ends(2200.0) + (730.0, 1460.0, 2190.0) + """ + + periods: Union[float, Tuple[float, ...]] + target: float + penalty_per_point: float + bonus_per_point: float = 0.0 + cap: Optional[float] = None + + def __post_init__(self): + periods: Any = self.periods + if is_number(periods): + if not (math.isfinite(periods) and periods > 0.0): + raise ValueError( + "periods must be a period's length, a finite number " + f"more than 0, or the periods' ends; got {periods!r}." + ) + periods = float(periods) + else: + try: + ends = tuple(float(end) for end in periods) + except (TypeError, ValueError): + raise ValueError( + "periods must be a period's length or a sequence of " + f"the periods' ends; got {periods!r}." + ) from None + steps = np.diff((0.0,) + ends) + if ( + not ends + or not all(math.isfinite(end) for end in ends) + or np.any(steps <= 0.0) + ): + raise ValueError( + "The periods' ends must be finite and increasing, the " + f"first more than 0; got {periods!r}." + ) + periods = ends + object.__setattr__(self, "periods", periods) + target = self.target + if not is_number(target) or not 0.0 <= target <= 1.0: + raise ValueError( + "target must be an availability from 0 to 1 (95% is " + f"0.95); got {target!r}." + ) + object.__setattr__(self, "target", float(target)) + for name in ("penalty_per_point", "bonus_per_point"): + object.__setattr__(self, name, _amount(getattr(self, name), name)) + if self.cap is not None: + cap = self.cap + if not is_number(cap) or not cap > 0.0: + raise ValueError( + "cap must be more than 0, or None for no limit; got " + f"{cap!r}." + ) + object.__setattr__(self, "cap", float(cap)) + + def period_ends(self, horizon: float) -> Tuple[float, ...]: + """The ends of the periods measured over ``[0, horizon]``. + + Parameters + ---------- + horizon : float + The length of time valued. + + Returns + ------- + tuple of float + Each period's end, in order. + + Raises + ------ + ValueError + If a period's end given is after ``horizon``, or no whole + period of the length given fits in it. + """ + horizon = float(horizon) + if isinstance(self.periods, tuple): + if self.periods[-1] > horizon: + raise ValueError( + f"The contract's last period ends at " + f"{self.periods[-1]:g}, after the horizon " + f"{horizon:g}: value a horizon that holds every " + "period, or leave the later periods out." + ) + return self.periods + count = math.floor(round(horizon / self.periods, 9)) + if count < 1: + raise ValueError( + f"No whole period of {self.periods:g} fits in the horizon " + f"{horizon:g}: value a longer horizon, or give shorter " + "periods." + ) + return tuple(self.periods * k for k in range(1, count + 1)) + + def payoff(self, availability) -> np.ndarray: + """What a period with each availability pays: positive a bonus, + negative a penalty. + + Parameters + ---------- + availability : array_like + Availabilities, each from 0 to 1. + + Returns + ------- + numpy.ndarray + The payments, of the same shape. + """ + points = 100.0 * (np.asarray(availability, float) - self.target) + paid = np.where( + points >= 0.0, + self.bonus_per_point * points, + self.penalty_per_point * points, + ) + if self.cap is not None: + paid = np.clip(paid, -self.cap, self.cap) + return paid + 0.0 + + def to_dict(self) -> Dict[str, Any]: + """The terms as plain data, ready for ``json.dumps`` + (``from_dict`` reads them back). + + Returns + ------- + dict + ``periods`` (a length, or a list of ends), ``target``, + ``penalty_per_point``, ``bonus_per_point`` and ``cap``. + """ + return { + "periods": ( + list(self.periods) + if isinstance(self.periods, tuple) + else self.periods + ), + "target": self.target, + "penalty_per_point": self.penalty_per_point, + "bonus_per_point": self.bonus_per_point, + "cap": self.cap, + } + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "AvailabilityContract": + """The terms ``to_dict`` wrote. + + Parameters + ---------- + data : dict + The plain data. + + Returns + ------- + AvailabilityContract + The contract. + """ + return cls(**data) diff --git a/repyability/rbd/joint_node.py b/repyability/rbd/joint_node.py index 3df5e782..70500470 100644 --- a/repyability/rbd/joint_node.py +++ b/repyability/rbd/joint_node.py @@ -18,6 +18,7 @@ ``NodeState`` age (see ``NonRepairableRBD.sf_given_state``). """ +import sys from typing import Any, Optional import numpy as np @@ -38,10 +39,16 @@ def _joint_classes() -> tuple: - """surpyval's ``JointModel`` and ``DynamicPrediction``. (The latter - has no public home in surpyval yet, so it comes from its module.)""" - from surpyval import JointModel - from surpyval.univariate.joint import DynamicPrediction + """surpyval's ``JointModel`` and ``DynamicPrediction``, or ``()`` + while surpyval's joint models are not imported. + + A model can only be one of them once their module is imported, so + until then nothing is imported to check: importing them loads + surpyval's regression and degradation code with pandas, which took + about 2 s of a session's first diagram.""" + if "surpyval.univariate.joint" not in sys.modules: + return () + from surpyval.univariate.joint import DynamicPrediction, JointModel return JointModel, DynamicPrediction @@ -55,8 +62,8 @@ def is_joint(model) -> bool: def as_node(model): """``model``, but a surpyval ``DynamicPrediction`` as the ``JointNode`` of its unit (a diagram takes a prediction as a node).""" - _, prediction = _joint_classes() - if isinstance(model, prediction): + classes = _joint_classes() + if classes and isinstance(model, classes[1]): return JointNode(model) return model diff --git a/repyability/rbd/non_repairable_rbd.py b/repyability/rbd/non_repairable_rbd.py index 61ba1e2f..7a67a189 100644 --- a/repyability/rbd/non_repairable_rbd.py +++ b/repyability/rbd/non_repairable_rbd.py @@ -75,7 +75,14 @@ ) from ._overrides import life_now, unit_life from ._sampling import RowSampler, column, inverse_sampler, row_sampler -from .ccf import VALIDITY, BetaFactor, CCFGroup, as_groups, checked_groups +from .ccf import ( + VALIDITY, + BetaFactor, + CCFGroup, + Shocks, + as_groups, + checked_groups, +) from .ccf import parameters as ccf_parameters from .ccf import shock_outcomes, validity_warning from .ccf import with_parameters as with_ccf_parameters @@ -110,6 +117,7 @@ UncertaintyResult, ) from .routes import EXACT, NUMERICAL, AnalysisRoute, Refused, model_route +from .shocks import written_shocks from .standby_node import StandbyModel from .uncertainty import ( GIVEN, @@ -696,6 +704,28 @@ def __init__( "ccf_groups": ccf_groups, "capacity": dict(capacity) if capacity else None, } + # Shocks at a rate of their own are written into the structure, + # each cause an exponential component after every member it fails + # (``shock_nodes``): from here on the diagram is the one written + # out, as if given so, and it is saved as it was given + # (``_given_args``). + self.shock_groups = [ + g for g in ccf_groups if isinstance(g.model, Shocks) + ] + if self.shock_groups: + self._given_args = dict(self._init_args) + ccf_groups = [ + g for g in ccf_groups if not isinstance(g.model, Shocks) + ] + edges, reliabilities = written_shocks( + edges, reliabilities, self.shock_groups + ) + self._init_args = { + **self._init_args, + "edges": [tuple(e) for e in edges], + "reliabilities": dict(reliabilities), + "ccf_groups": ccf_groups, + } reliabilities = copy(reliabilities) for key, value in reliabilities.items(): if key == value: @@ -1096,6 +1126,13 @@ def _ccf_measure( _, Q = self._ccf_system_pair(p, q, working, broken) with np.errstate(divide="ignore", invalid="ignore"): return {node: shares[node] / Q for node in self.nodes} + return self._ccf_measure_at(measure, p, q, working, broken, kind) + + def _ccf_measure_at( + self, measure: str, p, q, working, broken, kind: str = "failure" + ) -> Dict[Any, Union[float, np.ndarray]]: + """``_ccf_measure`` (but Fussell-Vesely) at the nodes' given + probabilities of working ``p`` and of failing ``q``.""" evaluation = self._ccf_evaluation(p, q, working, broken) R, Q = (np.atleast_1d(value) for value in evaluation.system()) out: Dict[Any, Union[float, np.ndarray]] = {} @@ -1431,17 +1468,49 @@ def _check_ccf_validity(self, index: int, group, Q: np.ndarray) -> None: warned.add(index) validity_warning(group, largest) - def _require_no_ccf_for_states(self) -> None: - """Raise if the RBD has CCF groups, for the condition-based methods - (``sf_given_state``, ``remaining_life``, - ``importances_given_state``).""" - if self.ccf_groups: - raise NotImplementedError( - "Condition-based evaluation (sf_given_state / remaining_life " - "/ importances_given_state) does not yet account for " - "common-cause (CCF) groups; use sf()/ff() for CCF system " - "reliability." - ) + def _require_ccf_states(self, state: Optional[dict] = None) -> None: + """Raise where the condition-based methods (``sf_given_state``, + ``remaining_life``, ``mean_residual_life``, + ``importances_given_state``) cannot take the RBD's common-cause + groups: a group splitting a probability (which says nothing of a + member's age), and, given the validated ``state``, a group whose + members are not all in one state. A group splitting the failure + rate gives its shared causes a share of the members' hazard, which + is one hazard only while the members are the same age.""" + for group in self.ccf_groups: + if group.model.basis != "rate": + raise NotImplementedError( + "Condition-based evaluation (sf_given_state / " + "remaining_life / mean_residual_life / " + "importances_given_state) does not take common-cause " + f"group {list(group.members)!r}, which splits a " + "probability of failing: that says nothing of a " + "member's age. For members of one age, split the " + f"failure rate ({group.model._by_rate()!r}); for " + "members of different ages, draw the shared cause as a " + "node in series with them (the guide's 'Common causes " + "with wear-out lives and ages'). sf()/ff() give the " + "reliability from new." + ) + if state is None: + continue + given = [state.get(member) for member in group.members] + if any(one != given[0] for one in given[1:]) or ( + given[0] is not None and not given[0].alive + ): + raise NotImplementedError( + "The members of common-cause group " + f"{list(group.members)!r} must be in one state for the " + "condition-based methods: alive, at one age (and of one " + "model and level, if given). The group's shared causes " + "take a share of the members' hazard, which is one " + "hazard only while the members are the same age; the " + "states given differ, or a member has failed. For " + "members of different ages, draw the shared cause as a " + "node in series with them, an exponential shock or a " + "repeated node (the guide's 'Common causes with " + "wear-out lives and ages')." + ) def _allocation_groups(self, nodes, options, ways) -> dict: """The common-cause group of each costed node in one, for redundancy @@ -3046,6 +3115,7 @@ def allocate_redundancy( required: Union[int, Dict[Hashable, int], None] = None, strategy: Union[str, Dict[Hashable, str]] = "active", switching_probability: Union[float, Dict[Hashable, float]] = 1.0, + start_probability: Union[float, Dict[Hashable, float]] = 1.0, mixing: bool = True, method: str = "exact", ) -> RedundancyAllocation: @@ -3153,8 +3223,17 @@ def allocate_redundancy( switching_probability : float or dict, optional For cold standby, the probability that switching onto a spare succeeds, for every cold node (a number) or particular ones (a - dict). By default 1.0 (perfect switching). Imperfect switching - is supported with one unit required. + dict). By default 1.0 (perfect switching). A failed switch + ends the arrangement. Imperfect switching is supported with one + unit required. + start_probability : float or dict, optional + For cold standby, the probability that a spare starts once + switched in, for every cold node (a number) or particular ones + (a dict): a spare that fails to start is skipped, and the next + one is tried, as a + [`StandbyModel`][repyability.StandbyModel]'s + ``start_probability`` (and a standby block's) means. By default + 1.0. Give it or ``switching_probability``, not both. mixing : bool, optional For nodes with options: whether their copies may be of different types (the default), or must all be of one type. @@ -3195,7 +3274,8 @@ def allocate_redundancy( number with several resources; a node nothing limits (see ``max_units``); an invalid ``max_units``, ``minimise``, ``mixing``, ``required`` (or one above ``max_units``), - ``strategy`` or ``switching_probability``; cold standby of a + ``strategy``, ``switching_probability`` or + ``start_probability`` (or both of the last two); cold standby of a fixed probability; ``t`` missing for a time-varying RBD or not a single number; a budget that cannot afford the required copies of each costed node; a ``target`` outside (0, 1) or not @@ -3314,6 +3394,7 @@ def allocate_redundancy( required, strategy, switching_probability, + start_probability, mixing, method, ) @@ -3479,6 +3560,7 @@ def _redundancy_problem( required, strategy, switching_probability, + start_probability, mixing, method, ) -> SimpleNamespace: @@ -3531,6 +3613,15 @@ def _redundancy_problem( switching = self._redundancy_switching( nodes, switching_probability, ways, fewest ) + starts = self._redundancy_switching( + nodes, start_probability, ways, fewest, "start_probability" + ) + if any(p < 1.0 for p in switching) and any(p < 1.0 for p in starts): + raise ValueError( + "Give switching_probability (a failed switch ends the " + "arrangement) or start_probability (a spare that fails to " + "start is skipped, and the next one is tried), not both." + ) grouped = self._allocation_groups(nodes, options, ways) # The lifetime (or probability) model of one copy of each kind. models = [ @@ -3678,6 +3769,7 @@ def unreliability(counts: tuple) -> float: units, k=fewest[i], switching_probability=switching[i], + start_probability=starts[i], ) if standby.is_simulated: raise NotImplementedError( @@ -3926,15 +4018,22 @@ def _redundancy_strategies(nodes, strategy) -> list: return [choices[given[node]] for node in nodes] @staticmethod - def _redundancy_switching(nodes, switching_probability, ways, fewest): + def _redundancy_switching( + nodes, + switching_probability, + ways, + fewest, + name: str = "switching_probability", + ): """The probability that switching onto each costed node's next cold - spare succeeds.""" + spare succeeds (or, as ``name="start_probability"``, that each + spare starts once switched in).""" cold = [node for node, way in zip(nodes, ways) if "cold" in way] if isinstance(switching_probability, dict): for node in switching_probability: if node not in cold: raise ValueError( - "switching_probability applies to cold standby, and " + f"{name} applies to cold standby, and " f"node {node!r} is not a cold standby node in costs." ) given = { @@ -3943,7 +4042,7 @@ def _redundancy_switching(nodes, switching_probability, ways, fewest): else: if float(switching_probability) != 1.0 and not cold: raise ValueError( - "switching_probability applies to cold standby, which no " + f"{name} applies to cold standby, which no " "node uses (see strategy)." ) given = {node: switching_probability for node in nodes} @@ -3952,10 +4051,12 @@ def _redundancy_switching(nodes, switching_probability, ways, fewest): rho = float(given[node]) if not 0.0 <= rho <= 1.0: raise ValueError( - f"switching_probability for node {node!r} must be in " + f"{name} for node {node!r} must be in " f"[0, 1], got {given[node]!r}." ) - if rho < 1.0 and "cold" in way and k > 1: + if name == "switching_probability" and ( + rho < 1.0 and "cold" in way and k > 1 + ): raise ValueError( "Imperfect switching is supported for cold standby with " f"one unit required; node {node!r} requires {k}." @@ -4194,6 +4295,7 @@ def redundancy_front( required: Union[int, Dict[Hashable, int], None] = None, strategy: Union[str, Dict[Hashable, str]] = "active", switching_probability: Union[float, Dict[Hashable, float]] = 1.0, + start_probability: Union[float, Dict[Hashable, float]] = 1.0, mixing: bool = True, ) -> List[RedundancyAllocation]: """The whole cost-reliability trade-off of redundancy allocation. @@ -4236,6 +4338,8 @@ def redundancy_front( ``allocate_redundancy``. switching_probability : float or dict, optional For cold standby, as for ``allocate_redundancy``. + start_probability : float or dict, optional + For cold standby, as for ``allocate_redundancy``. mixing : bool, optional Whether a node's copies may mix types, as for ``allocate_redundancy``. @@ -4296,6 +4400,7 @@ def redundancy_front( required, strategy, switching_probability, + start_probability, mixing, "exact", ) @@ -5238,7 +5343,7 @@ def built(route, reason): ) fixed = r.refusal(self._require_time_varying) give( - ("time_to_reliability", "bx_life"), + ("time_to_reliability", "bx_life", "qf"), ( r.refused(fixed) if fixed @@ -5376,7 +5481,13 @@ def built(route, reason): if stateless else "" ) - states = r.refusal(self._require_no_ccf_for_states) + if grouped: + note += ( + " A common-cause group's members are given one state " + "(alive, at one age): its causes share the members' " + "hazard from that age." + ) + states = r.refusal(self._require_ccf_states) give( ("sf_given_state", "importances_given_state"), ( @@ -7024,6 +7135,61 @@ def time_to_reliability( lambda t: float(self.sf(t, **kwargs)), target, upper_bound ) + def qf(self, p, **kwargs): + """The time by which a share ``p`` of systems have failed: the + inverse of [`ff`][repyability.NonRepairableRBD.ff], for each ``p`` + in [0, 1], so a diagram can be a unit's life. + + Each time is found to near machine precision in both tails: a + share up to a half solves ``ff(t) = p`` and a larger one ``sf(t) = + 1 - p``, each on the logarithms of time and probability, by false + position kept to a bracket (the Illinois rule) from a bracket + doubled out from the median. A share no more than the chance of + having failed at 0 gives 0, and 1 gives ``inf``. + + Parameters + ---------- + p : float or array_like + The shares failed, each in [0, 1]. + **kwargs + Keyword arguments of ``sf`` (``working_nodes``, + ``broken_nodes``, ``method``). + + Returns + ------- + float or numpy.ndarray + A time for each share (a float for a single one). + + Examples + -------- + >>> import math + >>> import surpyval as surv + >>> from repyability import NonRepairableRBD + >>> pair = NonRepairableRBD( + ... [("s", "a"), ("s", "b"), ("a", "t"), ("b", "t")], + ... {n: surv.Exponential.from_params([0.01]) for n in "ab"}, + ... ) + >>> t = pair.qf(0.25) # (1 - exp(-0.01 t))**2 = 0.25 + >>> round(t, 6), round(-100 * math.log(1 - 0.5), 6) + (69.314718, 69.314718) + """ + self._require_time_varying() + given = np.asarray(p, dtype=float) + shares = np.atleast_1d(given).ravel() + if not np.all((shares >= 0.0) & (shares <= 1.0)): + raise ValueError( + "qf takes shares failed in [0, 1] (a probability of " + f"failing by the time); got {p!r}." + ) + out = np.empty_like(shares) + at_start = float(self.ff(0.0, **kwargs)) + out[shares <= at_start] = 0.0 + out[shares == 1.0] = np.inf + todo = (shares > at_start) & (shares < 1.0) + if np.any(todo): + out[todo] = _invert_life(self, shares[todo], kwargs) + return float(out[0]) if given.ndim == 0 else out.reshape(given.shape) + def _invert_reliability( self, sf_func, @@ -7160,8 +7326,8 @@ def _state_node_probabilities(self, x, state) -> Dict[Any, ArrayLike]: of its own model if its state gives one; one at a measured level, the first passage from it (see ``_overrides.life_now``). """ - self._require_no_ccf_for_states() state = self._validate_state(state) + self._require_ccf_states(state) node_probabilities: Dict[Any, ArrayLike] = {} for node_name, model in self.reliabilities.items(): node_state = state.get(node_name) @@ -7242,7 +7408,10 @@ def sf_given_state( node), or a node whose model is a standby, load-sharing or repeated node or a nested RBD. NotImplementedError - If the RBD has common-cause (CCF) groups. + If the RBD has a common-cause (CCF) group that splits a + probability, or one whose members are not given one state + (alive, at one age): a group splitting the failure rate is + taken at its members' common age. Notes ----- @@ -7272,6 +7441,12 @@ def sf_given_state( if state is None: state = {} node_probabilities = self._state_node_probabilities(x, state) + if self.ccf_groups: + # Each cause's share of the members' cumulative hazard from + # their age on: the split at the conditional probabilities. + return self._ccf_system_probability( + node_probabilities, set(), set(), method + ) return self.system_probability(node_probabilities, method=method) def remaining_life( @@ -7396,7 +7571,8 @@ def mean_residual_life( If the RBD is fixed-probability (its reliability does not change with time), or as for ``sf_given_state``. NotImplementedError - As for ``sf_given_state`` (common-cause groups). + As for ``sf_given_state`` (common-cause groups it cannot + take). Examples -------- @@ -7416,7 +7592,7 @@ def mean_residual_life( """ if state is None: state = {} - self._require_no_ccf_for_states() + self._require_ccf_states() self._require_lifetimes() # Each model's knots, moved back by its age where it has one. knots, kinks = [np.empty(0)], [np.empty(0)] @@ -7505,7 +7681,8 @@ def importances_given_state( invalid (as for ``sf_given_state``), or ``kind`` is neither ``"failure"`` nor ``"success"``. NotImplementedError - If the RBD has common-cause (CCF) groups. + As for ``sf_given_state`` (common-cause groups it cannot + take). Examples -------- @@ -7536,8 +7713,25 @@ def importances_given_state( scalar_in = np.ndim(x) == 0 x_arr = np.atleast_1d(np.asarray(x, dtype=float)) node_probabilities = self._state_node_probabilities(x_arr, state) - birnbaum = super()._birnbaum_importance(node_probabilities) - criticality = super()._criticality_importance(node_probabilities, kind) + if self.ccf_groups: + one_of("kind", kind, ("failure", "success")) + failures = { + node: 1.0 - np.asarray(value, dtype=float) + for node, value in node_probabilities.items() + } + birnbaum: Dict[Any, Any] + criticality: Dict[Any, Any] + birnbaum, criticality = ( + self._ccf_measure_at( + measure, node_probabilities, failures, set(), set(), kind + ) + for measure in ("birnbaum", "criticality") + ) + else: + birnbaum = super()._birnbaum_importance(node_probabilities) + criticality = super()._criticality_importance( + node_probabilities, kind + ) def _squeeze(measure): return { @@ -8922,3 +9116,76 @@ def _life_end( return life_end( lambda t: self._sf_and_ff(t, working_nodes, broken_nodes)[0], knots ) + + +def _invert_life(rbd, shares: np.ndarray, kwargs: dict) -> np.ndarray: + """The times at which ``rbd`` has failed with probability ``shares`` + (each strictly between its chance at 0 and 1), for ``qf``: on the + lower half ``log ff(t) = log p`` and on the upper ``log sf(t) = + log(1 - p)``, in ``log t``, by false position with the Illinois rule + from a bracket doubled out from the median life.""" + lower = shares <= 0.5 + target = np.where(lower, np.log(shares), np.log1p(-shares)) + + def gap(log_t: np.ndarray) -> np.ndarray: + """Increasing in ``log t``, 0 at the time sought.""" + t = np.exp(log_t) + with np.errstate(divide="ignore"): + low = np.log(np.asarray(rbd.ff(t, **kwargs), dtype=float)) + high = np.log(np.asarray(rbd.sf(t, **kwargs), dtype=float)) + return np.where(lower, low - target, target - high) + + median = float(rbd.time_to_reliability(0.5, **kwargs)) + lo = np.full(shares.shape, math.log(median)) + hi = lo.copy() + g_lo, g_hi = gap(lo), gap(hi) + for _ in range(2000): + down = g_lo > 0.0 + up = g_hi < 0.0 + if not (np.any(down) or np.any(up)): + break + lo[down] -= math.log(2.0) + hi[up] += math.log(2.0) + g_lo = np.where(down, gap(lo), g_lo) + g_hi = np.where(up, gap(hi), g_hi) + else: + raise ValueError( + "qf found no time with the share failed asked for (the " + "diagram's reliability does not fall that far)." + ) + # The lower end may still have g_lo == 0 or the upper g_hi == 0. + side = np.zeros(shares.shape, dtype=int) + tiny = 4.0 * np.finfo(float).eps + for _ in range(200): + open_ = ( + (hi - lo > tiny * np.maximum(1.0, np.abs(hi))) + & (g_lo != 0.0) + & (g_hi != 0.0) + ) + if not np.any(open_): + break + with np.errstate(invalid="ignore", divide="ignore"): + x = hi - g_hi * (hi - lo) / (g_hi - g_lo) + x = np.where(np.isfinite(x) & (x > lo) & (x < hi), x, 0.5 * (lo + hi)) + x = np.where(open_, x, lo) + g = gap(x) + above = open_ & (g > 0.0) + below = open_ & (g < 0.0) + hit = open_ & (g == 0.0) + hi = np.where(above, x, hi) + lo = np.where(below, x, lo) + # Illinois: halve the end kept twice running. + g_lo = np.where( + below, g, np.where(above & (side == 1), g_lo / 2, g_lo) + ) + g_hi = np.where( + above, g, np.where(below & (side == -1), g_hi / 2, g_hi) + ) + side = np.where(above, 1, np.where(below, -1, side)) + lo = np.where(hit, x, lo) + hi = np.where(hit, x, hi) + g_lo = np.where(hit, 0.0, g_lo) + found = np.where( + g_lo == 0.0, lo, np.where(g_hi == 0.0, hi, 0.5 * (lo + hi)) + ) + return np.exp(found) diff --git a/repyability/rbd/regression_node.py b/repyability/rbd/regression_node.py index 0599363b..f7a4d5bc 100644 --- a/repyability/rbd/regression_node.py +++ b/repyability/rbd/regression_node.py @@ -37,7 +37,7 @@ def _is_semiparametric(model) -> bool: Cox model): its baseline is an estimate on the observed range only, with no tail beyond it. (Recognised by its type, not by its survival curve.)""" - from surpyval import SemiParametricRegressionModel + from surpyval.univariate.regression import SemiParametricRegressionModel return isinstance(model, SemiParametricRegressionModel) diff --git a/repyability/rbd/repairable_rbd.py b/repyability/rbd/repairable_rbd.py index c073031f..0a153d44 100644 --- a/repyability/rbd/repairable_rbd.py +++ b/repyability/rbd/repairable_rbd.py @@ -59,10 +59,14 @@ MaintenanceEffect, MaintenancePlan, NodeActionRates, + NPVComparison, + NPVDistribution, + NPVUncertainty, PFDBreakdown, PlanVsActual, RateBreakdown, ReplacementCycle, + SimulatedSwitchTime, SimulationSamples, SparesDemand, SparesStock, @@ -80,11 +84,13 @@ _costs, _crews, _curves, + _downtime_risk, _event_loop, _first_failure, _intervals, _long_run, _npv, + _npv_runs, _plan_actual, _repairable_allocation, _repairable_capacity, @@ -94,6 +100,7 @@ _runs, _shutdowns, _spec, + _switch_runs, _unplanned, _window_report, _windows, @@ -190,11 +197,19 @@ class RepairableRBD(RBD): the component still fails, and any repair or replace cost is charged, but it is never down), plus optional costs. ``"repair_cost"`` and ``"replace_cost"`` are charged at every - failure of the component: each is a number, or a distribution of + failure of the component (``"replace_cost"`` is the replacement + on failure; a planned replacement is charged the + ``"preventive"`` task's ``"cost"`` instead, and the guide's + costs page has a table of which cost is charged when): each is + a number, or a distribution of the cost (anything with ``qf`` and ``mean``, such as a fitted surpyval model) drawn afresh at each failure. ``"downtime_cost"`` is a number charged per unit time the component is down, whether - or not the system is. A cost left out, None or 0 prices nothing. + or not the system is, on top of ``downtime_cost_rate`` while the + system is down too: a component in series with + ``"downtime_cost": 500`` and ``downtime_cost_rate=1000`` costs + 1,500 an hour down. Price lost output in one of them, not both. + A cost left out, None or 0 prices nothing. ``"preventive"`` schedules preventive maintenance: a dict with an ``"interval"`` and optional ``"policy"``, ``"duration"`` and ``"cost"``. Under ``"policy": "age"`` (the default) the unit is @@ -202,9 +217,13 @@ class RepairableRBD(RBD): (at time 0, or at the end of a repair or of the last preventive action), unless it fails first; under ``"block"`` at every multiple of ``interval``, whatever its age, unless it is down - then. Under ``"condition"`` it is inspected at every multiple of - ``interval`` while it is up, in no time, and replaced if it is - then more likely than ``"threshold"`` (a probability) to fail + then; or, with ``"replace_at"`` in place of the interval, at + each of those times (increasing, from 0 in the diagram's time) + and after the last no more: a plan, valued over a horizon (it + has no long run). Under ``"condition"`` it is inspected at + every multiple of ``interval`` while it is up, in no time, and + replaced if it is then more likely than ``"threshold"`` (a + probability) to fail before the next inspection, given its age ``a``: ``1 - R(a + interval) / R(a)``; or, for a life that is a degradation process, with ``"level"`` in place of @@ -213,7 +232,9 @@ class RepairableRBD(RBD): condition). Each inspection is charged ``"inspection_cost"``, a number or a distribution drawn afresh each time. The replacement takes a time drawn from ``"duration"``, a - time-to-maintain model, during which the unit is down (a planned + time-to-maintain model or a number (a fixed time, such as 8 for + eight hours with models in hours), during which the unit is down + (a planned outage); ``"instant"`` (the default) takes no time, renewing the unit in place. Each replacement is charged ``"cost"``, a number or a distribution drawn afresh each time. The unit comes back as @@ -222,11 +243,18 @@ class RepairableRBD(RBD): ``"opportunity"`` (an age from 0 to ``interval``) renews the unit early, from that age, at a stop of its maintenance group (see ``"group"``), as its scheduled replacement would. + A ``"restore_to"`` (a virtual age, 0 or more) makes each task + leave the unit as if that old, whatever its age before (an + overhaul that leaves a pump as if 3,000 hours old; 0 renews it), + its next life drawn given that age from the end of the task; + simulated, as a ``"restoration"`` is, and not given with one. A ``"restoration"`` makes each task restore the unit only partly, by Kijima's virtual-age models, under the ``"age"``, ``"block"`` and ``"condition"`` policies: a dict of a ``"model"``, ``"kijima1"`` or ``"kijima2"``, and a restoration - factor ``"q"`` in [0, 1] (as ``"repair"`` takes them), or a + factor ``"q"`` of 0 or more (``"repair"`` takes it in [0, + 1]; above 1, each task leaves the unit older than it was, + harmful or invasive maintenance), or a fitted surpyval ``GeneralizedRenewal``, whose Kijima model and restoration factor are taken. A task after the unit has operated ``x`` since its last action (a repair, a task, or put @@ -271,7 +299,8 @@ class RepairableRBD(RBD): stays hidden until a full test, every ``"full_test"`` (required with a coverage below 1, a whole multiple of the interval, from the offset), which finds every failure. The test takes a time - drawn from ``"duration"``, a time-to-test model, during which the + drawn from ``"duration"``, a time-to-test model or a number (a + fixed time), during which the component is off-line (a planned outage) and does not age; ``"instant"`` (the default) takes no time. A failure found by a test is repaired once the test is done, and the repair and @@ -283,7 +312,11 @@ class RepairableRBD(RBD): ``"acquisition_cost"`` is the one-off cost of buying the unit, a number: it is not a running cost, so it is left out of ``expected_cost_rate`` and the simulated costs, and counted by - ``total_cost`` and ``allocate_redundancy``. ``"priority"`` is the + ``total_cost`` and ``allocate_redundancy``. ``"salvage"``, + ``"escalation"`` and ``"retire_at"`` are the unit's own money, + which ``expected_npv`` takes as its arguments of the same names + for the node (a ``UnitPlan``'s fields of those names). + ``"priority"`` is the component's place in the queue for a repair crew (see ``repair_crews``): a number, higher first, by default 0. ``"group"`` names the component's maintenance group (see @@ -326,8 +359,27 @@ class RepairableRBD(RBD): ``"full_test"``) go onto the clock divided by ``d``. The spec keeps them as given, for saving, the levers, ``with_intervals`` and the interval choices, which take and - give them in operating time. The life must be a surpyval - parametric distribution of a time. + give them in operating time. The life must be a model that + rescales its time (surpyval's ``rescale_time``; with surpyval + 0.28, a parametric distribution of a time). With no duty, a + task in operating time counts the diagram's clock. ``"duty"`` + may instead be a plan that changes over time, a + ``schedule.DutySchedule`` (``UsageForecast.schedule()``): each + unit's life is drawn in operating time and put on the clock + through the plan from when it is put into service, and a + preventive task in operating time falls when the plan reaches + it; only the simulations take such a block (see + ``schedule.CalendarContext``). + ``"upgrade"`` gives the component another life from a time: a + dict of ``"at"`` (the time, in the diagram's time from 0), + ``"reliability"`` (the life its units have from then: the unit + in service is replaced by one of it, in no time) and ``"cost"`` + (the capital cost, charged then under ``"capital"``). Its + values over a horizon are worked out, and the long-run methods + give the long run once upgraded (the diagram with the new + life); it takes no maintenance or tests of its own but block + replacement yet (see the guide's "Upgrades, retirement and + salvage"). ``"covariates"``, a surpyval ``StepSchedule``, runs a block whose ``"reliability"`` is a fitted surpyval regression model (proportional or additive hazards, accelerated failure time or @@ -358,6 +410,11 @@ class RepairableRBD(RBD): ``"instant"`` repair. Its long-run values are exact from its Markov chain when its units' lives and repair times are exponential; it is simulated in Python. + - A [`UnitPlan`][repyability.UnitPlan]: one unit's life + and repair models, its tasks and its prices, of which the spec + dict above is the shorthand. The node is the node given + ``plan.spec()``; [`plans`][repyability.RepairableRBD.plans] + reads each spec node back as a plan. - A [`NonRepairable`][repyability.NonRepairable], pairing a reliability model with a time-to-replace model. Each node gets its own copy, so one object can be given for several identical @@ -395,7 +452,10 @@ class RepairableRBD(RBD): The problems found are recorded in ``structure_check``. downtime_cost_rate : float, optional Cost per unit time the whole system is down (e.g. lost - production), by default 0.0 (not priced). + production), by default 0.0 (not priced). It adds to each down + component's own ``"downtime_cost"``, so lost output priced in + both is counted twice (a series component down an hour costs + both rates). capacity : dict[Hashable, float or dict], optional Each node's capacity, keyed by node name, by default None: the throughput it passes while it is up, a positive number in any unit @@ -472,26 +532,74 @@ class RepairableRBD(RBD): group's chain followed from every member up. The simulations draw each cause as a Poisson process, failing the members it names that are up; they need exponential lives alone. - shutdowns : dict, optional + shutdowns : Opportunities or dict, optional Outages planned on a period or at given times that hold the whole system, or a named set of its nodes, off line for a fixed time (see [Shutdowns](../guide/system-maintenance.md#shutdowns)), by - default none: a name and a spec for each, of ``"period"`` and + default none: the site's + [`Opportunities`][repyability.Opportunities] in model time (each + opportunity a shutdown of its name, its ``takes_down`` the scope, + its ``idle_ageing`` and ``opportunistic`` as below, a duration of + None taking no time, and the record's ``shut_costs`` each shut's + cost; on real dates, ``Opportunities.on_diagram`` puts them on + the diagram's clock), or, as its shorthand, a name and a spec for + each, of ``"period"`` and ``"offset"`` (the first shut's start, in ``[0, period)``; 0 puts the first at ``period``) or ``"times"`` (the shuts' starts, increasing), ``"duration"`` (0 or more, shorter than the period or the gaps between the times), ``"scope"`` (a list of the diagram's nodes; None, the default, for the whole system), ``"cost"`` - (charged at each shut) and ``"idle_ageing"`` (True, the default: + (charged at each shut), ``"idle_ageing"`` (True, the default: a block in scope not worked on keeps ageing; False: it stands - still until the shut ends). The work done at a shut is given on - the block: ``"preventive": {"shutdown": name}`` renews it at every + still until the shut ends) and ``"opportunistic"`` (``{node: + age}``, or one age for every block in scope under age + replacement: at each shut, such a block that is working and at + least that old is renewed as its own age replacement renews it, + at its cost and in its time, and its next replacement counts from + then; simulated, with the count renewed at each shut in + ``AvailabilityResult.outage_jobs``). The work done at a shut is given + on the block: ``"preventive": {"shutdown": name}`` renews it at every shut (with ``"older_than"``, only once that old; with ``"policy": - "condition"``, on its condition; with a ``"restoration"``, - partly), and ``"inspection": {"shutdown": name}`` tests it there; - either takes the shut's calendar and duration, and the block must - be in its scope. Shuts on a period are exact where the blocks fail - independently; the rest is simulated, in Python. + "condition"``, on its condition; with a ``"restoration"``, partly; + given a list of names, at every start of each, each renewal taking + its own shut's length, over a horizon only), and + ``"inspection": {"shutdown": name}`` tests it there; either takes the + shut's calendar and duration, and the block must be in its scope. Shuts + on a period are exact where the blocks fail independently, and so are + shuts at given times over a horizon (they have no long run) where the + blocks worked on in them are renewed; the rest is simulated, in Python. + crew_cost_rate : float, optional + What each repair crew costs per unit time, busy or not (its + salary), by default 0.0 (not priced). The ``repair_crews`` crews + cost ``repair_crews * crew_cost_rate`` per unit time from 0, the + same in every simulation: every cost result has it under the + category ``"crews"`` (over a window ``T``, ``n c T``; discounted + at a rate ``r``, ``n c (1 - exp(-r T)) / r``), and the long-run + cost rate ``n c``. It needs ``repair_crews``: as many crews as are + needed cannot be priced. + call_out : dict, optional + A call-out crew, one more crew that comes only when jobs wait, by + default None: ``{"when_waiting": k, "fee": f, "rate": c}``, with + ``k`` a whole number of jobs, 1 or more, and ``"fee"`` and + ``"rate"`` costs (0 if left out). The rule: when a job falls due, + finds every crew busy and is then the ``k``-th waiting, the + call-out crew comes at once and starts the waiting job the next + free crew would have taken. While it is engaged there is one crew + more, and a crew that finishes a job takes the next waiting one as + ever. It leaves at the first end of a job that leaves a crew with + no waiting job to take: the crews are alike, so the job the + call-out crew has then, if any, is finished by the crew that came + free. (It does not stay to finish its own job, and it is not sent + away while a job still waits.) It is one crew: jobs that wait + while it is engaged call no other. Each call-out costs ``f`` and + its time engaged ``c`` per unit time, under the category + ``"crews"``. With exponential lives and repairs the crews' Markov + chain has it exactly (the long-run values, those over time and the + discounted ones, as for ``repair_crews``); the simulations follow + the same rule, in Python. The same diagram without ``call_out`` + gives what the contract is worth: the difference of the two costs + (or NPVs). It needs ``repair_crews``, and does nothing where no + job can wait. Attributes @@ -514,6 +622,11 @@ class RepairableRBD(RBD): The capacities given, keyed by node name, as floats. repair_crews : int or None The number of repair crews (None: as many as are needed). + crew_cost_rate : float + What each repair crew costs per unit time (0.0: not priced). + call_out : dict or None + The call-out crew's ``"when_waiting"``, ``"fee"`` and ``"rate"`` + (None: there is none). acquisition_costs : dict Node name -> the one-off cost of buying the unit, for the nodes that declare a non-zero ``"acquisition_cost"``. @@ -539,9 +652,11 @@ class RepairableRBD(RBD): ``"threshold"`` and ``"inspection_cost"``, an ``"age"`` policy's ``"opportunity"``, a ``"condition"`` policy's ``"level"``, a ``"calendar"`` policy's ``"calendar"``, and a - task's ``"restoration"``, ``"replace_every"`` and + task's ``"restoration"``, ``"restore_to"``, ``"replace_every"`` + and ``"replacement_cost"``, a task's ``"shutdown"`` and - ``"older_than"``, and its times' ``"basis"``. + ``"older_than"``, its times' ``"basis"``, and ``"replace_at"``, + the times of a plan in place of an ``"interval"``. GROUP_KEYS : tuple[str, ...] The keys of a maintenance group's options: ``"setup_cost"`` and ``"system_down"``. @@ -557,8 +672,8 @@ class RepairableRBD(RBD): ``"dormancy_factor"`` and ``"switching_probability"``. SHUTDOWN_KEYS : tuple[str, ...] The keys of a shutdown's spec: ``"period"``, ``"offset"``, - ``"times"``, ``"duration"``, ``"scope"``, ``"cost"`` and - ``"idle_ageing"``. + ``"times"``, ``"duration"``, ``"scope"``, ``"cost"``, + ``"idle_ageing"`` and ``"opportunistic"``. Raises ------ @@ -571,7 +686,9 @@ class RepairableRBD(RBD): below 0); if a ``"preventive"`` spec is not a dict of its keys with a positive ``interval``, a ``policy`` of ``"age"``, ``"block"`` or ``"condition"`` and a ``duration`` that is a model or - ``"instant"``; if an ``"inspection"`` spec is not a dict of its + ``"instant"``, or its ``"replace_at"`` is not positive, finite, + increasing times under the ``"block"`` policy with no interval; + if an ``"inspection"`` spec is not a dict of its keys with a positive, finite ``interval``, a ``duration`` that is a model or ``"instant"``, an ``offset`` from 0 to less than the interval, a ``coverage`` from 0 to 1 and, with a coverage below 1, @@ -589,7 +706,10 @@ class RepairableRBD(RBD): ``"ignore"``; if the diagram is invalid and ``on_infeasible_rbd`` is ``"raise"``; if a capacity is not a positive number or is for the input or output node or a node not in the diagram; if - ``repair_crews`` is not a whole number of at least 1, or a + ``repair_crews`` is not a whole number of at least 1, a + ``crew_cost_rate`` is not a finite, non-negative number or is + given without ``repair_crews``, a ``call_out`` is not such a dict + or is given without ``repair_crews``, or a ``"priority"`` is not a finite number; or if an ``"opportunity"`` is not an age from 0 to an age policy's interval, is given to a component in no group, or a group's member has hidden failures or @@ -719,9 +839,23 @@ def __init__( repair_crews: Optional[int] = None, maintenance_groups: Optional[dict[Any, dict]] = None, ccf_groups: Optional[Sequence[Any]] = None, - shutdowns: Optional[dict[Any, dict]] = None, + shutdowns: Any = None, + crew_cost_rate: float = 0.0, + call_out: Optional[dict] = None, ): _check_on_infeasible_rbd(on_infeasible_rbd) + # A unit's UnitPlan is the node given its spec (UC-63 of + # the maintenance README): the spec is the plan's shorthand. + from repyability.maintenance._plan import UnitPlan + + components = { + name: ( + component.spec() + if isinstance(component, UnitPlan) + else component + ) + for name, component in dict(components).items() + } # Capture the constructor inputs verbatim (before any mutation) so the # RBD can be faithfully serialised via to_dict()/to_json(). edges = list(edges) @@ -766,6 +900,9 @@ def __init__( for name, component in components.items() } ccf_groups = as_groups(ccf_groups) or None + # An Opportunities record is read as the dicts it stands for, which + # the diagram then keeps and saves. + shutdowns = _shutdowns.as_specs(shutdowns) self._init_args = { "edges": [tuple(e) for e in edges], "components": dict(components), @@ -785,6 +922,10 @@ def __init__( if isinstance(shutdowns, dict) and shutdowns else shutdowns or None ), + "crew_cost_rate": crew_cost_rate, + "call_out": ( + dict(call_out) if isinstance(call_out, dict) else call_out + ), } # Outages planned at given times, holding blocks off line (see # _shutdowns); their scopes are checked once the diagram is built. @@ -800,8 +941,17 @@ def __init__( # _covariate_schedule); the spec as given keeps the regression # model and the schedule, for saving and drawing. components = _covariate_schedule.on_schedules(components) - components, self._operating_tasks = _on_duty(components) + components, self._operating_tasks, clocks = _on_duty(components) self.repair_crews = _validate_crews(repair_crews) + self.crew_cost_rate = _spec._validate_crew_cost( + crew_cost_rate, self.repair_crews + ) + # A call-out crew (see _events._Crews): when it is called, its + # fee and its rate while engaged. + self._call_out = _spec._validate_call_out(call_out, self.repair_crews) + self.call_out = ( + None if self._call_out is None else self._call_out._asdict() + ) # Each component's place in the queue for a crew (higher first). self._priority: dict[Any, float] = {} self.downtime_cost_rate = _spec._validate_cost( @@ -820,6 +970,9 @@ def __init__( self._standby: dict[Any, _Standby] = {} # One-off purchase costs, by node (only non-zero ones). self.acquisition_costs: dict[Any, float] = {} + # Each component's own money (its "salvage", "escalation" and + # "retire_at"), by node: what a valuation takes for it. + self._valuation: dict[Any, dict] = {} # Each component's maintenance group, by node (see _maintenance). self._member_group: dict[Any, Hashable] = {} # Components repaired imperfectly, by node (see _ImperfectComponent). @@ -827,6 +980,8 @@ def __init__( # Components their preventive maintenance restores only partly, by # node (see _ImperfectComponent). self._restoring: dict[Any, _Restoration] = {} + # Components upgraded at a time, by node (see _spec._Upgrade). + self._upgrades: dict[Any, Any] = {} # The base class checks the names given components against the # edges; a component for a name in no edge is not part of the # diagram (the structure check reports it). @@ -875,6 +1030,9 @@ def __init__( ) if cost is not None: node_costs["preventive_cost"] = cost + if name in clocks: + # Counted in operating time on a plan that changes. + schedule = schedule._replace(clock=clocks[name]) if ( np.isfinite(schedule.interval) or schedule.policy == "calendar" @@ -922,6 +1080,25 @@ def __init__( # A replacement in place of a task with a cost is # priced, even at 0. node_costs["replacement_cost"] = replacing + if component.get("upgrade") is not None: + upgrade = _spec._validate_upgrade(name, component) + self._upgrades[name] = upgrade + # Its schedule: replaced at the upgrade's time, by a + # unit of the new life (see _curves._plan_curve), as + # one more of its block replacements if it has them. + block = self._preventive.get(name) + self._preventive[name] = ( + _Preventive( + upgrade.at, "block", None, times=(upgrade.at,) + ) + if block is None + else block._replace(upgrade_at=upgrade.at) + ) + if upgrade.cost: + node_costs["capital_cost"] = upgrade.cost + own_money = _spec._validate_valuation(name, component) + if own_money: + self._valuation[name] = own_money if component.get("acquisition_cost") is not None: acquisition = _spec._validate_cost( name, "acquisition_cost", component["acquisition_cost"] @@ -1173,6 +1350,20 @@ def mean(value): out[node] = value return out + @property + def plans(self) -> dict: + """Each node given as a spec dict or a plan, as the + [`UnitPlan`][repyability.UnitPlan] it states (UC-63 of + the maintenance README), by node; a fitted renewal process given + as a life reads as its life from new and its repairs.""" + from repyability.maintenance._plan import UnitPlan + + return { + name: UnitPlan.from_spec(component) + for name, component in self._init_args["components"].items() + if isinstance(component, dict) + } + @property def has_costs(self) -> bool: """Whether any cost has been declared (per-component or system-wide). @@ -1183,7 +1374,7 @@ def has_costs(self) -> bool: distribution always counts), is on a ``"calendar"`` policy (charged its calendar's prices), a maintenance group has a set-up cost, a shutdown has a cost, or - ``downtime_cost_rate`` is + ``downtime_cost_rate`` or ``crew_cost_rate`` is non-zero: whether running the system costs anything. Costs of 0 price nothing, costs declared inside a nested ``RepairableRBD`` do not count (a nested diagram that carries any is warned of when @@ -1205,6 +1396,8 @@ def has_costs(self) -> bool: return ( bool(self.costs) or bool(self.downtime_cost_rate) + or bool(getattr(self, "crew_cost_rate", 0.0)) + or _crews._call_out_priced(self) or any( group.setup_cost for group in getattr(self, "_maintenance", {}).values() @@ -1214,6 +1407,7 @@ def has_costs(self) -> bool: ) ) + @_long_run.follows_upgrades def expected_cost_rate( self, working_nodes: Optional[Collection[Hashable]] = None, @@ -1229,6 +1423,7 @@ def expected_cost_rate( + sum_i nu_i * preventive_cost_i + sum_i inspection_cost_i / tau_i + sum_i (1 - A_i) * downtime_cost_i + + repair_crews * crew_cost_rate ``` where ``A_sys`` is the system's long-run availability @@ -1269,7 +1464,8 @@ def expected_cost_rate( With limited ``repair_crews``, ``A_sys``, ``A_i`` and ``omega_i`` come from the crews' Markov chain (see ``mean_availability``): a component waiting for a crew is down, and pays its downtime cost, - and it fails at its constant rate while it is up. + and it fails at its constant rate while it is up. The crews' + salaries (``crew_cost_rate`` each) are paid whatever happens. Every cost is optional and defaults to 0, so any subset can be priced; with nothing priced, not even an acquisition cost (see @@ -1737,6 +1933,8 @@ def allocate_redundancy( max_units: Union[int, Dict[Hashable, int], None] = None, method: str = "exact", discount_rate: float = 0.0, + objective: str = "cost", + value_rate: float = 0.0, ) -> TotalCostAllocation: """Choose the redundancy with the lowest total cost of ownership. @@ -1783,6 +1981,23 @@ def allocate_redundancy( ``method="greedy"`` adds or removes one copy at a time while that lowers the total: fast, but not guaranteed optimal. + Redundancy is a capital decision: the copies are bought now, and + what they save comes later. ``objective="npv"`` chooses the design + with the highest net present value over the horizon, the value + the system earns while it works (``value_rate`` per unit time) + less its total cost, each at ``discount_rate``; the result gives + the ``npv``, its split into ``value``, ``acquisition_cost`` and + ``running_cost``, and the ``eac``, the same as a steady cost per + unit time. ``objective="eac"`` chooses by that, which over one + horizon is the same design. A value earned while the system works + is a cost of its downtime, so the search is the total cost's + with an hour down costing ``downtime_cost_rate + value_rate``, + and with no value the design is the total cost's. The running + costs, the downtime and the value are the long-run rates over + the horizon's present value, as ``total_cost`` counts them, + which the result's ``basis`` says: a system new at the start is + up a little more often at first. + Parameters ---------- horizon : float @@ -1824,20 +2039,31 @@ def allocate_redundancy( The continuous discount rate per unit time of the component models, by default 0 (undiscounted), as for ``total_cost``: the design with the lowest present value is chosen. + objective : str, optional + What the design is chosen by: ``"cost"`` (the default), the + lowest total cost; ``"npv"``, the highest net present value; + or ``"eac"``, the lowest equivalent annual cost less the + value earned. + value_rate : float, optional + The value earned per unit time while the system works, for + ``"npv"`` and ``"eac"``, by default 0. Returns ------- TotalCostAllocation The chosen ``units`` per node and train, with the design's ``total_cost``, ``acquisition_cost``, ``cost_rate`` and - ``availability`` (see + ``availability``, and for ``"npv"`` and ``"eac"`` its + ``npv``, ``eac``, ``value`` and ``running_cost`` (see [`TotalCostAllocation`][repyability.TotalCostAllocation]). Raises ------ ValueError If ``horizon``, ``nodes``, ``trains``, ``min_availability``, - ``max_units``, ``method`` or ``discount_rate`` is invalid; if + ``max_units``, ``method``, ``discount_rate``, ``objective`` + or ``value_rate`` is invalid (a ``value_rate`` needs + ``"npv"`` or ``"eac"``); if no component has an acquisition cost and neither ``nodes`` nor ``trains`` is given; if a node's or train's copies cost nothing and are not capped; @@ -1847,11 +2073,14 @@ def allocate_redundancy( If a component is under block replacement with models its exact values do not cover (see ``node_availability``), or has hidden failures its numerical values do not cover (see - ``mean_availability``): its long-run values are not known. Or if - a component can wait for a repair crew (see ``repair_crews``): - the search assumes that none does. Or if a common-cause group's - chain does not cover it (see ``ccf_groups``), a member given - copies is in an ``MGL`` or ``AlphaFactor`` group (its + ``mean_availability``): its long-run values are not known. Or, + where a component can wait for a repair crew (see + ``repair_crews``): if the crews' Markov chain does not cover + the diagram, it has common-cause groups, maintenance groups + or shutdowns, ``trains`` are given, or the search needs a + design whose chain has too many states. Or if a common-cause + group's chain does not cover it (see ``ccf_groups``), a member + given copies is in an ``MGL`` or ``AlphaFactor`` group (its parameters are for its group's size), or a train holds a member. @@ -1887,6 +2116,23 @@ def allocate_redundancy( >>> rbd.allocate_redundancy(8760.0).units {'pump': 1} + At 30% a year the second pump does not pay on the lost production + alone, but it does if each hour of pumping also earns 400: + + >>> import math + >>> rate = math.log(1.30) / 8760 + >>> rbd.allocate_redundancy(87600.0, discount_rate=rate).units + {'pump': 1} + >>> best = rbd.allocate_redundancy( + ... 87600.0, objective="npv", discount_rate=rate, value_rate=400.0 + ... ) + >>> best.units, round(best.npv), round(best.eac, 2) + ({'pump': 2}, 12314518, -397.67) + >>> round(best.value), round(best.acquisition_cost) + (12385481, 40000) + >>> round(best.running_cost) + 30964 + A station needing two of three pump trains, each a pump and its motor, when an hour without pumping costs 2,000: is a fourth train worth it? Name one train, and its copies join the vote: @@ -1932,8 +2178,11 @@ def allocate_redundancy( max_units=max_units, method=method, discount_rate=discount_rate, + objective=objective, + value_rate=value_rate, ) + @_long_run.follows_upgrades def availability_allocation( self, target: float, @@ -2068,6 +2317,7 @@ def availability_allocation( feasibility=feasibility, ) + @_long_run.follows_upgrades def mttf_mttr_allocation( self, target: float, @@ -2264,6 +2514,14 @@ def optimal_replacement_intervals( min_availability: Optional[float] = None, max_cost_rate: Optional[float] = None, assume_unlimited_crews: bool = False, + objective: str = "cost", + discount_rate: float = 0.0, + value_rate: float = 0.0, + horizon=None, + robust=False, + uncertainty: Optional[Dict[Hashable, Any]] = None, + n_draws: int = 200, + seed=None, ) -> MaintenancePlan: """Choose the age-replacement intervals for the system as a whole. @@ -2312,6 +2570,44 @@ def optimal_replacement_intervals( every repair started at once. Simulate that plan with the crews, ``with_intervals(plan).cost()``, to see what the waiting costs. + At a discount rate, spending later is worth something, so the + best intervals are a little longer than the cost rate's. + ``objective="eac"`` chooses them for the lowest equivalent annual + cost in the long run: the steady cost per unit time worth the + same, at ``discount_rate``, as running the diagram for ever from + new, less ``value_rate`` for the time it works. Each component's + own costs are discounted over its renewal cycle, exactly (Fox, + 1966), as ``NonRepairable.optimal_replacement_policy`` discounts + one unit's; the cost of the system's downtime and the value it + earns are taken at its long-run availability, an approximation + that the plan's ``basis`` states. At a rate of 0 it is the cost + rate, and the plan the same. ``objective="npv"`` chooses them for + the highest expected net present value over ``horizon`` from new + (``expected_npv``), which follows the system's availability over + time. That takes each plan's curves over the horizon, so it is + much slower, and a plan's value over a horizon has a local best + wherever a replacement falls just inside or outside it: without + ``allowed`` the search is a local one from the long run's best + plan, and with ``allowed`` every combination is valued (replacing + like units at different ages, so that they are not all down + together, can be worth more from new). The targets are kept + either way: ``min_availability`` and ``max_cost_rate`` bound the + long-run values, and the objective is minimised within them. + + The intervals are the best for the models as fitted. With + ``robust``, the plan also says how robust that choice is to the + models' uncertainty (its ``robustness``, a ``PlanRobustness``): + the uncertain models are drawn ``n_draws`` times, as + ``mean_availability_uncertainty`` draws them, and under each draw + the choice is scored by the same objective against its + neighbours (each interval one step either way: the next of + ``allowed``, or a quarter longer or shorter), every plan under + the same draws; the share of draws in which it stays the best, + and the mean of what it loses where it does not (its regret), + follow. ``robust="reoptimise"`` chooses the intervals again under + each draw instead, which is slower. The models no draw changes + are listed in it as held fixed. + Parameters ---------- nodes : Collection[Hashable], optional @@ -2334,12 +2630,44 @@ def optimal_replacement_intervals( With limited ``repair_crews``, choose the intervals as if every repair started at once (the plan's cost rate and availability are then those without waiting), by default False: refused. + objective : str, optional + What the intervals minimise: ``"cost"`` (the default), the + long-run cost rate, or with ``max_cost_rate`` the + unavailability; ``"eac"``, the equivalent annual cost in the + long run at ``discount_rate``, less the value earned; or + ``"npv"``, less the expected net present value over + ``horizon``. + discount_rate : float, optional + The continuous discount rate per unit time of the models, for + ``"eac"`` and ``"npv"``, by default 0 (an annual rate ``i`` + with models in hours is ``math.log(1 + i) / 8760``). + value_rate : float, optional + The value earned per unit time while the system works, for + ``"eac"`` and ``"npv"``, by default 0. + horizon : float, optional + The time ``"npv"`` values, from new. + robust : bool or str, optional + Say how robust the choice is to the models' uncertainty: + ``True`` against its neighbours under each draw, + ``"reoptimise"`` against each draw's own best intervals. By + default False. + uncertainty : dict, optional + With ``robust``, the uncertain inputs, as for + ``mean_availability_uncertainty``: by default every fitted + model. + n_draws : int, optional + With ``robust``, the number of draws, by default 200. + seed : int, optional + With ``robust``, the seed of the draws. Returns ------- MaintenancePlan The interval of each component in ``nodes`` (``inf`` for never), - and the system's cost rate and availability with them. + and the system's cost rate and availability with them; for + ``"eac"`` and ``"npv"``, the objective's value too + (``objective_value``) and what it is made of (``basis``); + with ``robust``, its ``robustness``. Raises ------ @@ -2352,7 +2680,12 @@ def optimal_replacement_intervals( NotImplementedError If the long-run values are not known exactly (see ``expected_cost_rate``), or a component can wait for a repair - crew and ``assume_unlimited_crews`` is not given. + crew and ``assume_unlimited_crews`` is not given; for + ``"eac"`` at a discount rate, if a priced component has no + renewal cycle of its own worked out here (a standby group, + block replacement, a common-cause group, a unit whose tests + or repairs take time, ...): + the message names ``objective="npv"``. Examples -------- @@ -2387,6 +2720,21 @@ def optimal_replacement_intervals( The pump alone in the line is replaced later than those with a standby: its replacements stop the plant too. + + The plant earns 2000 an hour while it runs, so an hour down + loses 2500. At 10% a year, the intervals for the lowest + equivalent annual cost, net of what it earns: + + >>> import math + >>> plan = plant.optimal_replacement_intervals( + ... objective="eac", + ... discount_rate=math.log(1.10) / 8760, + ... value_rate=2000.0, + ... ) + >>> {node: round(t) for node, t in plan.intervals.items()} + {'a': 621, 'b1': 517, 'b2': 517} + >>> round(plan.objective_value, 2) + -1940.55 """ _shutdowns.refuse(self, "optimal_replacement_intervals") return _intervals.optimal_replacement_intervals( @@ -2396,6 +2744,14 @@ def optimal_replacement_intervals( min_availability=min_availability, max_cost_rate=max_cost_rate, assume_unlimited_crews=assume_unlimited_crews, + objective=objective, + discount_rate=discount_rate, + value_rate=value_rate, + horizon=horizon, + robust=robust, + uncertainty=uncertainty, + n_draws=n_draws, + seed=seed, ) def optimal_inspection_intervals( @@ -2407,6 +2763,10 @@ def optimal_inspection_intervals( max_cost_rate: Optional[float] = None, assume_unlimited_crews: bool = False, offset_shares=None, + objective: str = "cost", + discount_rate: float = 0.0, + value_rate: float = 0.0, + horizon=None, ) -> MaintenancePlan: """Choose the proof-test intervals of components with hidden failures, for the system as a whole. @@ -2448,6 +2808,23 @@ def optimal_inspection_intervals( divide it, from ``allowed`` (which must) or, left out, from every one in range. + At a discount rate, the tests are paid for now and the failures + they find later. ``objective="eac"`` chooses the intervals for + the lowest equivalent annual cost in the long run at + ``discount_rate``, less ``value_rate`` for the time the system + works, and ``objective="npv"`` for the highest expected net + present value over ``horizon`` from new, as + ``optimal_replacement_intervals`` does (see it for what each is + made of, and what is approximate). A tested component starts + afresh at the test that finds it failed: its cycle is the tests + up to that one, each paid for when it is made, the failure when + it is found, and its own downtime from the failure to that test. + That is worked out for tests and repairs that take no time and + find every failure. The targets are kept: ``min_availability`` + (the PFDavg limit) and ``max_cost_rate`` bound the long-run + values, and the objective is minimised within them. At a rate + of 0, ``"eac"`` is the cost rate, and the plan the same. + Parameters ---------- nodes : Collection[Hashable], optional @@ -2478,13 +2855,30 @@ def optimal_inspection_intervals( one's tests stay from 0. Needs ``allowed``. By default each offset keeps its share of the interval. The plan's ``offsets`` are the times they give (shares times the intervals). + objective : str, optional + What the intervals minimise: ``"cost"`` (the default), the + long-run cost rate, or with ``max_cost_rate`` the + unavailability; ``"eac"``, the equivalent annual cost in the + long run at ``discount_rate``, less the value earned; or + ``"npv"``, less the expected net present value over + ``horizon``. + discount_rate : float, optional + The continuous discount rate per unit time of the models, for + ``"eac"`` and ``"npv"``, by default 0. + value_rate : float, optional + The value earned per unit time while the system works, for + ``"eac"`` and ``"npv"``, by default 0. + horizon : float, optional + The time ``"npv"`` values, from new. Returns ------- MaintenancePlan The interval of each component in ``nodes``, its ``offsets`` (the time of its first test), and the system's cost rate and - availability (1 - PFDavg) with them. + availability (1 - PFDavg) with them; for ``"eac"`` and + ``"npv"``, the objective's value too (``objective_value``) + and what it is made of (``basis``). Raises ------ @@ -2503,7 +2897,11 @@ def optimal_inspection_intervals( If a component's hidden failures have no exact long-run values (see ``node_availability``), the intervals repeat together only after too many tests to average over, or a component can wait - for a repair crew and ``assume_unlimited_crews`` is not given. + for a repair crew and ``assume_unlimited_crews`` is not given; + for ``"eac"`` at a discount rate, if a priced component has no + renewal cycle of its own worked out here (tests or repairs + that take time, tests that can miss a failure, ...): the + message names ``objective="npv"``. Examples -------- @@ -2577,6 +2975,10 @@ def optimal_inspection_intervals( max_cost_rate=max_cost_rate, assume_unlimited_crews=assume_unlimited_crews, offset_shares=offset_shares, + objective=objective, + discount_rate=discount_rate, + value_rate=value_rate, + horizon=horizon, ) def with_intervals(self, intervals, offsets=None) -> "RepairableRBD": @@ -2705,6 +3107,7 @@ def initialize_event_queue( state=state, ) + @_long_run.follows_upgrades def mean_unavailability( self, working_nodes: Optional[Collection[Hashable]] = None, @@ -2843,6 +3246,7 @@ def analysis_routes(self) -> Dict[str, "AnalysisRoute"]: """ return _repairable_routes.analysis_routes(self) + @_long_run.follows_upgrades def mean_availability( self, working_nodes: Optional[Collection[Hashable]] = None, @@ -3839,7 +4243,9 @@ def cost_by_window( The number of simulations, as for [`cost`][repyability.RepairableRBD.cost]. seed : int, optional - The random seed, as for `cost`. + The random seed, as for `cost`. By default None: one seed + drawn from numpy's global random number generator for every + window's run, so the windows still share their histories. engine : str, optional The simulation engine, as for `cost`. levels : array-like, optional @@ -4105,6 +4511,12 @@ def expected_npv( broken_nodes: Optional[Collection[Hashable]] = None, method: str = "p", state=None, + retire_at=None, + salvage=None, + rate_sensitivity: bool = False, + escalation: Optional[Dict[Hashable, float]] = None, + rates: str = "nominal", + inflation: Optional[float] = None, ) -> ExpectedNPV: """The expected net present value of running the system for ``horizon``, from new or from a state: what it earns while it @@ -4149,9 +4561,11 @@ def expected_npv( models, as for ``total_cost``, by default 0 (undiscounted): for an annual rate ``i`` with models in hours, ``math.log(1 + i) / 8760``. - value_rate : float, optional + value_rate : float or ValueSchedule, optional What the system earns per unit time while it works, at least - 0, by default 0 (costs alone). Constant in this version. + 0, by default 0 (costs alone); or a + [`ValueSchedule`][repyability.ValueSchedule] of steps in + model time. periods : int or array-like, optional The periods of the cash-flow table: a number of equal periods across the horizon, or the increasing ends of the periods, the @@ -4170,6 +4584,46 @@ def expected_npv( Start from the components' current states rather than new, as for ``expected_cost``. By default None: every component new at 0. + retire_at : float, optional + Retire the system at this time, more than 0 and no later than + the horizon: nothing is earned or spent after it, and the + equivalent annual cost is over the time to it. By default + None: it runs to the horizon. + salvage : float or dict, optional + What is left is worth at the end (the retirement, or the + horizon), credited then and discounted from there: a number + for the system, or a dict of a number for each component (and + for None, the system); negative for a cost of disposal. A + component's may be a function of the age of its unit in + service (taking an array of ages), for a plain component from + new: its expected value over that age, a unit down then + credited nothing. By default None. + rate_sensitivity : bool, optional + Also work out how the NPV moves with the discount rate, + ``d npv / d r`` (the result's ``rate_sensitivity``), with an + estimate of its error: by Richardson's extrapolation of + differences of the NPV on steps of the rate of ``0.01`` and + ``0.02`` over the time valued (central, or one-sided from a + rate below the larger step), four more valuations. By default + False. + escalation : dict, optional + A growth rate per unit time (continuous, of either sign) for + some streams, by cost category (``"repair"``, ``"replace"``, + ``"preventive"``, ``"inspection"``, ``"component_downtime"``, + ``"system_downtime"``, ``"setup"``, ``"shutdown"``, + ``"crews"``), by component (over its categories), or + ``"value"`` and ``"salvage"``: an amount at ``t`` is its price + today times ``exp(g t)``, so it is discounted at the rate less + its growth. The acquisition cost is paid at 0. By default + None: every price as it is. + rates : str, optional + ``"nominal"`` (the default) or ``"real"``: what + ``discount_rate`` and the growths are in. + inflation : float, optional + With ``rates="real"``, the continuous inflation per unit time: + every amount is made nominal (the rate and each stream's + growth take it too), which leaves the present values as they + are and makes the undiscounted ones nominal. Returns ------- @@ -4183,10 +4637,13 @@ def expected_npv( ValueError If ``horizon``, ``discount_rate``, ``value_rate`` or ``periods`` is invalid; if nothing is priced and there is no - ``value_rate`` (as ``routes.Refused``); or as for - ``expected_cost``. + ``value_rate`` (as ``routes.Refused``); if ``retire_at`` is + past the horizon or a ``salvage`` is not a finite number or a + function of age; or as for ``expected_cost``. NotImplementedError - As for ``point_availability`` and ``expected_cost``. + As for ``point_availability`` and ``expected_cost``; for a + salvage by age of a component that is not a plain one from + new. Examples -------- @@ -4218,6 +4675,16 @@ def expected_npv( 9155 >>> len(result.cash_flows) 11 + + How much a point more on the annual rate would take off it: + + >>> result = rbd.expected_npv( + ... 5 * 8760.0, discount_rate=r, value_rate=10.0, + ... rate_sensitivity=True, + ... ) + >>> step = math.log(1.09) / 8760 - r + >>> round(result.rate_sensitivity * step) + -7376 """ return _npv.expected_npv( self, @@ -4229,6 +4696,633 @@ def expected_npv( broken_nodes=broken_nodes, method=method, state=state, + retire_at=retire_at, + salvage=salvage, + rate_sensitivity=rate_sensitivity, + escalation=escalation, + rates=rates, + inflation=inflation, + ) + + def npv_distribution( + self, + horizon, + *, + discount_rate: float = 0.0, + value_rate: float = 0.0, + mc_samples: Optional[int] = None, + seed: Optional[int] = None, + hurdle: Optional[float] = None, + tail: float = 0.1, + engine: str = "auto", + state=None, + contract=None, + escalation=None, + rates: str = "nominal", + inflation=None, + ) -> NPVDistribution: + """The net present value of each of many simulated runs of the + system over ``horizon``, and their spread: percentiles, the chance + of ending below a hurdle, and the average of the worst runs + (CVaR). Simulated. + + In plain terms: + [`expected_npv`][repyability.RepairableRBD.expected_npv] is the + average over every way the failures could fall, and hides + the risk; this simulates the runs themselves. Each run is a history + of [`simulate_timelines`][repyability.RepairableRBD.simulate_timelines] + (the same simulations, by seed), priced with the diagram's own + costs: each failure its repair and replace costs, each planned + outage its preventive cost, each component's and the system's + time down their downtime costs, each discounted at the time it + fell (``exp(-discount_rate * t)``), less the value earned while + the system was up, and the acquisition costs paid at the start. + A shutdown's cost is charged at each of its starts; a component + it holds off line is not charged for the hold, and what happens + to it in the shut (a failure, an opportunistic renewal) is + charged as anywhere else. A plan's own ``"retire_at"`` ends the + runs there, and its own ``"salvage"`` (a number) is credited to + every run at the end, as ``expected_npv`` credits them. The + runs' mean estimates ``expected_npv``'s value, within its + confidence interval. It + works for diagrams the exact methods refuse (repair crews with + other lives, maintenance groups, scheduled covariates, + opportunistic renewals at shutdowns), as the simulation does. + + A cost charged at an event the histories do not record (a + standby group's units' failures, tests and inspections, planned + replacements that take no time, a calendar policy's prices, a + maintenance group's set-up) is not left out: the + method refuses the diagram, naming it. A cost given as a + distribution is charged at its mean (``priced_at_mean``). + + Parameters + ---------- + horizon : float + The length of time to value, more than 0, in the component + models' unit. + discount_rate : float, optional + The continuous discount rate per unit time, as for + ``expected_npv``, by default 0. + value_rate : float or ValueSchedule, optional + What the system earns per unit time while it works, at least + 0, by default 0 (costs alone); or a + [`ValueSchedule`][repyability.ValueSchedule] of steps in + model time, each up span earning each step's rate over its + part of it. + mc_samples : int, optional + The number of runs, by default 10,000. + seed : int, optional + Seeds the runs, as for ``simulate_timelines``: the runs are + its simulations with this seed, on either engine. By default + one is drawn from numpy's global RNG (``np.random.seed`` makes + it repeatable), and kept in the result. + hurdle : float, optional + A value the NPV must reach: the result gives the share of runs + below it. By default None. + tail : float, optional + The share of the worst runs ``cvar`` averages, more than 0 and + at most 1, by default 0.1. + engine : str, optional + ``"auto"`` (the default), ``"python"`` or ``"numba"``, as for + ``simulate_timelines``; the runs are the same on each. + state : dict, optional + Start from the components' current states rather than new, as + for ``simulate_timelines``. By default every component new. + contract : AvailabilityContract, optional + Terms that pay on the system's availability in each period + (or their ``to_dict()``): each run's penalty or bonus in each + period, from the share of the period the system was up in + that run, paid at the period's end and added to its NPV as a + category of its own (``contract_samples``). By default None. + escalation : dict, optional + A growth rate per unit time for some streams, by cost + category, component, ``"value"`` (or ``"salvage"``), as for + ``expected_npv``: an amount at ``t`` is its price times + ``exp(g t)``. By default None. + rates : str, optional + ``"nominal"`` (the default) or ``"real"``, as for + ``expected_npv``. + inflation : float, optional + With ``rates="real"``, the continuous inflation per unit time, + as for ``expected_npv``. + + Returns + ------- + NPVDistribution + Each run's NPV, value and cost; the mean with + ``mean_interval()``, the value and cost split as in + ``ExpectedNPV``, ``p10``/``p50``/``p90`` (``percentile`` and + ``percentile_interval`` for others), the chance below the + hurdle and ``cvar``. + + Raises + ------ + ValueError + If ``horizon``, ``discount_rate``, ``value_rate``, ``hurdle``, + ``tail``, ``mc_samples`` or ``engine`` is invalid; if nothing + is priced and there is no ``value_rate`` (as + ``routes.Refused``); or as for ``simulate_timelines``. + NotImplementedError + If a cost is charged at events the histories do not record, + naming it; if a component has a salvage by age (of its unit + in service), or one of several components retires; or as for + ``simulate_timelines``. + + Examples + -------- + A pump earning 10 per hour while it works, repaired at 500 a + failure and bought for 20,000, over 5 years at 8% a year: the + spread around ``expected_npv``'s 321,975: + + >>> import math + >>> import surpyval as surv + >>> from repyability import RepairableRBD + >>> rbd = RepairableRBD( + ... [("s", "p"), ("p", "t")], + ... { + ... "p": { + ... "reliability": surv.Exponential.from_params([1e-3]), + ... "repairability": surv.Exponential.from_params([0.1]), + ... "repair_cost": 500.0, + ... "acquisition_cost": 20000.0, + ... } + ... }, + ... ) + >>> r = math.log(1.08) / 8760 # per hour + >>> runs = rbd.npv_distribution( + ... 5 * 8760.0, discount_rate=r, value_rate=10.0, mc_samples=2000, + ... seed=1, hurdle=320_000, + ... ) + >>> round(runs.mean), round(runs.p10), round(runs.p90) + (322045, 317651, 326267) + >>> round(runs.probability_below_hurdle, 3), round(runs.cvar) + (0.268, 315980) + """ + return _npv_runs.npv_distribution( + self, + horizon, + discount_rate=discount_rate, + value_rate=value_rate, + mc_samples=mc_samples, + seed=seed, + hurdle=hurdle, + tail=tail, + engine=engine, + state=state, + contract=contract, + escalation=escalation, + rates=rates, + inflation=inflation, + ) + + def compare_npv( + self, + other: "RepairableRBD", + horizon, + *, + discount_rate: float = 0.0, + value_rate: float = 0.0, + contract=None, + mc_samples: Optional[int] = None, + seed: Optional[int] = None, + confidence: float = 0.95, + engine: str = "auto", + state=None, + escalation=None, + rates: str = "nominal", + inflation=None, + ) -> NPVComparison: + """How much more this plan is worth than ``other``, run by run: + both simulated on the same random numbers, the distribution of + the difference in their net present values. Simulated. + + In plain terms: a choice between two plans (another maintenance + interval, a spare, a second pump) is about the difference, and + the difference is what this pins down. Both plans' runs are + [`npv_distribution`][repyability.RepairableRBD.npv_distribution]'s, + from one seed, and a component in the same place in both (the + same node name, and the same names down through nested RBDs) + draws the same random numbers in both, as for + [`compare`][repyability.RepairableRBD.compare]: the same + failures and repairs where it is modelled the same way, matching + ones where it is not. Each run's difference then comes from how + the plans differ rather than from chance, so its mean is known + far more precisely than either plan's NPV. Identical plans differ + by exactly 0 in every run. + + Parameters + ---------- + other : RepairableRBD + The plan to compare with. + horizon : float + The length of time to value, as for ``npv_distribution``. + discount_rate : float, optional + The continuous discount rate per unit time, by default 0. + value_rate : float or ValueSchedule, optional + What either system earns per unit time while it works (a + number or a [`ValueSchedule`][repyability.ValueSchedule]), + by default 0. + contract : AvailabilityContract, optional + Terms that pay on availability, applied to both plans, as for + ``npv_distribution``. By default None. + mc_samples : int, optional + The number of runs of each plan, by default 10,000. + seed : int, optional + Seeds both plans' runs; by default one is drawn from numpy's + global RNG (``np.random.seed`` makes it repeatable), and kept + in the result. + confidence : float, optional + The confidence level of the mean difference's interval, by + default 0.95. + engine : str, optional + ``"auto"`` (the default), ``"python"`` or ``"numba"``, as for + ``simulate_timelines``. + state : dict, optional + The components' states at the start, in both plans, as for + ``simulate_timelines``. By default every component new. + escalation : dict, optional + A growth rate per unit time for some streams, by cost + category, component, ``"value"`` (or ``"salvage"``), as for + ``expected_npv``: an amount at ``t`` is its price times + ``exp(g t)``. By default None. + rates : str, optional + ``"nominal"`` (the default) or ``"real"``, as for + ``expected_npv``. + inflation : float, optional + With ``rates="real"``, the continuous inflation per unit time, + as for ``expected_npv``. + + Returns + ------- + NPVComparison + Each run's difference (this plan's NPV less the other's), + their mean with a confidence interval, the chance the other + plan is better, the standard error two independent runs would + have given, and both plans' ``NPVDistribution``. + + Raises + ------ + ValueError + If an argument is invalid, or as for ``npv_distribution``. + TypeError + If ``other`` is not a ``RepairableRBD``. + NotImplementedError + If a plan's runs cannot be priced from their histories (as for + ``npv_distribution``), or a plan's components draw numbers + that cannot be matched with the other's (a model sampled its + own way), naming them. + + Examples + -------- + A pump earning 10 an hour while it works, repaired in 10 hours on + average, against the same pump repaired in 5, over a year at 8%: + + >>> import math + >>> import surpyval as surv + >>> from repyability import RepairableRBD + >>> E = surv.Exponential.from_params + >>> def pump(mttr): + ... return RepairableRBD( + ... [("s", "p"), ("p", "t")], + ... { + ... "p": { + ... "reliability": E([1e-3]), + ... "repairability": E([1 / mttr]), + ... "repair_cost": 500.0, + ... } + ... }, + ... ) + >>> r = math.log(1.08) / 8760 + >>> gain = pump(5.0).compare_npv( + ... pump(10.0), 8760.0, discount_rate=r, value_rate=10.0, + ... mc_samples=2000, seed=1, + ... ) + >>> round(gain.mean), round(gain.interval.standard_error, 1) + (393, 4.9) + + Two independent runs of the same size would have pinned it down + ten times less precisely: + + >>> round(gain.independent_standard_error, 1) + 52.7 + """ + return _npv_runs.compare_npv( + self, + other, + horizon, + discount_rate=discount_rate, + value_rate=value_rate, + contract=contract, + mc_samples=mc_samples, + seed=seed, + confidence=confidence, + engine=engine, + state=state, + escalation=escalation, + rates=rates, + inflation=inflation, + ) + + def least_spend_for_downtime( + self, + horizon: float, + limit: float, + *, + level: float = 0.95, + objective: str = "var", + measure: str = "hours", + downtime: str = "all", + redundancy: Optional[Mapping] = None, + intervals: Optional[Mapping] = None, + max_units: Optional[Mapping] = None, + budget: Optional[float] = None, + value_rate: float = 0.0, + confidence: float = 0.95, + mc_samples: Optional[int] = None, + seed: Optional[int] = None, + engine: str = "auto", + ): + """The least spend that keeps a bad run's downtime under + ``limit``: "I want to be 95% sure I don't lose more than this on + downtime over the horizon; what is the least I need to pay?". + Simulated. + + In plain terms: the target is the system's downtime over + ``horizon``, in hours or its cost (each hour down at the + ``downtime_cost_rate`` and ``value_rate``), all of it or only the + unplanned part (``downtime=``). A design meets the limit when an + upper confidence bound on the downtime's quantile at ``level`` + (``objective="var"``, an order statistic, exact) or on the mean of + the worst share beyond it (``"cvar"``, approximate) is under it. + The levers are each at their own price, and spend is unbounded + unless ``budget`` is given: ``redundancy`` (copies of a node in + parallel with it, at a price each) and ``intervals`` (a node's + preventive interval, through the candidates given, at its tasks' + expected cost). The search takes, step by step, the move that + lowers the bad run's downtime most per extra spend, every design + on the same seed, until one meets the limit; its designs are the + frontier. If the levers stop short, ``stopped`` says what stopped + them (the budget, their caps, or planned task downtime no lever + lowers). Every design reports both its planned and its unplanned + downtime, the mean and the quantile at ``level``, in hours and + in cost. The guide's "Downtime you can be sure of" explains. + + Parameters + ---------- + horizon : float + The length of time valued, more than 0. + limit : float + The downtime (hours, or cost) a bad run must stay under. + level : float, optional + The share of runs that must stay under it, by default 0.95. + objective : str, optional + ``"var"`` (the default) or ``"cvar"``. + measure : str, optional + ``"hours"`` (the default) or ``"cost"``. + downtime : str, optional + ``"all"`` (the default) or ``"unplanned"``. + redundancy : dict, optional + ``{node: price of a copy}``: the nodes that may be given + copies in parallel. + intervals : dict, optional + ``{node: intervals to try, in order}`` for nodes with a + preventive task. + max_units : dict, optional + ``{node: most copies}``; by default none. + budget : float, optional + The most the levers may cost; by default no bound. + value_rate : float, optional + The value lost per unit time down, added to the + ``downtime_cost_rate`` for ``measure="cost"``, by default 0. + confidence : float, optional + The level of the bound, by default 0.95. + mc_samples : int, optional + Each design's runs, by default 2,000. + seed : int, optional + Seeds every design's runs; by default one is drawn from + numpy's global RNG (``np.random.seed`` makes it repeatable), + and kept. + engine : str, optional + ``"auto"``, ``"python"`` or ``"numba"``, as for + ``availability``. + + Returns + ------- + DowntimeRiskResult + ``met``, the ``design`` (the cheapest that meets the limit, or + the best found), the ``frontier``, and ``floor`` and + ``stopped`` when the limit is not met. + + Raises + ------ + ValueError + If an argument is invalid, or a lever's node cannot take it. + NotImplementedError + If a redundancy node is in a maintenance or common-cause + group, or as for ``availability``. + + Examples + -------- + A pump down about 5% of the time, 50 hours a repair: a second + pump at 5,000 keeps a bad year's downtime under 100 hours: + + >>> import surpyval as surv + >>> from repyability import RepairableRBD + >>> E = surv.Exponential.from_params + >>> pump = RepairableRBD( + ... [("s", "p"), ("p", "t")], + ... {"p": {"reliability": E([1e-3]), + ... "repairability": E([0.02])}}, + ... ) + >>> found = pump.least_spend_for_downtime( + ... 8760.0, 100.0, redundancy={"p": 5000.0}, + ... mc_samples=1000, seed=1, + ... ) + >>> found.met, found.design.copies, found.design.spend + (True, {'p': 1}, 5000.0) + """ + return _downtime_risk.least_spend_for_downtime( + self, + horizon, + limit, + level=level, + objective=objective, + measure=measure, + downtime=downtime, + redundancy=redundancy, + intervals=intervals, + max_units=max_units, + budget=budget, + value_rate=value_rate, + confidence=confidence, + mc_samples=mc_samples, + seed=seed, + engine=engine, + ) + + def best_switch_time( + self, + covariates, + value_rates, + horizon, + *, + discount_rate: float = 0.0, + mc_samples: Optional[int] = None, + seed: Optional[int] = None, + scan: int = 11, + engine: str = "auto", + state=None, + escalation=None, + rates: str = "nominal", + inflation=None, + ) -> SimulatedSwitchTime: + """The best time to switch blocks of the system from one way of + running them to another (a load, a speed, a temperature): the + switch time that maximises the simulated net present value of the + whole system. Simulated. + + In plain terms: running harder can earn more but wears the + blocks out faster. Each block in ``covariates`` runs on a + covariate schedule (a regression life, see the guide's [load + schedule](../guide/condition-based.md#is-it-worth-running-hot) + section); it runs at its first row of covariates until the switch + and at its second after, and the system earns the first of + ``value_rates`` per unit of time up before the switch and the + second after. Switching at 0 runs the second way from the start, + and at the horizon never switches; the answer says which time is + best, and how sure it is better than each end + (``difference_interval``). For one unit the same question is + worked out numerically by + [`best_switch_time`][repyability.best_switch_time]. + + Each candidate switch time is the diagram with those schedules, + simulated and priced as + [`npv_distribution`][repyability.RepairableRBD.npv_distribution] + prices its runs, every candidate from the same seed (common + random numbers), so the differences between candidates are much + less noisy than their values. The NPV is scanned at ``scan`` + times from 0 to the horizon and at 6 more between the best's + neighbours; the scan is returned to audit the answer, as the NPV + need not have one peak. The other blocks run as the diagram says. + + Parameters + ---------- + covariates : dict + For each block that switches, its two rows of covariates: + before the switch and after (two numbers for a model with one + covariate), e.g. ``{"pump": [[60.0], [85.0]]}``. Each must be a + block built on a covariate schedule (its spec's + ``"covariates"``), which this replaces. + value_rates : array_like + What the system earns per unit of time up before the switch, + and after, each at least 0. + horizon : float + The length of time to value, more than 0, in the component + models' unit. + discount_rate : float, optional + The continuous discount rate per unit time, as for + ``expected_npv``, by default 0. + mc_samples : int, optional + The runs at each switch time, by default 1,000. + seed : int, optional + Seeds the runs; every switch time's runs share it. By default + one is drawn from numpy's global RNG (``np.random.seed`` makes + it repeatable), and kept in the result. + scan : int, optional + The switch times scanned from 0 to the horizon, ends included, + at least 3, by default 11. + engine : str, optional + ``"auto"`` (the default), ``"python"`` or ``"numba"``, as for + ``simulate_timelines``. + state : dict, optional + Start from the components' current states rather than new, as + for ``simulate_timelines``. + escalation : dict, optional + A growth rate per unit time for some streams, by cost + category, component, ``"value"`` (or ``"salvage"``), as for + ``expected_npv``: an amount at ``t`` is its price times + ``exp(g t)``. By default None. + rates : str, optional + ``"nominal"`` (the default) or ``"real"``, as for + ``expected_npv``. + inflation : float, optional + With ``rates="real"``, the continuous inflation per unit time, + as for ``expected_npv``. + + Returns + ------- + SimulatedSwitchTime + The best switch time, its choice and mean NPV, the NPVs of + never switching and of switching at once, the runs of each, + and the scan. + + Raises + ------ + ValueError + If no block runs on a covariate schedule (as + ``routes.Refused``); if a block in ``covariates`` does not, or + its rows, ``value_rates``, ``horizon``, ``discount_rate``, + ``mc_samples``, ``scan`` or ``engine`` is invalid; or as for + ``npv_distribution``. + NotImplementedError + As for ``npv_distribution``. + + Examples + -------- + A pump whose life wears out (Weibull, under proportional hazards + on its load), replaced at 80 a failure, run hot (load 1.5, earning + 1.5 an hour) or cool (load 1, earning 1) over 200 hours. Running + hot while it is new and then cool beats either way throughout: + + >>> import numpy as np + >>> import surpyval as surv + >>> from repyability import RepairableRBD + >>> 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]) + >>> rbd = RepairableRBD( + ... [("s", "pump"), ("pump", "t")], + ... { + ... "pump": { + ... "reliability": model, + ... "repairability": surv.Exponential.from_params([1.0]), + ... "replace_cost": 80.0, + ... "covariates": surv.StepSchedule.from_changepoints( + ... [0.0], [[1.0]] + ... ), + ... } + ... }, + ... ) + >>> best = rbd.best_switch_time( + ... {"pump": [[1.5], [1.0]]}, [1.5, 1.0], 200.0, + ... mc_samples=200, seed=1, scan=5, + ... ) + >>> best.choice, round(best.switch_time, 1) + ('switch', 28.6) + >>> round(best.npv), round(best.switch_at_once_npv) + (52, 46) + >>> round(best.never_switch_npv) + -27 + >>> gain = best.difference_interval("switch at once") + >>> round(gain.lower, 1), round(gain.upper, 1) + (2.2, 9.1) + """ + return _switch_runs.best_switch_time( + self, + covariates, + value_rates, + horizon, + discount_rate=discount_rate, + mc_samples=mc_samples, + seed=seed, + scan=scan, + engine=engine, + state=state, + escalation=escalation, + rates=rates, + inflation=inflation, ) def plan_vs_actual( @@ -4243,6 +5337,9 @@ def plan_vs_actual( method: str = "p", state=None, start_state=None, + escalation=None, + rates: str = "nominal", + inflation=None, ) -> PlanVsActual: """A plan against what happened: the plan's expected cash flows so far beside those the outage log implies, where the two differ, and @@ -4284,9 +5381,10 @@ def plan_vs_actual( discount_rate : float, optional The continuous discount rate per unit time, as for ``expected_npv``, by default 0. - value_rate : float, optional - What the system earns per unit time while it works, by - default 0. + value_rate : float or ValueSchedule, optional + What the system earns per unit time while it works (a number + or a [`ValueSchedule`][repyability.ValueSchedule] of steps on + the plan's clock), by default 0. periods : int or array-like, optional The periods of the tables over the whole horizon, as for ``expected_npv``; a period that ``now`` falls in is split in @@ -4302,6 +5400,17 @@ def plan_vs_actual( start_state : dict, optional The components' states at the start of the plan, as for ``expected_npv``'s ``state``. By default every component new. + escalation : dict, optional + A growth rate per unit time for some streams, by cost + category, component, ``"value"`` (or ``"salvage"``), as for + ``expected_npv``: an amount at ``t`` is its price times + ``exp(g t)``. By default None. + rates : str, optional + ``"nominal"`` (the default) or ``"real"``, as for + ``expected_npv``. + inflation : float, optional + With ``rates="real"``, the continuous inflation per unit time, + as for ``expected_npv``. Returns ------- @@ -4360,6 +5469,9 @@ def plan_vs_actual( method=method, state=state, start_state=start_state, + escalation=escalation, + rates=rates, + inflation=inflation, ) @contextmanager @@ -4379,6 +5491,7 @@ def _sharing_curves(self): finally: self._curve_memo = None + @_long_run.follows_upgrades def capacity_distribution( self, working_nodes: Optional[Collection[Hashable]] = None, @@ -4675,6 +5788,10 @@ def _crews_couple(self) -> bool: ``_standby_long_run``), and the nodes stay independent.""" if not _crews._crews_limited(self): return False + if _crews._call_when(self): + # A call-out crew ties the jobs together whoever owns them + # (a standby group's own chain does not count it). + return True owners = { key.node if isinstance(key, _Unit) else key for key in _crews._crew_served(self) @@ -6031,6 +7148,7 @@ def cost( conditional=conditional, ) + @_long_run.follows_upgrades def node_availability(self) -> dict[Hashable, float]: """Returns each node's long-run (steady-state) availability. @@ -6108,6 +7226,7 @@ def node_availability(self) -> dict[Hashable, float]: """ return _long_run.node_availability(self) + @_long_run.follows_upgrades def node_action_rates( self, working_nodes: Optional[Collection[Hashable]] = None, @@ -6280,6 +7399,7 @@ def crew_states( _shutdowns.refuse(self, "crew_states") return _crews.crew_states(self, working_nodes, broken_nodes) + @_long_run.follows_upgrades def replacement_cycle(self, node: Hashable) -> ReplacementCycle: """The renewal cycle of a component under block replacement or replaced on condition, in the long run. @@ -6424,6 +7544,7 @@ def simulation_samples( entropy=entropy, ) + @_long_run.follows_upgrades def system_failure_frequency( self, working_nodes: Optional[Collection[Hashable]] = None, @@ -6508,6 +7629,7 @@ def system_failure_frequency( self, working_nodes=working_nodes, broken_nodes=broken_nodes ) + @_long_run.follows_upgrades def mean_time_between_failures( self, working_nodes: Optional[Collection[Hashable]] = None, @@ -6568,6 +7690,7 @@ def mean_time_between_failures( self, working_nodes=working_nodes, broken_nodes=broken_nodes ) + @_long_run.follows_upgrades def mean_up_time( self, working_nodes: Optional[Collection[Hashable]] = None, @@ -6628,6 +7751,7 @@ def mean_up_time( self, working_nodes=working_nodes, broken_nodes=broken_nodes ) + @_long_run.follows_upgrades def mean_down_time( self, working_nodes: Optional[Collection[Hashable]] = None, @@ -6689,6 +7813,7 @@ def mean_down_time( ) @_times_first() + @_long_run.follows_upgrades def birnbaum_importance( self, working_nodes: Optional[Collection[Hashable]] = None, @@ -6814,6 +7939,7 @@ def birnbaum_importance( ) @_times_first() + @_long_run.follows_upgrades def improvement_potential( self, working_nodes: Optional[Collection[Hashable]] = None, @@ -6906,6 +8032,7 @@ def improvement_potential( ) @_times_first() + @_long_run.follows_upgrades def risk_achievement_worth( self, working_nodes: Optional[Collection[Hashable]] = None, @@ -7004,6 +8131,7 @@ def risk_achievement_worth( ) @_times_first() + @_long_run.follows_upgrades def risk_reduction_worth( self, working_nodes: Optional[Collection[Hashable]] = None, @@ -7100,6 +8228,7 @@ def risk_reduction_worth( ) @_times_first() + @_long_run.follows_upgrades def criticality_importance( self, working_nodes: Optional[Collection[Hashable]] = None, @@ -7226,6 +8355,7 @@ def criticality_importance( ) @_times_first() + @_long_run.follows_upgrades def fussell_vesely( self, fv_type: str = "c", @@ -7602,6 +8732,7 @@ def with_levers(self, values) -> "RepairableRBD": """ return _sensitivity.with_levers(self, values) + @_long_run.follows_upgrades def mean_availability_uncertainty( self, uncertainty: Optional[Dict[Hashable, Any]] = None, @@ -7844,6 +8975,7 @@ def mission_availability_uncertainty( state=state, ) + @_long_run.follows_upgrades def expected_cost_rate_uncertainty( self, uncertainty: Optional[Dict[Hashable, Any]] = None, @@ -7889,6 +9021,142 @@ def expected_cost_rate_uncertainty( sampling=sampling, ) + def expected_npv_uncertainty( + self, + horizon, + uncertainty: Optional[Dict[Hashable, Any]] = None, + *, + discount_rate: float = 0.0, + value_rate: float = 0.0, + working_nodes: Optional[Collection[Hashable]] = None, + broken_nodes: Optional[Collection[Hashable]] = None, + method: str = "p", + state=None, + retire_at=None, + salvage=None, + n_draws: int = 1000, + seed=None, + sampling: str = "random", + shares: bool = True, + ) -> NPVUncertainty: + """The expected net present value over plausible models of the + components: how unsure the NPV is because the fitted models are + estimates. Each draw gives the uncertain components plausible + models, as ``mean_availability_uncertainty`` draws them, and values + the plan exactly as + [`expected_npv`][repyability.RepairableRBD.expected_npv] does. + + The models no input draws (a model given by hand, with no fit + behind it, or one left out of ``uncertainty``) are held as they + are in every draw, and listed in the result's ``held_fixed``: the + spread leaves out their uncertainty. Each input's share of the + NPV's variance is worked out by the delta method (the NPV's + derivatives in the input's parameters, by central differences of + 1% of each, against their covariance), as + ``uncertainty_importance(method="delta")`` splits the other + quantities'. + + Parameters + ---------- + horizon : float + The length of time to value, as for ``expected_npv``. + uncertainty : dict, optional + The uncertain inputs, as for + ``mean_availability_uncertainty``. By default every fitted + model. + discount_rate : float, optional + As for ``expected_npv``. + value_rate : float, optional + As for ``expected_npv``. + working_nodes : Collection[Hashable], optional + As for ``expected_npv``. + broken_nodes : Collection[Hashable], optional + As for ``expected_npv``. + method : str, optional + As for ``expected_npv``. + state : dict or str, optional + As for ``expected_npv``. + retire_at : float, optional + As for ``expected_npv``. + salvage : float or dict, optional + As for ``expected_npv``. + n_draws : int, optional + The number of draws, by default 1000. + seed : int, optional + Seed for the draws. + sampling : str, optional + ``"random"`` (the default) or ``"sobol"``. + shares : bool, optional + Split the variance among the inputs (``variance_shares``), by + default True: two more valuations for each parameter drawn. + + Returns + ------- + NPVUncertainty + The NPV of every draw, the ``nominal`` NPV, the intervals + (``interval(level)``), each input's share of the variance and + the models held fixed. + + Raises + ------ + ValueError, NotImplementedError + As for ``mean_availability_uncertainty`` and + ``expected_npv``. + + Examples + -------- + A pump whose life was fitted to 30 failures, earning 10 an hour + while it works, over 5 years at 8% a year: + + >>> import math + >>> import numpy as np + >>> import surpyval as surv + >>> from repyability import RepairableRBD + >>> life = surv.Weibull.fit(np.linspace(400.0, 1800.0, 30)) + >>> rbd = RepairableRBD( + ... [("s", "p"), ("p", "t")], + ... { + ... "p": { + ... "reliability": life, + ... "repairability": surv.Exponential.from_params([0.1]), + ... "repair_cost": 500.0, + ... } + ... }, + ... ) + >>> result = rbd.expected_npv_uncertainty( + ... 5 * 8760.0, + ... discount_rate=math.log(1.08) / 8760, + ... value_rate=10.0, + ... n_draws=50, + ... seed=1, + ... ) + >>> lower, upper = result.interval(0.9) + >>> round(result.nominal), round(lower), round(upper) + (344241, 342538, 345967) + >>> result.variance_shares + {'p': 1.0} + >>> result.held_fixed + [{'node': 'p', 'role': 'repairability'}] + """ + return _repairable_uncertainty.expected_npv_uncertainty( + self, + horizon, + uncertainty, + n_draws=n_draws, + seed=seed, + sampling=sampling, + shares=shares, + discount_rate=discount_rate, + value_rate=value_rate, + working_nodes=working_nodes, + broken_nodes=broken_nodes, + method=method, + state=state, + retire_at=retire_at, + salvage=salvage, + ) + + @_long_run.follows_upgrades def uncertainty_importance( self, x=None, @@ -8019,6 +9287,7 @@ def uncertainty_importance( ) @_times_first() + @_long_run.follows_upgrades def differential_importance( self, working_nodes: Optional[Collection[Hashable]] = None, @@ -8301,6 +9570,7 @@ def availability_rate( ) @_times_first("window") + @_long_run.follows_upgrades def barlow_proschan_importance( self, working_nodes: Optional[Collection[Hashable]] = None, @@ -8396,6 +9666,7 @@ def barlow_proschan_importance( state=state, ) + @_long_run.follows_upgrades def pfd_breakdown( self, working_nodes: Optional[Collection[Hashable]] = None, @@ -8487,6 +9758,7 @@ def pfd_breakdown( ) @_times_first() + @_long_run.follows_upgrades def joint_importance( self, working_nodes: Optional[Collection[Hashable]] = None, diff --git a/repyability/rbd/results.py b/repyability/rbd/results.py index f0d3266b..d70b4ae2 100644 --- a/repyability/rbd/results.py +++ b/repyability/rbd/results.py @@ -877,6 +877,61 @@ def shown(value) -> str: ) +@dataclass(repr=False) +class NPVUncertainty(UncertaintyResult): + """The spread of a plan's expected net present value over plausible + models of its components: returned by + ``RepairableRBD.expected_npv_uncertainty``. + + Each draw gives the uncertain components plausible models (from a + fit's parameter covariance, a Bayesian fit's posterior, or the + distributions given) and values the plan exactly as ``expected_npv`` + does. The spread is how unsure the NPV is because the models are + estimates, not how a run of the plan varies (``npv_distribution``). + ``interval(0.9)`` gives the 90% interval, as for every + ``UncertaintyResult``. + + Attributes + ---------- + samples : numpy.ndarray + The expected NPV of each draw. + nominal : float + The expected NPV with every component's own model. + n_draws : int + The number of draws. + band : str or None + What the band is: ``"confidence"``, ``"credible"``, ``"given"`` or + ``"mixed"`` (see ``UncertaintyResult``). + horizon : float + The length of time valued, as for ``expected_npv``. + discount_rate : float + The continuous discount rate per unit time it was valued at. + value_rate : float + The value earned per unit time while the system works. + variance_shares : dict + Each uncertain input's share of the NPV's variance by the delta + method (the NPV's derivatives in the input's parameters against + their covariance; summing to 1), by the input's key; empty with + ``shares=False``. + delta_variance : float or None + The NPV's variance by the delta method, which the shares divide: + near ``std ** 2`` where the NPV is close to linear in the + parameters over their spread. None with ``shares=False``. + held_fixed : list + The models every draw keeps as they are, each as ``{"node": ..., + "role": ...}`` (a role as ``parameter_sensitivity`` names it; + ``"ccf"`` for a common-cause group's model, under its members): + their uncertainty is not in the spread. + """ + + horizon: float = 0.0 + discount_rate: float = 0.0 + value_rate: float = 0.0 + variance_shares: Dict[Hashable, float] = field(default_factory=dict) + delta_variance: Optional[float] = None + held_fixed: List[Dict[str, Any]] = field(default_factory=list) + + @dataclass class UpDownImportance(_ResultMapping): """An importance measure split by system state. @@ -1252,11 +1307,13 @@ class CostResult(_ResultMapping): ``"replace"`` (both charged per failure; for a hidden failure, when an inspection finds it), ``"preventive"`` (charged per preventive replacement), ``"inspection"`` (charged per inspection), - ``"component_downtime"``, ``"system_downtime"`` and ``"setup"`` (a - maintenance group's set-up cost, charged once per stop), found as + ``"component_downtime"``, ``"system_downtime"``, ``"setup"`` (a + maintenance group's set-up cost, charged once per stop), + ``"shutdown"`` and ``"crews"`` (the repair crews' salaries, + ``crew_cost_rate``, the same in every replication), found as ``mean`` is: exact for an exact ``mean``, given the modules' histories for a conditional one, and otherwise the simulations' own - means. The seven sum to ``mean``, but for a run controlled by a + means. They sum to ``mean``, but for a run controlled by a twin that is not the system itself (``control_variate=True``), whose breakdowns are the simulations' own and sum to ``sample_mean``. @@ -1857,8 +1914,9 @@ class ExpectedCost(_ResultMapping): The expected cost of ``"repair"`` and ``"replace"`` (per corrective action), ``"preventive"`` (per preventive replacement), ``"inspection"`` (per test), ``"component_downtime"``, - ``"system_downtime"`` and ``"setup"`` (once per stop of a - maintenance group), as in ``CostResult``. + ``"system_downtime"``, ``"setup"`` (once per stop of a + maintenance group), ``"shutdown"`` and ``"crews"`` (the repair + crews' salaries), as in ``CostResult``. by_component : dict The expected cost attributable to each costed component (its repair, replace, preventive, inspection and own downtime cost). @@ -2115,7 +2173,8 @@ class ExpectedNPV(_ResultMapping): The continuous rate per unit time the amounts were discounted at (0: not discounted). value_rate : float - The value earned per unit time while the system works. + The value earned per unit time while the system works (NaN with + a ``value_schedule``). npv : float The expected net present value: ``value - cost``. value : float @@ -2125,7 +2184,9 @@ class ExpectedNPV(_ResultMapping): acquisition cost (paid at the start). eac : float The equivalent annual cost: ``cost`` divided by the - ``annuity_factor``, per unit of the models' time. + ``annuity_factor``, per unit of the models' time: the level + annuity at ``discount_rate`` worth the costs, so with real rates a + level real annuity. undiscounted_npv : float The same sum with no discounting. undiscounted_value : float @@ -2136,25 +2197,60 @@ class ExpectedNPV(_ResultMapping): cost_by_category : dict The present value of the cost in each category (``"repair"``, ``"replace"``, ``"preventive"``, ``"inspection"``, - ``"component_downtime"``, ``"system_downtime"``, ``"setup"``, and - ``"acquisition"``), as positive amounts. + ``"component_downtime"``, ``"system_downtime"``, ``"setup"``, + ``"shutdown"``, ``"crews"`` and ``"acquisition"``), as positive + amounts. cost_by_component : dict The present value of the cost attributable to each costed component, with its acquisition cost. period_ends : list Where each period of the cash-flow table ends, in the models' time: the last is the horizon. + salvage : float + The present value of the salvage credited at the end (the + retirement, or the horizon); 0 with none. + undiscounted_salvage : float + The salvage, not discounted. + retire_at : float or None + When the system is retired, before the horizon: nothing is earned + or spent after it. None if it runs to the horizon. + rate_sensitivity : float or None + How the NPV moves with the continuous discount rate, ``d npv / + d r``, per unit of the rate per unit time (times a change of + rate, the NPV's change), from + ``expected_npv(rate_sensitivity=True)``; None otherwise. It is + negative where the value earned outweighs the costs, as a higher + rate shrinks the later earnings. + rate_sensitivity_error : float or None + An estimate of the error of ``rate_sensitivity``, from the + differences it is worked out from (see ``expected_npv``); None + with no ``rate_sensitivity``. + rate_basis : str + ``"nominal"`` or ``"real"``: what ``discount_rate`` and the + growths are in. With ``"real"`` and an ``inflation``, the + undiscounted amounts are nominal (grown by it too); the present + values are the same either way. + inflation : float or None + The continuous inflation per unit time real rates were made + nominal with; None when not given. + escalation : dict + Each stream's growth per unit time, as given (a cost category, a + component, ``"value"`` or ``"salvage"``): an amount at ``t`` is + its price times ``exp(g t)``. Empty with none. + value_schedule : ValueSchedule or None + The value earned as steps, when given one (``value_rate`` is + then NaN); None for a single rate. cash_flows : list The cash-flow table: one dict per period, category and component with something in it, with ``period`` (from 1), ``start``, ``end``, - ``category`` (a cost category, or ``"value"``), ``component`` (None - for value, the system's downtime and a group's set-up), - ``present_value`` and ``undiscounted``, both signed: costs - negative, value positive. The ``present_value`` of all rows add up + ``category`` (a cost category, ``"value"`` or ``"salvage"``), + ``component`` (None for value, the system's salvage, its downtime + and a group's set-up), + ``present_value`` and ``undiscounted``, both signed: costs negative, + value and salvage positive. The ``present_value`` of all rows add up to ``npv``. Costs given by period and category are the exact - increments of the expected cost; the table is for applying your - own tax, depreciation and financial-year conventions outside the - package. + increments of the expected cost; the table is for applying your own + tax, depreciation and financial-year conventions outside the package. Examples -------- @@ -2200,22 +2296,451 @@ class ExpectedNPV(_ResultMapping): cost_by_component: Dict[Hashable, float] period_ends: List[float] cash_flows: List[Dict[str, Any]] + salvage: float = 0.0 + undiscounted_salvage: float = 0.0 + retire_at: Optional[float] = None + rate_sensitivity: Optional[float] = None + rate_sensitivity_error: Optional[float] = None + rate_basis: str = "nominal" + inflation: Optional[float] = None + escalation: Dict[Hashable, float] = field(default_factory=dict) + value_schedule: Any = None @property def annuity_factor(self) -> float: - """What one unit of cost per unit time, steady over the horizon, - is worth now: ``(1 - exp(-r H)) / r`` for the ``discount_rate`` - ``r`` and the ``horizon`` ``H``, and ``H`` with none. + """What one unit of cost per unit time, steady over the horizon + (to the retirement, with a ``retire_at``), is worth now: + ``(1 - exp(-r H)) / r`` for the ``discount_rate`` ``r`` and the + ``horizon`` ``H``, and ``H`` with none. Returns ------- float The factor ``eac`` divides the cost by. """ + length = self.horizon if self.retire_at is None else self.retire_at if not self.discount_rate: - return self.horizon + return length return float( - -np.expm1(-self.discount_rate * self.horizon) / self.discount_rate + -np.expm1(-self.discount_rate * length) / self.discount_rate + ) + + +def _order_statistic(ordered: np.ndarray, p: float) -> float: + """The ``p`` quantile of the sorted values ``ordered``: the smallest + value with at least a share ``p`` of them at or below it (the + ``ceil(p n)``-th, at least the first).""" + from repyability.value._risk import quantile + + return quantile(ordered, p) + + +@dataclass +class NPVDistribution(_ResultMapping): + """The net present value of each simulated run of a system over a + horizon, and their spread: returned by + ``RepairableRBD.npv_distribution``. + + In plain terms: [`ExpectedNPV`][repyability.ExpectedNPV] is the + average over every way the failures could fall; this is how far one + run, the one you will live through, can fall from it. ``p10`` is the + value nine runs in ten beat, ``probability_below_hurdle`` the chance + of ending below a value you must reach, and ``cvar`` the average of + the worst ``tail`` of the runs: a plan with a slightly lower mean and + a much better worst case is often the one to choose. + + Each run's NPV is its value earned while the system was up less every + cost it met, each discounted at the time it fell (``exp(-r t)``), the + acquisition costs paid at the start. ``mean`` estimates the expected + NPV, within ``mean_interval()``; the percentiles and ``cvar`` describe + the runs and do not shrink with more of them. + + Attributes + ---------- + horizon : float + The length of time valued, in the models' unit. + discount_rate : float + The continuous rate per unit time the amounts were discounted at. + value_rate : float + The value earned per unit time while the system works (NaN with + a ``value_schedule``). + samples : numpy.ndarray + Each run's net present value: ``value_samples - cost_samples``, + plus ``contract_samples`` with a contract. + value_samples : numpy.ndarray + Each run's present value earned while the system worked. + cost_samples : numpy.ndarray + Each run's present value of every cost, the acquisition included. + mean : float + The runs' mean NPV: the estimate of the expected NPV. + value : float + The runs' mean present value earned. + cost : float + The runs' mean present cost. + undiscounted_npv : float + The runs' mean NPV with no discounting. + undiscounted_value : float + The runs' mean value earned, undiscounted. + undiscounted_cost : float + The runs' mean cost, undiscounted, with the acquisition costs. + cost_by_category : dict + The runs' mean present cost in each category, as for + ``ExpectedNPV``. + cost_by_component : dict + The runs' mean present cost of each costed component, with its + acquisition cost. + p10 : float + The 10th percentile of the runs' NPVs (see ``percentile``). + p50 : float + Their median, the 50th percentile. + p90 : float + Their 90th percentile. + hurdle : float or None + The value the NPV is compared with, if given. + probability_below_hurdle : float or None + The share of the runs whose NPV is below ``hurdle`` (None without + one). + tail : float + The share of the runs ``cvar`` averages. + cvar : float + The conditional value at risk: the mean NPV of the worst ``tail`` + of the runs (the ``ceil(tail n)`` lowest). + n_simulations : int + How many runs. + seed : int + The seed of the runs (drawn when none was given), to repeat them. + engine : str + The engine that simulated them: ``"python"`` or ``"numba"``. + priced_at_mean : list + The components with a cost given as a distribution: each such + cost is charged at its mean, so the spread is that of the events + alone. + contract : dict or None + The ``AvailabilityContract``'s terms (its ``to_dict()``), if one + was given. + contract_samples : numpy.ndarray or None + Each run's present value of the contract's payments, a category + of its own: bonuses positive, penalties negative, each paid at + its period's end (None without a contract). + contract_payoff : float + The runs' mean present value of the contract's payments (0 + without a contract). + undiscounted_contract_payoff : float + The runs' mean total of the contract's payments, undiscounted. + period_ends : list of float or None + The ends of the contract's periods. + period_availability : numpy.ndarray or None + Each run's availability in each of the contract's periods, one + row a run: the share of the period the system was up. + rate_basis : str + ``"nominal"`` or ``"real"``, as for ``ExpectedNPV``. + inflation : float or None + The continuous inflation per unit time real rates were made + nominal with; None when not given. + escalation : dict + Each stream's growth per unit time, as given (see + ``ExpectedNPV``); empty with none. + value_schedule : ValueSchedule or None + The value earned as steps, when given one (``value_rate`` is + then NaN); None for a single rate. + salvage : float + The present value of the salvage the components' plans credit at + the end (their own ``"salvage"``, as a number), the same in every + run and in ``samples``; 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); None otherwise. + + Examples + -------- + A pump earning 10 per hour while it works, failing on average every + 1000 hours, repaired in 10 at 500 per repair, bought for 20,000, + valued over 5 years of 8,760 hours at 8% a year: + + >>> import math + >>> import surpyval as surv + >>> from repyability import RepairableRBD + >>> rbd = RepairableRBD( + ... [("s", "p"), ("p", "t")], + ... { + ... "p": { + ... "reliability": surv.Exponential.from_params([1e-3]), + ... "repairability": surv.Exponential.from_params([0.1]), + ... "repair_cost": 500.0, + ... "acquisition_cost": 20000.0, + ... } + ... }, + ... ) + >>> r = math.log(1.08) / 8760 # per hour + >>> runs = rbd.npv_distribution( + ... 5 * 8760.0, discount_rate=r, value_rate=10.0, mc_samples=2000, + ... seed=1, hurdle=320_000, + ... ) + >>> round(runs.mean), round(runs.p10), round(runs.p90) + (322045, 317651, 326267) + >>> round(runs.probability_below_hurdle, 3), round(runs.cvar) + (0.268, 315980) + """ + + horizon: float + discount_rate: float + value_rate: float + samples: np.ndarray + value_samples: np.ndarray + cost_samples: np.ndarray + mean: float + value: float + cost: float + undiscounted_npv: float + undiscounted_value: float + undiscounted_cost: float + cost_by_category: Dict[str, float] + cost_by_component: Dict[Hashable, float] + p10: float + p50: float + p90: float + hurdle: Optional[float] + probability_below_hurdle: Optional[float] + tail: float + cvar: float + n_simulations: int + seed: Any + engine: str + priced_at_mean: List[Hashable] + contract: Optional[Dict[str, Any]] = None + contract_samples: Optional[np.ndarray] = None + contract_payoff: float = 0.0 + undiscounted_contract_payoff: float = 0.0 + period_ends: Optional[List[float]] = None + period_availability: Optional[np.ndarray] = None + rate_basis: str = "nominal" + inflation: Optional[float] = None + escalation: Dict[Hashable, float] = field(default_factory=dict) + value_schedule: Any = None + salvage: float = 0.0 + undiscounted_salvage: float = 0.0 + retire_at: Optional[float] = None + + @property + def std(self) -> float: + """The standard deviation of the runs' NPVs (nan for one run). + + Returns + ------- + float + How much one run's NPV varies. + """ + if self.samples.size < 2: + return math.nan + return float(np.std(self.samples, ddof=1)) + + def mean_interval(self, confidence: float = 0.95) -> ConfidenceInterval: + """A confidence interval for the expected NPV: ``mean +/- z * + std / sqrt(n)``, by the central limit theorem, for the normal + quantile ``z`` of ``confidence``. It says how well the runs pin + the average down; for the range one run falls in, use + ``percentile``. + + Parameters + ---------- + confidence : float, optional + The confidence level, strictly between 0 and 1, by default 0.95. + + Returns + ------- + ConfidenceInterval + The mean, its bounds, standard error and the number of runs. + + Raises + ------ + ValueError + If ``confidence`` is not strictly between 0 and 1. + """ + if not 0.0 < confidence < 1.0: + raise ValueError("confidence must be between 0 and 1.") + se = montecarlo.standard_error(self.samples, False) + z = montecarlo.z_value(confidence) + return ConfidenceInterval( + estimate=self.mean, + lower=self.mean - z * se, + upper=self.mean + z * se, + confidence=confidence, + standard_error=se, + n_samples=int(self.samples.size), + method="simulated", + ) + + def percentile(self, q: float) -> float: + """The ``q``-th percentile of the runs' NPVs: the lowest run's + NPV with at least ``q`` percent of the runs at or below it (an + order statistic, the ``ceil(q n / 100)``-th lowest, no + interpolation). + + Parameters + ---------- + q : float + The percentile, more than 0 and at most 100: ``q`` strictly + between 0 and 1 warns, as it is more likely a fraction meant. + + Returns + ------- + float + The NPV. + + Raises + ------ + ValueError + If ``q`` is not in ``(0, 100]``. + """ + p = self._share(q) + return _order_statistic(np.sort(self.samples), p) + + def percentile_interval( + self, q: float, confidence: float = 0.95 + ) -> Tuple[float, float]: + """A confidence interval for the ``q``-th percentile of the NPV, by + the binomial method (distribution-free): order statistics ``l`` + and ``u`` such that the percentile lies between them with at + least ``confidence``, as the number of runs below it is binomial. + A bound the runs are too few to give is ``-inf`` or ``inf``. + + Parameters + ---------- + q : float + The percentile, as for ``percentile``. + confidence : float, optional + The confidence level, strictly between 0 and 1, by default 0.95. + + Returns + ------- + tuple of float + The lower and upper bounds. + + Raises + ------ + ValueError + If ``q`` or ``confidence`` is out of range. + """ + from scipy.stats import binom + + p = self._share(q) + if not 0.0 < confidence < 1.0: + raise ValueError("confidence must be between 0 and 1.") + ordered = np.sort(self.samples) + n = ordered.size + alpha = 1.0 - confidence + low = int(binom.ppf(alpha / 2.0, n, p)) + high = int(binom.ppf(1.0 - alpha / 2.0, n, p)) + 1 + lower = float(ordered[low - 1]) if low >= 1 else -math.inf + upper = float(ordered[high - 1]) if high <= n else math.inf + return lower, upper + + def probability_below(self, hurdle: float) -> float: + """The share of the runs whose NPV is below ``hurdle``. + + Parameters + ---------- + hurdle : float + The value to reach. + + Returns + ------- + float + The estimated chance of ending below it. + """ + return float(np.mean(self.samples < float(hurdle))) + + @staticmethod + def _share(q) -> float: + _on_percent_scale(q, "percentile") + q = float(q) + if not 0.0 < q <= 100.0: + raise ValueError( + "The percentile must be more than 0 and at most 100; got " + f"{q!r}." + ) + return q / 100.0 + + def __repr__(self) -> str: + # A summary (#235): the runs are in ``samples``. + parts = [ + f"mean={self.mean:.6g}", + f"p10={self.p10:.6g}", + f"p50={self.p50:.6g}", + f"p90={self.p90:.6g}", + f"cvar={self.cvar:.6g}", + f"tail={self.tail:g}", + ] + if self.hurdle is not None: + parts.append( + f"probability_below_hurdle={self.probability_below_hurdle:.4g}" + ) + if self.contract is not None: + parts.append(f"contract_payoff={self.contract_payoff:.6g}") + parts += [ + f"n_simulations={self.n_simulations}", + f"horizon={self.horizon:g}", + ] + return f"NPVDistribution({', '.join(parts)})" + + +@dataclass +class NPVComparison(_ResultMapping): + """How much more one plan is worth than another, run by run, on the + same random numbers: returned by ``RepairableRBD.compare_npv``. + + In plain terms: both plans are simulated with the same failures and + repairs wherever they share a component (the same random numbers), + so each run's difference comes from how the plans differ, not from + luck. The difference is then known far more precisely than either + plan's value: compare ``interval.standard_error`` with + ``independent_standard_error``, what two independent runs of the + same size would give. + + Attributes + ---------- + differences : numpy.ndarray + Each run's NPV of this plan less the other's. + mean : float + The mean difference: the estimate of the expected one. + interval : ConfidenceInterval + The mean difference with its standard error and normal + confidence interval (not clipped: it may be negative). + probability_other_better : float + The share of runs in which the other plan's NPV is higher. + independent_standard_error : float + The standard error the mean difference would have from two + independent runs of the same size: the two plans' own standard + errors combined. + this : NPVDistribution + This plan's runs. + other : NPVDistribution + The other plan's runs. + n_simulations : int + How many runs of each plan. + seed : int + The seed both plans' runs were made from. + """ + + differences: np.ndarray + mean: float + interval: ConfidenceInterval + probability_other_better: float + independent_standard_error: float + this: NPVDistribution + other: NPVDistribution + n_simulations: int + seed: Any + + def __repr__(self) -> str: + # A summary (#235): the runs are in ``differences``. + return ( + f"NPVComparison(mean={self.mean:.6g}, " + f"standard_error={self.interval.standard_error:.4g}, " + f"probability_other_better={self.probability_other_better:.4g}, " + f"n_simulations={self.n_simulations})" ) @@ -2374,6 +2899,36 @@ class TotalCostAllocation(_ResultMapping): discount_rate : float The continuous discount rate the running costs were discounted at (0: undiscounted). + objective : str + What the design was chosen by: ``"cost"`` (the lowest total + cost), ``"npv"`` (the highest net present value) or ``"eac"`` + (the lowest equivalent annual cost, less the value earned), the + last two with a ``value_rate``. Over one horizon ``"npv"`` and + ``"eac"`` choose the same design. + value_rate : float + The value earned per unit time while the system works that the + objective counted. + value : float or None + For ``"npv"`` and ``"eac"``, the present value of what the system + earns over the horizon: ``value_rate`` times its long-run + availability times the horizon's present value. None for + ``"cost"``, as are the four below. + running_cost : float or None + The present value of the running costs over the horizon, with + the cost of the system's downtime: ``total_cost - + acquisition_cost``. + npv : float or None + The net present value: ``value - total_cost``, the split being + ``value - acquisition_cost - running_cost``. + eac : float or None + The equivalent annual cost, less the value earned: the steady + amount per unit time over the horizon worth ``-npv`` (``-npv`` + over the horizon's present value; ``nan`` over a horizon of 0). + basis : str or None + What the net present value is made of, in words, with what is + approximate in it; and, with limited repair crews, that each + design's values come from the crews' Markov chain (under any + objective). Examples -------- @@ -2411,6 +2966,13 @@ class TotalCostAllocation(_ResultMapping): method: str trains: Optional[Dict[Hashable, list]] = None discount_rate: float = 0.0 + objective: str = "cost" + value_rate: float = 0.0 + value: Optional[float] = None + running_cost: Optional[float] = None + npv: Optional[float] = None + eac: Optional[float] = None + basis: Optional[str] = None @dataclass @@ -2469,12 +3031,133 @@ class MaintenancePlan(_ResultMapping): ``offset_shares``, or else each keeping its share of the interval, so that plans compare as they are. ``with_intervals`` takes them as they are. None for ``optimal_replacement_intervals``. + objective : str + What the intervals were chosen to minimise: ``"cost"`` (the + long-run cost rate, or with a cost cap the unavailability), + ``"eac"`` (the equivalent annual cost at ``discount_rate``, less + the value earned) or ``"npv"`` (less the expected net present + value over ``horizon``). + discount_rate : float + The continuous rate per unit time the objective was discounted + at (0: not discounted). + value_rate : float + The value earned per unit time while the system works that the + objective counted. + horizon : float or None + The horizon of ``"npv"``; None otherwise. + objective_value : float or None + What the objective comes to with those intervals: for ``"eac"`` + the equivalent annual cost less the value earned, per unit time; + for ``"npv"`` the expected net present value. None for + ``"cost"``, whose value is ``cost_rate``. + basis : str or None + For ``"eac"`` and ``"npv"``, what ``objective_value`` is made + of, in words, with what is approximate in it. + robustness : PlanRobustness or None + With ``optimal_replacement_intervals(robust=...)``, how often the + choice stays the best across draws of the uncertain models, and + what it loses where it does not; None otherwise. """ intervals: Dict[Hashable, float] cost_rate: float availability: float offsets: Optional[Dict[Hashable, float]] = None + objective: str = "cost" + discount_rate: float = 0.0 + value_rate: float = 0.0 + horizon: Optional[float] = None + objective_value: Optional[float] = None + basis: Optional[str] = None + robustness: Optional["PlanRobustness"] = None + + +@dataclass +class PlanRobustness(_ResultMapping): + """How robust a choice of intervals is to the uncertainty of the + models it was made with: the ``robustness`` of a ``MaintenancePlan`` + from ``RepairableRBD.optimal_replacement_intervals(robust=...)``. + + Intervals chosen on fitted models are the best for those models. Each + draw gives the uncertain components plausible models (as + ``mean_availability_uncertainty`` draws them), and the choice is + scored again under them, by the plan's own objective, against other + plans: by default the ``candidates`` near it (each interval one step + either way: the next of ``allowed``, or a quarter longer or shorter + without), every candidate under the same draws; or, with + ``robust="reoptimise"``, against each draw's own best intervals, + chosen again (slower). The ``score`` is what the choice minimises: the + cost rate (or with a cost cap the unavailability), the equivalent + annual cost less the value earned, or for ``"npv"`` less the expected + NPV; a ``regret`` is in its units, how much worse the choice scores + than the best plan of the draw. + + Attributes + ---------- + method : str + ``"neighbours"`` or ``"reoptimise"``. + candidates : list + The plans compared, the choice first: each a dict of node to + interval. With ``"reoptimise"``, the choice alone. + scores : numpy.ndarray + Each draw's score of each candidate (a row each draw). + meets_target : numpy.ndarray + Whether each candidate meets the plan's target + (``min_availability`` or ``max_cost_rate``) in each draw: all + True with none. + regret : numpy.ndarray + Each draw's regret: the choice's score less the best score among + the plans that meet the target (NaN where none does; negative + where the choice misses the target but scores better). + share_best : float or None + The share of draws in which the choice is the best plan that + meets the target. With ``"reoptimise"``, the share in which each + draw's own best intervals are the choice: None without + ``allowed``, whose continuous search never lands on the same + intervals twice. + share_best_by_candidate : list + For ``"neighbours"``, the share of draws in which each candidate + is the best (ties to the earliest); empty with ``"reoptimise"``. + share_meets_target : float + The share of draws in which the choice meets the target. + expected_regret : float + The mean regret over the draws that have one. + draw_choices : list or None + With ``"reoptimise"``, each draw's own best intervals; None + otherwise. + n_draws : int + The number of draws. + band : str or None + What the draws are (see ``UncertaintyResult``): ``"confidence"``, + ``"credible"``, ``"given"`` or ``"mixed"``. + held_fixed : list + The models every draw keeps as they are, as for + ``NPVUncertainty``: their uncertainty is not counted. + """ + + method: str + candidates: List[Dict[Hashable, float]] + scores: np.ndarray + meets_target: np.ndarray + regret: np.ndarray + share_best: Optional[float] + share_best_by_candidate: List[float] + share_meets_target: float + expected_regret: float + draw_choices: Optional[List[Dict[Hashable, float]]] + n_draws: int + band: Optional[str] + held_fixed: List[Dict[str, Any]] + + def __repr__(self) -> str: + best = "None" if self.share_best is None else f"{self.share_best:.3g}" + return ( + f"PlanRobustness(method={self.method!r}, " + f"candidates={len(self.candidates)}, share_best={best}, " + f"expected_regret={self.expected_regret:.6g}, " + f"share_meets_target={self.share_meets_target:.3g}, " + f"n_draws={self.n_draws})" + ) @dataclass @@ -2867,6 +3550,11 @@ class AvailabilityResult(_ResultMapping): uptimes : numpy.ndarray, optional The system's up time in each simulation, in order (they sum to ``system_uptime``); None in a result built without them. + unplanned_downtimes : numpy.ndarray, optional + The system's unplanned downtime in each simulation, in the order + of ``uptimes`` (see ``system_unplanned_downtime``); None for a + diagram that takes no planned outage (all its downtime is + unplanned) or a result built without them. antithetic : bool Whether the simulations ran in antithetic pairs (simulations ``2i`` and ``2i + 1``; see ``RepairableRBD.availability``), by default @@ -2900,9 +3588,18 @@ class AvailabilityResult(_ResultMapping): availability's): ``delivered_fraction`` is then that exact value. None otherwise. opportunistic_renewals : dict, optional - With maintenance groups (see ``RepairableRBD``): each component's - early renewals at another's stop, summed over the simulations. - None without groups. + With maintenance groups, or shutdowns that renew components + opportunistically (see ``RepairableRBD``): each component's early + renewals at another's stop or at a shut, summed over the + simulations. None without either. + outage_jobs : list, optional + With shutdowns that renew components opportunistically: for each + start of such a shut in the window, in order, a dict of its + ``"shutdown"``, its ``"start"``, the ``"mean"`` number of + components renewed there per simulation, its ``"standard_error"`` + and a 95% interval (``"lower"``, ``"upper"``: the mean less and + plus 1.96 standard errors, the lower no less than 0). None + otherwise. control_variate : ControlVariate, optional The exact twin the run was controlled by (see [`ControlVariate`][repyability.ControlVariate]): by default the @@ -2994,12 +3691,14 @@ class AvailabilityResult(_ResultMapping): demand: Optional[float] = None delivered: Optional[np.ndarray] = None opportunistic_renewals: Optional[Dict[Hashable, int]] = None + outage_jobs: Optional[List[Dict[str, Any]]] = None control_variate: Optional[ControlVariate] = None conditional: Optional[ConditionalRun] = None delivered_control: Optional[ControlVariate] = None shutdowns: int = 0 system_planned_downtime: Optional[float] = None system_unplanned_downtime: Optional[float] = None + unplanned_downtimes: Optional[np.ndarray] = None @property def mean_capacity(self) -> Optional[float]: @@ -3948,7 +4647,8 @@ class PlanVsActual(_ResultMapping): discount_rate : float The continuous discount rate per unit time (0: undiscounted). value_rate : float - The value earned per unit time while the system works. + The value earned per unit time while the system works (NaN with + a ``value_schedule``). plan_npv : float The original plan's expected net present value over the horizon. revalued_npv : float @@ -4008,7 +4708,21 @@ class PlanVsActual(_ResultMapping): The original plan over the horizon, from its start. rest : ExpectedNPV or None The rest valued as of ``now`` (its own clock from 0), with no - acquisition cost; None if ``now`` is the horizon. + acquisition cost; None if ``now`` is the horizon. With a value + schedule or escalation, its own amounts are those from ``now``: + ``rest_cash_flows`` are them grown and discounted to the plan's + clock. + rate_basis : str + ``"nominal"`` or ``"real"``, as for ``ExpectedNPV``. + inflation : float or None + The continuous inflation per unit time real rates were made + nominal with; None when not given. + escalation : dict + Each stream's growth per unit time, as given (see + ``ExpectedNPV``); empty with none. + value_schedule : ValueSchedule or None + The value earned as steps, when given one (``value_rate`` is + then NaN); None for a single rate. """ now: float @@ -4038,6 +4752,10 @@ class PlanVsActual(_ResultMapping): derived_states: List[Hashable] plan: ExpectedNPV rest: Optional[ExpectedNPV] + rate_basis: str = "nominal" + inflation: Optional[float] = None + escalation: Dict[Hashable, float] = field(default_factory=dict) + value_schedule: Any = None def __repr__(self) -> str: return ( @@ -4132,6 +4850,15 @@ class CrewStates(_ResultMapping): (it has crews of its own); 1 for the input and output nodes. probabilities : numpy.ndarray Each state's long-run probability, adding up to 1. + call_out_rate : numpy.ndarray or None + With a call-out crew (``call_out``), the rate at which it is + called in each state: ``probabilities @ call_out_rate`` is its + call-outs per unit time in the long run. Zeros without one (None + for a result made without it). + call_out_engaged : numpy.ndarray or None + 1 in the states the call-out crew is engaged in, else 0: + ``probabilities @ call_out_engaged`` is the fraction of the time + it is engaged. Examples -------- @@ -4146,6 +4873,8 @@ class CrewStates(_ResultMapping): node_availability: Dict[Hashable, np.ndarray] probabilities: np.ndarray + call_out_rate: Optional[np.ndarray] = None + call_out_engaged: Optional[np.ndarray] = None def __repr__(self) -> str: # A summary (#235): the states' values are in the fields. @@ -4496,3 +5225,285 @@ def to_dict(self) -> dict: out = super().to_dict() out["cls"] = getattr(self.cls, "name", str(self.cls)) return out + + +@dataclass +class SimulatedSwitchTime(_ResultMapping): + """The best time to switch blocks of a system from one way of running + them to another, by simulation: returned by + [`RepairableRBD.best_switch_time`][repyability.RepairableRBD.best_switch_time]. + + In plain terms: the switching blocks run the first way until + ``switch_time`` and the second way after it, and the system earns the + first value rate per unit of time up before it and the second after. + Switching at 0 runs the second way from the start; switching at the + horizon never switches. Every candidate time is simulated from the + same seed, so the differences between them are much steadier than + the NPVs themselves; ``difference_interval`` says how sure the + best is better than either end. + + Attributes + ---------- + switch_time : float + The scanned switch time with the highest mean NPV, in ``[0, + horizon]``. + choice : str + ``"switch at once"``, ``"never switch"`` or ``"switch"`` (in + between). + npv : float + The mean NPV when switching at ``switch_time``. + never_switch_npv : float + The mean NPV of running the first way throughout. + switch_at_once_npv : float + The mean NPV of running the second way throughout. + gain : float + ``npv`` less the better of the two above (0 when an end is best). + samples : numpy.ndarray + Each run's NPV switching at ``switch_time``. + never_switch_samples : numpy.ndarray + Each run's NPV never switching (the same runs' random numbers). + switch_at_once_samples : numpy.ndarray + Each run's NPV switching at once. + times : list of float + Every switch time valued, in order: the scan from 0 to the + horizon and the finer one around its best. + npvs : list of float + The mean NPV at each of ``times``, to audit the answer (the NPV + need not have one peak). + horizon : float + The length of time valued. + discount_rate : float + The continuous discount rate per unit time. + value_rates : list of float + What the system earns per unit of time up before the switch, and + after. + n_simulations : int + The runs at each switch time. + seed : int + The seed every switch time's runs share. + engine : str + The engine that ran them. + rate_basis : str + ``"nominal"`` or ``"real"``, as for ``ExpectedNPV``. + inflation : float or None + The continuous inflation per unit time real rates were made + nominal with; None when not given. + 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 + choice: str + npv: float + never_switch_npv: float + switch_at_once_npv: float + gain: float + samples: np.ndarray + never_switch_samples: np.ndarray + switch_at_once_samples: np.ndarray + times: List[float] + npvs: List[float] + horizon: float + discount_rate: float + value_rates: List[float] + n_simulations: int + seed: Any + engine: str + 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 + ) -> ConfidenceInterval: + """A confidence interval for how much switching at + ``switch_time`` beats ``against`` on average: the mean of the + runs' differences ``+/- z * std / sqrt(n)``, the runs paired by + their random numbers. The best time is picked from the same runs, + so the interval leans a little in its favour; give more + ``mc_samples`` to narrow it. + + Parameters + ---------- + against : str, optional + ``"never switch"`` (the default) or ``"switch at once"``. + confidence : float, optional + The confidence level, strictly between 0 and 1, by default + 0.95. + + Returns + ------- + ConfidenceInterval + The mean difference, its bounds, standard error and the number + of runs. + + Raises + ------ + ValueError + If ``against`` or ``confidence`` is not as described. + """ + from repyability.utils import checks + + checks.one_of("against", against, ("never switch", "switch at once")) + if not 0.0 < confidence < 1.0: + raise ValueError("confidence must be between 0 and 1.") + other = ( + self.never_switch_samples + if against == "never switch" + else self.switch_at_once_samples + ) + difference = self.samples - other + estimate = float(difference.mean()) + se = montecarlo.standard_error(difference, False) + z = montecarlo.z_value(confidence) + return ConfidenceInterval( + estimate=estimate, + lower=estimate - z * se, + upper=estimate + z * se, + confidence=confidence, + standard_error=se, + n_samples=int(difference.size), + method="simulated", + ) + + def __repr__(self) -> str: + # A summary (#235): the runs are in the samples. + return ( + f"SimulatedSwitchTime(switch_time={self.switch_time:.6g}, " + f"choice={self.choice!r}, npv={self.npv:.6g}, " + f"never_switch_npv={self.never_switch_npv:.6g}, " + f"switch_at_once_npv={self.switch_at_once_npv:.6g}, " + f"n_simulations={self.n_simulations}, " + f"horizon={self.horizon:g})" + ) + + +@dataclass +class DowntimeDesign(_ResultMapping): + """One design of ``RepairableRBD.least_spend_for_downtime``'s search: + its levers, its spend, and its downtime over the horizon. + + Attributes + ---------- + copies : dict + The copies of each redundancy node, by node. + intervals : dict + Each interval node's task interval (None: as given), by node. + spend : float + What the levers cost beyond the diagram as given: the copies' + prices, and the change in the expected preventive cost over the + horizon. + estimate : float + The target downtime's risk measure: its quantile at the level, or + its tail mean. + bound : float + The estimate's upper confidence bound. + meets : bool + Whether the bound is at or under the limit. + planned : dict + The planned downtime, whichever is targeted: ``mean_hours`` and + ``bad_hours`` (the quantile at the level), and ``mean_cost`` and + ``bad_cost`` at the downtime's rate (None without one). + unplanned : dict + The unplanned downtime, in the same terms. + """ + + copies: Dict[Hashable, int] + intervals: Dict[Hashable, Optional[float]] + spend: float + estimate: float + bound: float + meets: bool + planned: Dict[str, Optional[float]] + unplanned: Dict[str, Optional[float]] + + +@dataclass +class DowntimeRiskResult(_ResultMapping): + """The least spend that keeps a bad run's downtime under a limit: + returned by ``RepairableRBD.least_spend_for_downtime``. + + Attributes + ---------- + horizon : float + The horizon. + limit : float + The limit on the target downtime. + level : float + The level of its risk measure (0.95: "95% sure"). + objective : str + ``"var"`` (the downtime's quantile at ``level``) or ``"cvar"`` + (the mean of the worst share beyond it). + measure : str + ``"hours"`` or ``"cost"``. + downtime : str + ``"all"`` (planned and unplanned) or ``"unplanned"``. + confidence : float + The level of the upper bound a design must keep under the limit. + bound_method : str + How the bound is found. + budget : float or None + The most the levers may cost, if given. + met : bool + Whether a design meets the limit. + design : DowntimeDesign + The cheapest design that meets it, or else the design with the + lowest bad-run downtime found. + frontier : list of DowntimeDesign + The search's designs in order: spend rising, the bad-run downtime + falling. + floor : str or None + When no design meets the limit, what stopped the levers: + ``"budget"``, ``"caps"``, ``"planned"`` (planned task downtime + no lever lowers), ``"lowest"`` (no lever given lowers it) or + ``"steps"``. + stopped : str or None + The same, in words, with the lowest downtime reached. + n_simulations : int + Each design's runs. + seed : int + Their seed (every design takes it). + engine : str + The engine asked for (``"auto"`` lets each design's run choose). + """ + + horizon: float + limit: float + level: float + objective: str + measure: str + downtime: str + confidence: float + bound_method: str + budget: Optional[float] + met: bool + design: DowntimeDesign + frontier: List[DowntimeDesign] + floor: Optional[str] + stopped: Optional[str] + n_simulations: int + seed: int + engine: str + + def __repr__(self) -> str: + what = "met" if self.met else f"not met ({self.floor})" + return ( + f"DowntimeRiskResult(limit {self.limit:g} {self.measure} at " + f"{self.level:g}: {what}; spend {self.design.spend:.6g}, " + f"estimate {self.design.estimate:.6g}, bound " + f"{self.design.bound:.6g}; {len(self.frontier)} designs)" + ) diff --git a/repyability/rbd/routes.py b/repyability/rbd/routes.py index 9cb62382..2cbe53b6 100644 --- a/repyability/rbd/routes.py +++ b/repyability/rbd/routes.py @@ -176,7 +176,7 @@ def model_route(model) -> Tuple[str, str]: from surpyval import Parametric from ._bayesian_life import PosteriorPredictive - from ._covariate_schedule import ScheduledLife + from ._covariate_schedule import ClockLife from .helper_classes import PerfectReliability, PerfectUnreliability from .joint_node import JointNode from .load_sharing_node import LoadSharingModel @@ -188,7 +188,7 @@ def model_route(model) -> Tuple[str, str]: if model is PerfectReliability or model is PerfectUnreliability: return EXACT, "a constant" - if isinstance(model, ScheduledLife): + if isinstance(model, ClockLife): return REFUSED, str(model._no_reliability()) if isinstance(model, (StandbyModel, LoadSharingModel)): if model.is_simulated: @@ -229,7 +229,7 @@ def mean_route(model) -> Tuple[str, str]: """How a node model's mean lifetime (its ``mean()``) is found: the route, and a phrase saying how, or the message its ``mean()`` would raise.""" from ._bayesian_life import PosteriorPredictive - from ._covariate_schedule import ScheduledLife + from ._covariate_schedule import ClockLife from .degrading_node import DegradingNode from .joint_node import JointNode from .load_sharing_node import LoadSharingModel @@ -238,7 +238,7 @@ def mean_route(model) -> Tuple[str, str]: from .repeated_node import RepeatedNode from .standby_node import StandbyModel - if isinstance(model, ScheduledLife): + if isinstance(model, ClockLife): return REFUSED, str(model._no_reliability("mean life")) if isinstance(model, NonRepairableRBD): message = refusal(model._require_lifetimes) diff --git a/repyability/rbd/serialisation.py b/repyability/rbd/serialisation.py index cf799b0b..c6a6669b 100644 --- a/repyability/rbd/serialisation.py +++ b/repyability/rbd/serialisation.py @@ -55,6 +55,7 @@ from repyability.rbd.repeated_node import PARALLEL, RepeatedNode from repyability.rbd.repeated_standby_node import RepeatedStandbyNode from repyability.rbd.standby_node import StandbyModel +from repyability.utils.checks import is_number #: Whether every model must load back as the class it is (see #: ``exactly``). @@ -171,11 +172,23 @@ def _serialise_model(model: Any) -> dict: ), } if isinstance(model, NonRepairable): - return { + out = { "kind": "non_repairable", "reliability": serialise_model(model.reliability), "time_to_replace": serialise_model(model.time_to_replace), } + # The prices at opportunities, where given (an Opportunity key + # saved by its name, which the policies match it by too). + if model.opportunity_cost is not None: + out["opportunity_cost"] = model.opportunity_cost + if model.job_duration is not None: + out["job_duration"] = model.job_duration + if model.opportunity_costs: + out["opportunity_costs"] = { + getattr(k, "name", k): v + for k, v in model.opportunity_costs.items() + } + return out if isinstance(model, RegressionNode): return {"kind": "regression_node", **model.to_dict()} if isinstance(as_node(model), JointNode): @@ -303,6 +316,9 @@ def deserialise_model(d: dict) -> Any: return NonRepairable( deserialise_model(d["reliability"]), deserialise_model(d["time_to_replace"]), + opportunity_cost=d.get("opportunity_cost"), + job_duration=d.get("job_duration"), + opportunity_costs=d.get("opportunity_costs"), ) if kind == "regression_node": return RegressionNode.from_dict(d) @@ -398,7 +414,11 @@ def _serialise_component(value) -> dict: if value.get("replace_after") is not None: out["replace_after"] = int(value["replace_after"]) if value.get("duty") is not None: - out["duty"] = float(value["duty"]) + duty = value["duty"] + # A share, or a duty plan that changes over time (its dict). + out["duty"] = ( + float(duty) if is_number(duty) else _duty_plan_dict(duty) + ) if value.get("covariates") is not None: from repyability.rbd._covariate_schedule import schedule_to_dict @@ -406,6 +426,28 @@ def _serialise_component(value) -> dict: for key in ("preventive", "inspection"): if value.get(key) is not None: out[key] = _serialise_schedule(value[key]) + if value.get("upgrade") is not None: + # An upgrade: its time, the new life and the capital cost. + upgrade = value["upgrade"] + out["upgrade"] = { + "at": float(upgrade["at"]), + "reliability": serialise_model(upgrade["reliability"]), + } + if upgrade.get("cost"): + out["upgrade"]["cost"] = float(upgrade["cost"]) + for key in ("salvage", "escalation", "retire_at"): + # The unit's own money: numbers (a salvage by age is a + # function, which is not saved). + own = value.get(key) + if own is None: + continue + if callable(own): + raise NotImplementedError( + f"Cannot save a {key!r} given as a function (a salvage " + "by age): save the diagram with the salvage as a " + "number, or without it, and give the function again." + ) + out[key] = float(own) if value.get("standby") is not None: # A standby group: numbers only. out["standby"] = { @@ -433,6 +475,9 @@ def _serialise_schedule(spec: dict) -> dict: out["shutdown"] = spec["shutdown"] if spec.get("older_than") is not None: out["older_than"] = float(spec["older_than"]) + elif spec.get("replace_at") is not None: + # Replaced at the times of a plan, in place of an interval. + out["replace_at"] = [float(t) for t in spec["replace_at"]] else: out["interval"] = float(spec["interval"]) if spec.get("basis") is not None: @@ -472,6 +517,8 @@ def _serialise_schedule(spec: dict) -> dict: "model": spec["restoration"]["model"], "q": float(spec["restoration"]["q"]), } + if spec.get("restore_to") is not None: + out["restore_to"] = float(spec["restore_to"]) if spec.get("replace_every") is not None: out["replace_every"] = int(spec["replace_every"]) cost = spec.get("replacement_cost") @@ -526,7 +573,16 @@ def _deserialise_component(d: dict) -> Any: if "replace_after" in d: out["replace_after"] = d["replace_after"] if "duty" in d: - out["duty"] = d["duty"] + duty = d["duty"] + if isinstance(duty, dict): + from repyability.schedule import DutySchedule + + duty = DutySchedule( + str(duty.get("unit", "hours")), + tuple(float(t) for t in duty["times"]), + tuple(float(x) for x in duty["shares"]), + ) + out["duty"] = duty if "covariates" in d: from repyability.rbd._covariate_schedule import ( schedule_from_dict, @@ -536,8 +592,16 @@ def _deserialise_component(d: dict) -> Any: for key in ("preventive", "inspection"): if key in d: out[key] = _deserialise_schedule(d[key]) + if "upgrade" in d: + out["upgrade"] = { + **d["upgrade"], + "reliability": deserialise_model(d["upgrade"]["reliability"]), + } if "standby" in d: out["standby"] = dict(d["standby"]) + for key in ("salvage", "escalation", "retire_at"): + if key in d: + out[key] = d[key] return out return deserialise_model(d) @@ -594,7 +658,7 @@ def _capacity_from_list(capacity_list): def _ccf_to_list(ccf_groups): - from repyability.rbd.ccf import MGL, AlphaFactor, BetaFactor + from repyability.rbd.ccf import MGL, AlphaFactor, BetaFactor, Shocks if not ccf_groups: return None @@ -610,6 +674,19 @@ def _ccf_to_list(ccf_groups): "alphas": list(group.model.alphas), "testing": group.model.testing, } + elif isinstance(group.model, Shocks): + out.append( + { + "members": list(group.members), + "model": { + "kind": "shocks", + "rate": group.model.rate, + "p": group.model.p, + "lethal_rate": group.model.lethal_rate, + }, + } + ) + continue else: raise NotImplementedError( f"Cannot serialise CCF model {type(group.model).__name__}." @@ -625,7 +702,13 @@ def _ccf_to_list(ccf_groups): def _ccf_from_list(ccf_list): - from repyability.rbd.ccf import MGL, AlphaFactor, BetaFactor, CCFGroup + from repyability.rbd.ccf import ( + MGL, + AlphaFactor, + BetaFactor, + CCFGroup, + Shocks, + ) if not ccf_list: return None @@ -634,8 +717,14 @@ def _ccf_from_list(ccf_list): model_dict = entry["model"] kind = model_dict["kind"] basis = model_dict.get("basis", "probability") - if kind == "beta_factor": - model: object = BetaFactor(model_dict["beta"], basis=basis) + if kind == "shocks": + model: object = Shocks( + model_dict["rate"], + model_dict["p"], + model_dict["lethal_rate"], + ) + elif kind == "beta_factor": + model = BetaFactor(model_dict["beta"], basis=basis) elif kind == "mgl": model = MGL( *model_dict["letters"], @@ -658,7 +747,9 @@ def _ccf_from_list(ccf_list): def rbd_to_dict(rbd: RBD) -> dict: """Serialise an RBD (NonRepairableRBD or RepairableRBD) to a dict.""" - args = rbd._init_args + # As given: a diagram with shock groups keeps them, not the causes + # it wrote into its structure. + args = getattr(rbd, "_given_args", rbd._init_args) out = { "repyability_version": __version__, "type": type(rbd).__name__, @@ -681,6 +772,10 @@ def rbd_to_dict(rbd: RBD) -> dict: out["downtime_cost_rate"] = args.get("downtime_cost_rate", 0.0) if args.get("repair_crews") is not None: out["repair_crews"] = int(args["repair_crews"]) + if getattr(rbd, "crew_cost_rate", 0.0): + out["crew_cost_rate"] = rbd.crew_cost_rate + if getattr(rbd, "call_out", None) is not None: + out["call_out"] = dict(rbd.call_out) if args.get("maintenance_groups"): # Each group's options, by name (a name may not be a JSON key). out["maintenance_groups"] = [ @@ -719,6 +814,9 @@ def _shutdown_spec(spec: dict) -> dict: out[key] = None if value is None else list(value) elif key == "idle_ageing": out[key] = bool(value) + elif key == "opportunistic" and isinstance(value, dict): + # By component, as pairs (a name may not be a JSON key). + out[key] = [[node, float(age)] for node, age in value.items()] elif value is not None: out[key] = float(value) return out @@ -755,7 +853,11 @@ def rbd_from_dict(d: dict) -> RBD: key: ( [_node_name(n) for n in value] if key == "scope" and value is not None - else value + else ( + {_node_name(n): age for n, age in value} + if key == "opportunistic" and isinstance(value, list) + else value + ) ) for key, value in e.items() if key != "shutdown" @@ -767,6 +869,8 @@ def rbd_from_dict(d: dict) -> RBD: components, downtime_cost_rate=d.get("downtime_cost_rate", 0.0), repair_crews=d.get("repair_crews"), + crew_cost_rate=d.get("crew_cost_rate", 0.0), + call_out=d.get("call_out"), maintenance_groups=groups or None, ccf_groups=_ccf_from_list(d.get("ccf_groups")), shutdowns=shutdowns or None, @@ -794,3 +898,21 @@ def rbd_to_json(rbd: RBD, **json_kwargs) -> str: def rbd_from_json(s: str) -> RBD: """Reconstruct an RBD from a JSON string.""" return rbd_from_dict(json.loads(s)) + + +def _duty_plan_dict(plan) -> dict: + """A duty plan that changes over time (a ``DutySchedule``, or its + dict) as JSON.""" + if isinstance(plan, dict): + unit, times, shares = ( + plan.get("unit", "hours"), + plan["times"], + plan["shares"], + ) + else: + unit, times, shares = plan.unit, plan.times, plan.shares + return { + "unit": str(unit), + "times": [float(t) for t in times], + "shares": [float(x) for x in shares], + } diff --git a/repyability/rbd/shocks.py b/repyability/rbd/shocks.py new file mode 100644 index 00000000..d6b8ae3d --- /dev/null +++ b/repyability/rbd/shocks.py @@ -0,0 +1,234 @@ +"""Shocks that fail some of a diagram's nodes, written out as nodes. + +A shock process strikes at a constant rate, whatever the age of what it +strikes, and each shock fails each of the members it reaches with a +probability (the binomial failure rate model of Vesely and of Atwood). +Shocks at rate ``rate`` that fail each of ``m`` members independently with +probability ``p`` are, by thinning the process, one independent cause for +each set of members: the cause that fails exactly a set of ``j`` of them +strikes at rate ``rate * p**j * (1 - p)**(m - j)``. A cause that has not +struck by ``t``, with probability ``exp(-its rate * t)``, is an +exponential component in series with every member it fails, so each is +drawn as one: a node after each of its members, the appearances after the +first naming the first (one component in several places). + +The members keep their own lives, of any kind and each its own, and their +own ages: the causes have no age. Every analysis of the diagram then +takes the shocks as it takes any repeated component. +""" + +from itertools import combinations +from typing import Any, Collection, Dict, Hashable, Iterable, List, Tuple + +import surpyval as surv + +from repyability.utils.checks import number_or_nan + +#: The most members a shock process may reach: it has a cause for each +#: set of them, ``2**m - 1``. +MAX_MEMBERS = 10 + + +def _rate(value, name: str) -> float: + number = number_or_nan(value) + if not 0.0 <= number < float("inf"): + raise ValueError( + f"{name} must be a finite number, 0 or more: shocks per unit of " + f"the diagram's time. Got {value!r}." + ) + return number + + +def checked(rate, p, lethal_rate) -> Tuple[float, float, float]: + """The rate, the probability and the lethal rate of a shock process, + as floats, or a ``ValueError`` saying what each must be.""" + rate = _rate(rate, "rate") + lethal_rate = _rate(lethal_rate, "lethal_rate") + chance = number_or_nan(p) + if not 0.0 < chance <= 1.0: + raise ValueError( + "p, the probability that a shock fails a member it reaches, " + f"must be a number above 0 and at most 1, got {p!r}." + ) + return rate, chance, lethal_rate + + +def causes( + members: tuple, rate: float, p: float, lethal_rate: float +) -> List[Tuple[tuple, float]]: + """A shock process's independent causes: each set of ``members`` a + shock can fail exactly (in their order, smaller sets first) with the + rate it strikes at, ``rate * p**j * (1 - p)**(m - j)`` for a set of + ``j`` of the ``m`` (plus ``lethal_rate`` for all of them); those of + rate 0 left out.""" + m = len(members) + out: List[Tuple[tuple, float]] = [] + for size in range(1, m + 1): + strikes = rate * p**size * (1.0 - p) ** (m - size) + if size == m: + strikes += lethal_rate + if strikes > 0.0: + out += [ + (struck, strikes) for struck in combinations(members, size) + ] + return out + + +def shock_nodes( + edges: Iterable[Tuple[Hashable, Hashable]], + nodes: Dict[Any, Any], + members: Collection[Hashable], + rate: float, + p: float = 1.0, + lethal_rate: float = 0.0, + name: Hashable = "shock", +) -> Tuple[List[Tuple[Hashable, Hashable]], Dict[Any, Any]]: + """A diagram's edges and nodes with a shock process written in. + + Shocks arrive at ``rate``, whatever the members' ages, and each fails + each of ``members`` independently with probability ``p`` (the binomial + failure rate model); shocks of a second kind, at ``lethal_rate``, fail + every member. The members keep their own lives (of any kind, and each + its own) for their other failures. The result is passed to + [`NonRepairableRBD`][repyability.NonRepairableRBD], whose every + analysis then takes the shocks, given each member's own age too + (``sf_given_state``): they have none. + + Each set of members that a shock can fail exactly is a cause of its + own, at rate ``rate * p**j * (1 - p)**(m - j)`` for a set of ``j`` of + the ``m`` members (plus ``lethal_rate`` for the set of all of them), + independent of the others. It is drawn as an exponential node after + each member it fails, one component in several places, named ``(name, + its members, the member it follows)``. The importance measures + therefore name each cause, and a member's own entry is that of its + own failures. + + Parameters + ---------- + edges : iterable of (node, node) + The diagram's edges. + nodes : dict + The diagram's nodes, as ``NonRepairableRBD`` takes them. + members : collection of hashable + The nodes the shocks reach: two or more, at most ten. + rate : float + Shocks per unit of time; 0 or more. + p : float, optional + The probability that a shock fails a member it reaches, in + (0, 1]. By default 1: every shock fails every member, which is + one exponential node in series with them. + lethal_rate : float, optional + Shocks per unit of time that fail every member; by default 0. + name : hashable, optional + The first item of the cause nodes' names, by default ``"shock"``: + give each process of a diagram its own. + + Returns + ------- + edges : list of (node, node) + nodes : dict + The diagram with the causes written in. The arguments are not + changed. + + Raises + ------ + ValueError + If a member is not a component of ``nodes`` (or repeats another + node), there are fewer than two members or more than ten, a member + is named twice, a rate is negative or not a number, ``p`` is not + in (0, 1], or a cause's name is already a node. + + Notes + ----- + The shocks are for a non-repairable diagram. In a ``RepairableRBD`` a + node in series is down and repaired as one component, where a shock + leaves each member it failed to be repaired on its own. + + Examples + -------- + Two pumps of different ages in parallel; a shock every 50,000 hours + on average fails each with probability 0.6: + + >>> import surpyval as surv + >>> from repyability import NonRepairableRBD, shock_nodes + >>> pump = surv.Weibull.from_params([8000, 2.5]) + >>> edges, nodes = shock_nodes( + ... [("s", "p1"), ("s", "p2"), ("p1", "t"), ("p2", "t")], + ... {"p1": pump, "p2": pump}, + ... members=["p1", "p2"], rate=2e-5, p=0.6, + ... ) + >>> rbd = NonRepairableRBD(edges, nodes) + >>> round(rbd.sf_given_state(2000, {"p1": 6000, "p2": 1000}), 5) + 0.95111 + """ + members = list(members) + nodes = dict(nodes) + edges = [(a, b) for a, b in edges] + if len(set(members)) != len(members): + raise ValueError(f"members names a node twice: {members!r}.") + if not 2 <= len(members) <= MAX_MEMBERS: + raise ValueError( + f"members must name 2 to {MAX_MEMBERS} nodes (a shock process " + "has a cause for each set of them), got " + f"{len(members)}. For a shock that fails one node, give the " + "node a life in series with it; for more members, shocks that " + "fail every member (p=1) are one exponential node in series " + "with them." + ) + for member in members: + if member not in nodes: + raise ValueError( + f"Member {member!r} is not one of the nodes given." + ) + if not hasattr(nodes[member], "sf"): + raise ValueError( + f"Member {member!r} repeats node {nodes[member]!r}: name " + "the node it repeats as the member, once." + ) + rate, chance, lethal_rate = checked(rate, p, lethal_rate) + struck_by = causes(tuple(members), rate, chance, lethal_rate) + for member in members: + after = [edge for edge in edges if edge[0] == member] + edges = [edge for edge in edges if edge[0] != member] + last = member + for struck, strikes in struck_by: + if member not in struck: + continue + node, first = (name, struck, member), (name, struck, struck[0]) + if node in nodes: + raise ValueError( + f"{node!r} is already a node: give this shock process " + "a name of its own (name=...)." + ) + nodes[node] = ( + surv.Exponential.from_params([strikes]) + if node == first + else first + ) + edges.append((last, node)) + last = node + edges += [(last, to) for _, to in after] + return edges, nodes + + +def shock_name(index: int, count: int) -> Hashable: + """The name of the ``index``-th of a diagram's ``count`` shock + groups, the first item of its cause nodes' names: ``"shock"`` for an + only group, else ``"shock 1"``, ``"shock 2"``, ...""" + return "shock" if count == 1 else f"shock {index + 1}" + + +def written_shocks(edges, nodes, groups) -> Tuple[list, dict]: + """The diagram's edges and nodes with each of ``groups`` (each a + ``CCFGroup`` of a ``Shocks`` model) written in by ``shock_nodes``.""" + for index, group in enumerate(groups): + edges, nodes = shock_nodes( + edges, + nodes, + group.members, + group.model.rate, + group.model.p, + group.model.lethal_rate, + name=shock_name(index, len(groups)), + ) + return list(edges), nodes diff --git a/repyability/rbd/value_schedule.py b/repyability/rbd/value_schedule.py new file mode 100644 index 00000000..c6605c30 --- /dev/null +++ b/repyability/rbd/value_schedule.py @@ -0,0 +1,6 @@ +"""``ValueSchedule`` lives in ``repyability.value``; this name is kept so +that code and saved objects that import it from here still find it.""" + +from repyability.value.value_schedule import ValueSchedule, value_of + +__all__ = ["ValueSchedule", "value_of"] diff --git a/repyability/repairable.py b/repyability/repairable.py index 43d349d5..f39926cc 100644 --- a/repyability/repairable.py +++ b/repyability/repairable.py @@ -230,7 +230,7 @@ class Repairable: - ``mcf(t, items=..., random_state=...)``: a simulation-estimated mean cumulative function (imperfect repair), e.g. a surpyval ``GeneralizedRenewal`` (Kijima I/II) model, fitted or built with - ``fit_from_parameters``. + ``from_params``. If both are present ``cif`` is used (analytic, exact). For a simulation-backed model the failure-count methods @@ -275,7 +275,7 @@ class Repairable: >>> import surpyval as surv >>> from surpyval.recurrent import GeneralizedRenewal - >>> grp = GeneralizedRenewal.fit_from_parameters( + >>> grp = GeneralizedRenewal.from_params( ... [100.0, 2.0], 0.5, kijima="i", dist=surv.Weibull ... ) >>> unit = Repairable(grp) @@ -773,7 +773,7 @@ def find_optimal_overhaul_interval( >>> import surpyval as surv >>> from surpyval.recurrent import GeneralizedRenewal - >>> grp = GeneralizedRenewal.fit_from_parameters( + >>> grp = GeneralizedRenewal.from_params( ... [100.0, 2.0], 1.0, kijima="i", dist=surv.Weibull ... ) >>> unit = Repairable(grp) @@ -1011,7 +1011,7 @@ def expected_time_to_nth_failure( >>> from surpyval.recurrent import GeneralizedRenewal >>> from repyability import Repairable >>> from repyability import minimal_repair_time_to_nth_failure - >>> grp = GeneralizedRenewal.fit_from_parameters( + >>> grp = GeneralizedRenewal.from_params( ... [100.0, 2.0], 1.0, kijima="i", dist=surv.Weibull ... ) >>> unit = Repairable(grp) @@ -1108,7 +1108,7 @@ def find_optimal_replacement_failure_count( >>> import surpyval as surv >>> from surpyval.recurrent import GeneralizedRenewal >>> from repyability import Repairable - >>> grp = GeneralizedRenewal.fit_from_parameters( + >>> grp = GeneralizedRenewal.from_params( ... [100.0, 2.0], 0.4, kijima="i", dist=surv.Weibull ... ) >>> unit = Repairable(grp) @@ -1167,7 +1167,7 @@ def optimal_failure_limit_policy( >>> import surpyval as surv >>> from surpyval.recurrent import GeneralizedRenewal >>> from repyability import Repairable - >>> grp = GeneralizedRenewal.fit_from_parameters( + >>> grp = GeneralizedRenewal.from_params( ... [100.0, 2.0], 0.4, kijima="i", dist=surv.Weibull ... ) >>> unit = Repairable(grp) @@ -1274,22 +1274,55 @@ def optimal_overhaul_replace_policy( overhaul_factor: float, replacement_cost: float, max_cycles: int = _cycles.DEFAULT_MAX_CYCLES, + max_failures: int = _DEFAULT_MAX_FAILURES, ) -> OverhaulReplacePolicy: - """The best overhaul interval and number of periods between - replacements. - - For each number of periods ``K`` from 1 to ``max_cycles`` the - interval that minimises the long-run cost rate of - [`overhaul_replace_cost_rate`][repyability.Repairable.overhaul_replace_cost_rate] - is found (a grid search, then a bounded refinement), and the best - ``K`` is kept (the fewer on a tie). The cost rate need not fall - steadily with ``K``: it can have a local minimum at a few periods - and a slightly lower value much further out, so read the result - with ``max_cycles`` in mind (compare a few limits). A result with - ``cycles`` equal - to ``max_cycles`` may mean more periods would pay: raise the - limit. ``interval`` is ``inf`` when the unit does not wear out, so - that neither overhauls nor replacements pay. + """The cheapest way to repair, overhaul and replace a wearing unit. + + In plain words: four plans are priced, each at its own best + setting, and the cheapest is returned with the others beside it. + + - ``"overhaul and replace"``: overhaul every ``interval`` and + replace after ``cycles`` periods (2 to ``max_cycles``), as + [`overhaul_replace_cost_rate`][repyability.Repairable.overhaul_replace_cost_rate] + prices it; + - ``"overhaul only"``: overhaul every ``interval`` and never + replace (``cycles`` is ``inf``); + - ``"replace only"``: replace every ``interval``, with no + overhauls (``cycles`` is 1); + - ``"failure limit"``: no overhauls; repair the first failures and + replace at the ``failure_count``-th (up to ``max_failures``), + at ``replacement_cost``. + + An overhaul that keeps part of the unit's age lets the age build + up to a ceiling, so a replacement does not always pay: often the + unit is best overhauled for ever, and often best replaced at a + failure count. The result's ``plan`` names the winner, + ``alternatives`` holds every plan's cost rate and settings, and + ``saving`` is how much less per unit time the winner costs than the + next best. + + Formally, failures are a non-homogeneous Poisson process with + cumulative intensity ``L(a)``, and an overhaul keeps the share + ``f`` of the age. Never replacing, the age at the start of a period + settles at ``v* = f T / (1 - f)``, where an overhaul takes off what + the period added, so the long-run cost rate is ``g_inf(T) = (cr * + [L(v* + T) - L(v*)] + co) / T``, the limit of ``g(T, K)`` as ``K`` + grows. The failure limit's is ``(cr (n - 1) + replacement_cost) / + E[T_n]``, with ``E[T_n]`` exact (see + ``optimal_failure_limit_policy``, which prices the replacement at + ``co``). Each interval is found by a grid search and a bounded + refinement; for ``"overhaul and replace"`` the best ``K`` is kept + (the fewer on a tie). Its rate need not fall steadily with ``K``; + ``cycles_limit_reached`` says the best ``K`` was ``max_cycles``, so + more periods might pay (they tend towards ``"overhaul only"``, + which is priced anyway). A ``failure_count`` equal to + ``max_failures`` may likewise mean a higher count pays. A unit that + does not wear out is run to failure: ``plan`` is ``"run to + failure"``, ``interval`` is ``inf`` and ``cycles`` 1. + + On a tie the plan earlier in the list ``"replace only"``, + ``"overhaul and replace"``, ``"overhaul only"``, ``"failure + limit"`` wins. Parameters ---------- @@ -1300,36 +1333,55 @@ def optimal_overhaul_replace_policy( The cost of replacing the unit. max_cycles : int, optional The most periods per replacement cycle searched (default 20). + max_failures : int, optional + The highest failure count searched for the failure limit + (default 30). Returns ------- OverhaulReplacePolicy - The ``interval``, ``cycles`` and ``cost_rate``. + The winning ``plan`` with its ``interval``, ``cycles``, + ``failure_count`` and ``cost_rate``, plus ``alternatives``, + ``saving`` and ``cycles_limit_reached``. Raises ------ ValueError, NotImplementedError As for - [`overhaul_replace_cost_rate`][repyability.Repairable.overhaul_replace_cost_rate]. + [`overhaul_replace_cost_rate`][repyability.Repairable.overhaul_replace_cost_rate]; + ``ValueError`` also for a ``max_failures`` below 1. Examples -------- A wearing-out unit (failures grow with the 2.5th power of its age), - repaired for 1, overhauled for 5, and replaced for 20; an overhaul - takes off 40% of its age: + repaired for 1, overhauled for 5, and replaced for 20. An overhaul + that takes off only 10% of its age does little, so replacing pays, + and the cheapest way is to replace at the 13th failure: >>> from surpyval.recurrent import CrowAMSAA >>> from repyability import Repairable >>> unit = Repairable(CrowAMSAA.from_params([100.0, 2.5])) >>> unit.set_repair_and_overhaul_costs(cr=1.0, co=5.0) + >>> policy = unit.optimal_overhaul_replace_policy( + ... 0.9, 20.0, max_cycles=5 + ... ) + >>> policy.plan, policy.failure_count, round(policy.cost_rate, 4) + ('failure limit', 13, 0.1158) + >>> round(policy.alternatives["replace only"]["cost_rate"], 4) + 0.1183 + + An overhaul that takes off 40% of the age holds it at a ceiling, + so the unit is best overhauled every 73.8 and never replaced, + saving 0.0028 per unit time on the next best plan: + >>> policy = unit.optimal_overhaul_replace_policy( ... 0.6, 20.0, max_cycles=5 ... ) - >>> policy.cycles, round(policy.interval, 1) - (2, 177.7) - >>> round(policy.cost_rate, 4) - 0.1172 + >>> policy.plan, policy.cycles, round(policy.interval, 1) + ('overhaul only', inf, 73.8) + >>> round(policy.cost_rate, 4), round(policy.saving, 4) + (0.1129, 0.0028) """ return _cycles.optimal_policy( - self, overhaul_factor, replacement_cost, max_cycles + self, overhaul_factor, replacement_cost, max_cycles, max_failures ) diff --git a/repyability/schedule/README.md b/repyability/schedule/README.md index 9a37e23f..6ff12aa9 100644 --- a/repyability/schedule/README.md +++ b/repyability/schedule/README.md @@ -21,6 +21,24 @@ moved out with the calendar side in October 2026, and return here under their own numbers with the answers recorded for them. The use cases in model time (UC-1, UC-5 to UC-27) stay in `repyability/maintenance/README.md`. +## Layers + +This module is the calendar layer (`CLAUDE.md`, Architecture). It turns +dates into model time and back, and it says what each unit's duty is. +It leaves money to `repyability.value`, a unit's plan to +`repyability.maintenance` and the system to `RepairableRBD`: + +| Question | Where | Use cases | +|---|---|---| +| Which dates does a rule give? | `Recurrence` (its `dates`) | UC-2, UC-3, UC-4 | +| How many operating hours by when? | `DutyPlan`, `UsageForecast` | UC-10 | +| The calendar an analysis runs on, and each unit's duty plan | `CalendarContext` (taken by `events_by_period` and by `UnitPlan`'s methods as `calendar=`) | UC-64 | +| A part's failures and costs by month | `failures_by_period` (a `NonRepairable`), or `UnitPlan.failures_by_period` (the diagram's engine) | UC-48 | +| A system's events and costs by month | `events_by_period` (a `RepairableRBD`) | UC-39, UC-64 | + +The duty plan belongs to the analysis: the same diagram or plan runs on +another site's calendar with other plans. + ## Conventions - **Dates are whole local dates** (a `datetime.date`, or ISO text such as @@ -40,6 +58,18 @@ model time (UC-1, UC-5 to UC-27) stay in `repyability/maintenance/README.md`. - **Results are plain data** (`_ResultMapping`s with `to_dict()`, dates as ISO text); rules and tasks have `to_dict()` and `from_dict()` with a `"kind"` and a `"version"`. +- **`discount=` is the effective yearly rate** (0.07 is 7% a year), the + one convention of the dated replacement policies + (`repyability.maintenance`): an amount `y` years after the date it is + discounted to is worth `(1 + discount)^(-y)`, a year being 365.25 + days; the continuous rate a year is `ln(1 + discount)`. Money is + discounted to the forecast's first date (the caller's "today"). Every + present value here goes through `_discount.py`, whose arithmetic is + the money module's (`repyability.value`): the one convention of + RePyability, continuous discounting at a rate per unit of the clock + the money falls on, with a yearly rate converted to it there and + nowhere else. With no `discount` nothing is discounted and every result is + as it was. ## The use cases, by number @@ -53,6 +83,13 @@ model time (UC-1, UC-5 to UC-27) stay in `repyability/maintenance/README.md`. | UC-29 | The first, or the fifth, Saturday of each month, and the months without one | **Built**: `Recurrence.monthly(nth=)`, `Recurrence.notes` | | UC-30 | Two limits, whichever comes first, and a task waiting for the crew's visit | **Built**: `Task(also=, visits=, tolerance=, last_done=)` | | UC-31 | The work in each month: how many tasks, hours and cost | **Built**: `work_by_period` | +| UC-47 | $250 every 30 days at 7% a year: what is it worth this year, and for ever? | **Built**: `Task.due(discount=)`, `work_by_period(discount=)`, `Task.long_run_value` | +| UC-48 | The wear ring's expected failure costs by month, as present values | **Built**: `failures_by_period(discount=)` (to a stated precision; a window, not the long run) | +| 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 | | UC-34 | About 3 h a day, or 2 to 4: when are the 250-hour inspections? | **Built**: `Rate`, ranges | @@ -62,7 +99,7 @@ model time (UC-1, UC-5 to UC-27) stay in `repyability/maintenance/README.md`. | UC-38 | The wear ring on the weekday pump: expected failures and cost by month, and the range | **Built**: `failures_by_period` | | UC-39 | A system's events by calendar month | **Built**: `events_by_period` | | UC-40 | Shuts on dates as opportunities on the part's clock | **Built**: `Opportunity.from_recurrence` | -| UC-41 | The annual overhaul on the first Tuesday of November, as a diagram's shutdown | **Built**: `shutdown_spec` (simulated; the exact methods take shuts on a period) | +| UC-41 | The annual overhaul on the first Tuesday of November, as a diagram's shutdown | **Built**: `shutdown_spec` (worked out over a horizon where the blocks worked on are renewed, and simulated; no long run) | | UC-43 | A site's shuts on real dates, one record for policies and diagrams | **Built** in `repyability.maintenance` (`Shutdowns`; its README's UC-43), laid on the part's clock through this module's rules, plans and forecasts | | UC-42 | Starts per operating hour for a life on two clocks | **Built**: `UsageForecast.life_at_usage` (needs surpyval 0.28) | @@ -260,6 +297,71 @@ model time (UC-1, UC-5 to UC-27) stay in `repyability/maintenance/README.md`. - **Checks:** the counts above; the periods add up to each task's whole; the periods cover the dates asked with no gap. +### UC-47: "I have a $250 task every 30 days from today. At 7% a year, what is it worth this year, and if it goes on for ever?" + +- **Status:** built: `Task.due(start, end, discount=)` (`TaskDue.npv`, + `eac`), `work_by_period(..., discount=)` (`WorkByPeriod.npv`, + `total_npv`, `eac`) and `Task.long_run_value(start, discount)` + returning a `LongRunValue`. +- **Who asks:** the owner of a maintenance budget comparing a recurring + task with a one-off spend (a modification that removes the task), who + has the NPV of replacement policies in model time and asks whether the + scheduled work ties into it. +- **What they know:** the task, its rule and its cost each time; today's + date (20 November 2026 here); the yearly discount rate. +- **The answer, by hand:** from 20 November 2026 to 19 November 2027 the + task is done on days 0, 30, 60, ..., 360: **13 times, $3,250**. Each is + worth `250 / 1.07^(days / 365.25)` today: 250.00, 248.61, 247.24, + 245.87, 244.50, 243.15, 241.80, 240.46, 239.13, 237.80, 236.49, 235.18 + and 233.87, **$3,144.10** in all. By quarter (the first and last cut to + the dates): 2, 3, 3, 3 and 2 tasks; $498.61, $737.61, $725.41, $713.42 + and $469.05. Repeating for ever it is a geometric sum, `250 / (1 - + 1.07^(-30 / 365.25))` = `250 / 0.0055417` = **$45,112**. The equivalent + annual cost of the perpetuity is `45,112 × ln(1.07)` = $3,052 a year + (a little more than 12.175 tasks a year at $250, $3,044, because each + interval's task is paid at its start). +- **How it is solved:** the dates a task is done on are known, so a + period's present value is a finite sum, each cost discounted from the + date the task is done (after its visit), in the period it is counted + in. For ever: a plain interval of days or weeks (no second limit, + visits, season or excluded dates) repeats exactly from the second time + it is done, so the first is discounted on its own and the rest are the + geometric sum above (`method="closed form"`). Any other task (the first + Tuesday of the month, every 3 months, a task waiting for visits, two + limits) is summed date by date (`method="summed"`): a task is done at + most once a day, so the dates after day `T` are worth less than `cost × + v^(T+1) / (1 - v)` with `v = 1.07^(-1 / 365.25)`, and the sum stops + where that bound is under `precision` (1e-9 by default) of what is + summed, reporting the bound. At 7% that is some 360 years of dates. The + first Tuesday of every month at $250 is worth **$44,350.51** (12 a + year, the first on 1 December). +- **Decisions (defaults):** + - `discount` is the yearly effective rate, discounted to `start`. + - `eac` is the steady cost **a year** over the period (both dates + included) worth the present value, as the dated policies' `eac`; at a + discount of 0 it is the cost over the period's years. + - Tasks with no cost stay named in `no_cost`, and a note says the + present values leave them out; a task with no cost has no `npv`. + - **Refused, saying what to run:** a long-run value at `discount=0` + (the costs add up without end); a task on given dates, or done at + visits on given dates (they end: `due` to the last date is the whole + value); a limit by use (`Usage` follows a usage forecast, which + ends); a rate so low that the sum does not settle to `precision` by + the year 9999, where dates stop (under about 0.3% a year at 1e-9). + - A date far from a rule's anchor is now found without walking to it + from the anchor (`Recurrence._counted_from`): the same dates, in a + time that no longer grows with the distance. +- **Checks:** `test_uc47_thirty_day_task_this_year_and_for_ever` (the + numbers above to the cent), `test_long_run_against_100000_dates`, + `test_a_pattern_for_ever_against_2000_years_of_dates` (the first + Tuesdays worked out without `Recurrence`), + `test_no_discount_leaves_results_as_they_were`, + `test_discount_of_zero_is_the_plain_total`, + `test_periods_present_values_add_up`, + `test_long_run_with_visits_and_overdue`, + `test_what_has_no_long_run_value_is_refused` and + `test_far_dates_are_the_anchors_own`. + ## Duty plans and the date ↔ usage map These use cases are answered by `DutyPlan`, `UsageForecast` and the @@ -479,6 +581,361 @@ in `test_schedule_forecast.py`. `test_cost_by_month_is_exact_on_average`, `test_uc1_diagram_by_calendar_month_sums_to_the_year`. +### UC-48: "What are the wear ring's expected failure costs worth today, month by month?" + +- **Status:** built: `failures_by_period(..., discount=, npv_tolerance=)` + (`FailuresByPeriod.expected_npv`, `npv`, `npv_precision`, `eac`). +- **Who asks:** UC-38's planner, whose budget is in present values. +- **What they know:** UC-38's ring and pump; 7% a year. +- **The answer, by hand:** UC-38's months cost $105, $227, $217, $214, + $252, $247, $239, $252, $253, $252, $250, $236 and $244, $2,988 in + all. A month's cost falls somewhere inside it, so it is worth at most + its cost discounted from the month's start and at least from its end + (the months end 0.041, 0.126, 0.211, 0.287, 0.372, 0.455, 0.539, + 0.622, 0.706, 0.791, 0.873, 0.958 and 1.040 years on): **between + $2,874.75 and $2,890.71**, so $2,882.73 give or take $7.98. Each + failure's cost discounted from when it is expected to fall (the + integral below), the value is **$2,882.74**, to within $0.016 at the + default tolerance (and $2,882.741 to within $0.0007 at + `npv_tolerance=1e-5`); by month $104.40, $226.20, $214.53, $210.05, + $246.83, $239.74, $230.71, $242.24, $241.48, $239.51, $236.52, + $222.18 and $228.36. The equivalent annual cost over the 1.04 years + is $2,869.51. (Until #604, short windows each discounted at their + middle gave $2,882.77 give or take $2.47, and an EAC of $2,869.53.) +- **How it is solved:** an expected cost accrues as the part runs, so + discounting it needs the dates inside each period. With `C(s)` the + expected cost by the calendar time `s` (the part's expected cost to + the operating time the duty plan has run by `s`), the present value + to `T` is `exp(-r T) C(T) + r ∫ exp(-r s) C(s) ds`, each cost + discounted from when it is expected to fall. It is the diagram's own + discounting (`_common._discounted_accrual`, the one design of an + accrued cost's present value): the integral by the Gauss-Kronrod (7, + 15) rule on pieces from the start (32 equal ones, cut again at the + periods' ends), the pieces whose two rules differ most halved until + the differences, times `r`, are within `npv_tolerance` of the value. + `npv_precision` is that error estimate plus what the error of `C` + itself can move the value: run to failure, `failures`' count is + worked out at a grid's points and taken linearly between them, off + by at most an eighth of the grid's largest second difference, and at + most that times `exp(-r T) + |1 - exp(-r T)|` in the present value. + `C` comes from `failures` run to failure, and from `cost_by_window`'s means under a policy + (every policy it takes, with no new renewal maths). Days with no + running add nothing. +- **Decisions (defaults):** + - `npv_tolerance` is 1e-3 (ten cents in a hundred dollars). The + rules' difference is a cautious estimate: the ring's value at 1e-3 + is within $0.002 of the one at 1e-5. A duty plan's shifts bend `C` + at every start and stop, which the halving closes in on; at most + 60 rounds are worked out, and a forecast that falls short of the + tolerance says so in its notes, with what it reached. + - The ranges (5th to 95th percentile) stay undiscounted, and the notes + say so: a discounted distribution of a part's cost is a later item. + - At `discount=0` the present values are the expected costs + themselves, with a precision of 0. + - A part with no cost has no present value (a note); a part whose + replacement takes time (run to failure with `NonRepairable.failures`) + is discounted the same way from `failures`' expected counts. + - A window only: the value of the part for ever on dates is not built + (see below). +- **Checks:** `test_uc48_wear_ring_present_value_by_month` (the numbers + above, inside the hand bracket by month), + `test_constant_rate_in_calendar_time_against_the_closed_form` (rate × + cost × the integral of the discount factor, inside the bracket), + `test_the_bracket_narrows_and_holds_a_simulation` (tolerances from 5e-3 to 1e-4; + 400,000 seeded rings on the duty plan, within four standard errors + and the bracket), `test_nothing_accrues_while_idle`, + `test_a_policy_as_a_present_value`, + `test_a_part_with_no_cost_has_no_present_value`, + `test_a_forecast_short_of_the_tolerance_says_so`. + +### UC-49: "And the system's expected costs, month by month, as present values?" + +- **Status:** built: `events_by_period(..., cost=True, discount=)` + (`EventsByPeriod.expected_npv`, `npv`, `eac`). +- **Who asks:** UC-39's planner. +- **What they know:** UC-39's pump (a failure per 2,000 h on average, + repaired at once), $1,000 a repair; the months of 2027; 7% a year. +- **The answer, by hand:** costs come at $0.50 an hour, so a span to `T` + hours is worth `0.5 × (1 - e^(-r T)) / r` with `r = ln(1.07) / 8,766` + an hour: January (744 h) **$370.93**, to the end of February (1,416 h) + $704.15, so February $333.21, and the year (8,760 h) **$4,235.21** + against $4,380 undiscounted. The equivalent annual cost is $4,383 a + year of 365.25 days: the cost rate itself, as it should be for costs + at a constant rate. +- **How it is solved:** a diagram's clock is calendar time, so the + yearly rate is one continuous rate per unit of it (`ln(1 + discount)` + over the units in a year of 365.25 days), which + `RepairableRBD.expected_cost(t, discount_rate=)` takes: each period's + present value is its difference at the period's ends. Exact, as + `expected_cost` is, with each event discounted at its own time (a + block replacement at its instant, not the middle of a month). +- **Decisions (defaults):** `discount=` needs `cost=True` (refused + otherwise, saying so); the range stays undiscounted (a diagram's + discounted spread is `npv_distribution`'s, in model time); an + acquisition cost, paid at the start, is not in the periods, as it is + not in `cost_by_window`'s. +- **Checks:** `test_uc49_constant_rate_by_month_as_present_values`, + `test_events_present_value_is_expected_npvs_cost`, + `test_events_discount_needs_cost`. + +### UC-50: "Is replacing the wear ring at every 6-monthly service worth it, at 7% a year?" + +- **Status:** built: `task_value(task, Replaces(part), usage, age=, + discount=, period=)` returning a `TaskValue`. +- **Who asks:** UC-48's planner, who has the ring's failure costs as + present values and a task that costs money each time: does the task pay + for itself? +- **What they know:** UC-38's ring (Weibull, scale 9,000 operating hours, + shape 2.5), 5,200 h old on Monday 16 November 2026, $4,800 when it + fails; the pump of UC-32 (Mon–Fri 06:00–22:00, forecast to 1 December + 2027); the 6-monthly service (`Recurrence.every(6, "months", + "2026-12-01")`), at which a new ring costs $600; 7% a year. +- **The answer, by hand:** the service is done on 1 December 2026 and 1 + June 2027 (1 December 2027 is the forecast's end, not in it). At + midnight those are **176 h and 2,256 h** of running from the start + (UC-32's months), and the forecast is 4,352 h. *With the task* the ring + is new at each, whatever its age, and a failure in between is replaced + too without moving the dates: the old ring runs 176 h from 5,200 h + (renewal count 0.02178), a new one 2,080 h (0.02541) and another 2,096 + h (0.02590), **0.0731 failures, $350.82**, and two planned rings, + $1,200: **$1,550.82**. *Without the task* (run to failure from the same + age over the same dates) it is UC-38's **0.6224 failures, $2,987.56**. + The task saves **$1,436.74** and avoids **0.549 failures**. By month, + with the task: 0.0218 failures in November (the old ring's 176 h), then + 0.0003, 0.0014, 0.0026, 0.0050, 0.0070 and 0.0090 (the new ring ageing), + 0.0003 again in June, ... At 7% a year, the planned rings are worth + $600 × 1.07^(-15/365.25) + $600 × 1.07^(-197/365.25) = $598.34 + + $578.50 = **$1,176.83**. Each month's failure cost discounted at its + start and at its end brackets the rest, as in UC-48: with the task the + failures are worth $339.39 to $341.00, so **$1,516.22 to $1,517.84** in + all; without, UC-48's **$2,874.75 to $2,890.71**; the task's present + value is **between $1,356.92 and $1,374.49**. The service pays, mostly + by putting a new ring in for an old one at once. +- **How it is solved:** the task's dates come from `Task.due` over the + forecast; each is done at midnight of its date (a limit by use: when the + meter reaches its reading), which `usage.model_time` puts on the part's + clock. Between two of them the ring is a renewal process from new (from + `age` before the first), so its expected failures to any time are a + sum of `NonRepairable.failures` over the stretches (its renewal + count, to about 1e-6; no new renewal maths). Without the task they are `failures` from `age`. Each + side's failure cost is discounted as UC-48's (from when it is + expected to fall, the integral's error estimate the precision); a + planned replacement is discounted from its own instant. + `value = without − with`, by period and in all. +- **Decisions (defaults):** + - **Block replacement on dates:** a failure between two services does + not move the next; the task's dates are its own (`Task.due`, with its + visits, second limit and `resets`). + - **"Without" is run to failure** from the same age over the same + dates, not the best other policy (`NonRepairable.renewal_forecast` + and the optimal policies answer that in model time). + - **One price:** the task's `cost` is the planned ring's. A task with + no cost takes the part's `planned_cost`; given both, they must agree, + or it refuses naming the two numbers. The part needs an + `unplanned_cost` (without it the task saves nothing to set against its + cost). + - 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 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 + months on a duty plan are not. The stretches between the dates say + it for any dates. +- **Checks:** `test_uc50_wear_ring_six_monthly_service` (the numbers + above, inside the hand bracket by month), + `test_even_dates_match_renewal_forecast` (a discount of 0 against + `renewal_forecast`'s plan and run-to-failure costs), + `test_constant_rate_task_only_costs` (exponential: the value is minus + the task's own present value), `test_wear_out_against_a_simulation` + (both plans simulated from a seed, within four standard errors), + `test_periods_add_up`, `test_one_price`, + `test_what_is_not_a_replacement_is_refused`, + `test_a_task_by_use_matches_block_replacement_in_model_time`. + +### UC-54: "Is the 6-monthly trip test worth it, at 7% a year?" + +- **Status:** built: `task_value(task, Finds(device, demand_rate=, + consequence_cost=, repair_cost=), usage, age=, discount=, period=)` + returning a `TaskValue`. +- **Who asks:** UC-50's planner, about a task that replaces nothing: a + test of a protective device (a trip, a relief valve, a standby pump's + start). A test prevents no failure; what it is worth is the time the + device would otherwise sit failed with nobody knowing. +- **What they know:** a trip failing hidden at a constant 0.1 a year, + working on Monday 16 November 2026; a test on 1 January and 1 July + (`Recurrence.every(6, "months", "2027-01-01")`), $400 each; a failure + repaired as new for $3,000; the protected event once in 2 years (0.5 a + year), which costs $250,000 if it meets the trip failed and shows the + failure, repaired then; three years, to 16 November 2029; 7% a year. +- **The answer, by hand:** the trip's life is in calendar time, so its + clock is the calendar's: the six tests are 46, 227, 411, 593, 777 and + 958 days from the start (0.126, 0.621, 1.125, 1.624, 2.127 and 2.623 + years), and the forecast 1,096 days (3.0007 years). As UC-53 of the + maintenance README: from a test (or the start) the chance the trip is + failed after `s` years is `0.1 / 0.6 (1 - exp(-0.6 s))`. *With the + task* the tests find it failed with chances 0.0121, 0.0429, 0.0435, + 0.0431, 0.0435 and 0.0429 (**0.2279 failures found**); it is failed + for 0.0640 years (a mean unavailability of **0.0213**), so **0.0320 + demands** meet it failed: tests $2,400, repairs $3,000 x (0.2279 + + 0.0320) = $779.60, consequences $250,000 x 0.0320 = $7,995.30: + **$11,174.90**. *Without the task* (never tested; a failure stays + until a demand shows it) it is failed for 0.2682 years (**0.0894**), + **0.1341 demands** meet it failed: $253,000 x 0.1341 = **$33,931.58**. + The tests save **$22,756.68**. At 7% a year (the calendar's clock is + the trip's, so the closed form discounts exactly, at `ln 1.07` a + year): the tests are worth $400 x sum 1.07^(-t) = $2,190.54, with the + task **$10,087.23**, without **$29,936.76**: the task's present value + is **$19,849.53**. +- **How it is solved:** the task's dates come from `Task.due` and are + laid on the device's clock as UC-50's are. With them as the tests' + times, the device's chance of being failed over time is UC-53's + (`maintenance._finding_window`), from `age`, working at the start; + without the task it is the same with no tests. Each side's demands on + a failed device accrue with the device's operating time (the demand + rate times the failed time), so they go by period and are discounted + exactly as UC-50's failures are (`_accrued_npv`'s integral, its error + estimate in `precision`, with the grid's own error); + a test's cost and the repair of what it finds are discounted from the + instant the task is done. `value = without - with`. The result is + UC-50's `TaskValue`: its "failures" are the demands that meet the + device failed, and it adds `found` (the failures the tests find) and + `unavailability_with` and `unavailability_without` (the device's mean + unavailability in each period, and over the forecast in `total`). +- **Decisions (defaults):** + - **A demand that meets the device failed shows the failure**, which + is repaired then at `repair_cost`, with the task and without it + (`demands_reveal=False` on `Finds` turns it off on both sides: only + a test finds a failure, as `failure_finding` has it, and never + tested a failure is for good). + - **Tests and repairs take no time and a test never misses**, as + `failure_finding` assumes. + - **The caller gives the demand rate and the consequence's cost**; a + `Task` does not carry them, and a diagram's system-level consequence + is not worked out here. The demand rate is per unit of the device's + own time, so demands come only while it runs. + - The task's `cost` is one test's; a task with no cost is refused + (0.0 for a free test). The device's own costs are not used. + - Tests at one time on the device's clock (two dates with no running + between them) are one test of the device: each costs, and the first + finds what there is to find. + - "Without" is never tested, not the best other interval + (`optimal_failure_finding_interval` answers that in the long run). +- **Checks** (`test_schedule_finds.py`): + `test_uc54_six_monthly_trip_test` (the numbers above, undiscounted to + 1e-9 and discounted within `precision`), + `test_only_tests_find_a_failure`, + `test_matches_the_model_time_calculation` (a Weibull device 1,000 h + old tested every 30 days against `failure_finding_window`, with and + without a discount), `test_uneven_dates_under_a_duty_plan` (the first + Tuesday of each month on a pump on weekday shifts, against the closed + form on the pump's clock, each day's cost discounted at its start and + its end by hand), `test_tests_while_the_device_does_not_run`, + `test_the_value_follows_the_prices` (rising with the consequence, + 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, @@ -510,10 +967,11 @@ in `test_schedule_forecast.py`. Sydney the first is the same 8,478 h: both ends are in daylight saving. - **How it is solved:** as UC-40, on the diagram's clock (calendar time), as the shutdown's `"times"`. -- **Not built:** the exact methods (`expected_events`, `expected_cost`, - and so `events_by_period`) take shuts on a period only; a diagram with - shuts at given times is simulated (`cost()`, `availability()`), and - `events_by_period` refuses it with the diagram's own message. +- **Over a horizon:** `expected_events`, `expected_cost` and + `expected_npv` (and so `events_by_period`) take shuts at given times + where the blocks worked on in them are renewed; the simulations + (`cost()`, `availability()`) take any. They end, so the long-run + methods refuse such a diagram with a message that says so. - **Checks:** `test_uc41_shutdown_spec_on_dates`, `test_uc41_a_diagram_takes_the_dated_shuts` (two shuts in two years, $40,000, simulated). @@ -534,19 +992,89 @@ in `test_schedule_forecast.py`. model); `test_uc42_with_surpyval_equivalence`, skipped before surpyval 0.28 (run by hand against surpyval's `dev`: it passes). +### UC-64: "Our line has two pumps in parallel: one runs weekday shifts, the other around the clock. The first has its seal changed every 4,000 running hours, the second at a check on the first Monday of each quarter. What failures, services and costs come each month?" + +- **Status:** built: `CalendarContext(usage, duty={node: forecast or + share}, unit=)`, taken by `events_by_period`; a block's `"duty"` + takes a share or a `DutySchedule` (`UsageForecast.schedule()`); a + task on a rule is replaced at `CalendarContext.rule_times(rule, at)` + (its `"replace_at"`). +- **Who asks:** UC-39's planner, whose pumps do not run alike: one on + Monday to Friday 06:00 to 22:00 (80 h a week), one 24/7. +- **What they know:** one diagram (the two pumps, each life in operating + hours, Weibull scale 3,000 h and shape 2, repairs of about 8 h); the + shift pump's 4-hour seal change every 4,000 operating hours, the 24/7 + pump's at the check on the first Monday of each quarter (06:00); each + pump's duty plan; the months of 2027. +- **The answer, by hand:** each pump runs its own clock `D(t)`, the + operating hours from 1 January to `t`. The shift pump runs 4,176 h in + 2027 and reaches 4,000 h at the end of the shift on **Thursday 16 + December, 22:00** (`usage.moment(4000)`), so its one seal change falls + in December (the plan's hours, whatever repairs the pump has: the + service is on the plan). The 24/7 pump's seal + is changed on **4 January, 5 April, 5 July and 4 October** at 06:00 + (the rule's dates). With repairs in no time, a pump is its operating-time + process seen through `D`: its expected failures by `t` are `M(D(t))`, + `M` the renewal count (with its block service) in operating time, from + the one-node diagram with no duty; the simulation on the calendar + agrees within its error (`test_a_unit_is_its_operating_process_seen_through_its_plan`). +- **How it is solved:** the engine always runs on calendar time. The + analysis, not the plan, says each unit's duty: `CalendarContext.diagram` + gives each node its plan as its `"duty"`. A plan of one share is the + constant share it always was (the model rescaled, exact). A plan that + changes is a life on the diagram's clock (`_duty.PlannedLife`): a unit + put in at `t0` fails at `D⁻¹(D(t0) + L)`, `L` drawn from the model's own + quantile function in operating hours, and a task counted in operating + time falls when `D` reaches it (`_Preventive.clock`). Its reliability + from new, `R(D(t))`, is the model's own `sf`; a unit put in later has + another, so it is no renewal process, and the Python simulation counts + it (the compiled engine hands it over). `events_by_period` then counts + each month's events in the histories and takes the cost's mean and + range from the same runs, each cost discounted from when it falls. +- **Decisions (defaults):** a plan belongs to the analysis + (`CalendarContext.duty`), not to the unit's plan; a task in operating + time on a block with no duty counts the diagram's clock as its + operating time (as a model without a calendar runs from 0); a plan + holds its last share past its end (the calendar refuses a forecast + that ends first); on a plan that changes, a unit starts new (a state + other than new, a virtual age, replacement on condition, tests counted + in operating time and standby groups are refused, saying so). +- **Checks:** `test_duty_plans.py`: a plan of one share is the duty share + to the bit; the simulation against `M(D(t))` for run to failure, block + and age replacement; a usage task's dates equal the forecast's + `moment`s; a rule's dates; saving; the refusals. A rule as a spec of + its own (resolved by the calendar) is not built: the diagram must + stand without a calendar, and a rule's dates need one. + ### What is not built yet +- **A part's expected failure costs for ever, on dates.** + `failures_by_period(discount=)` values a forecast's window. "The dated + window, then the discounted long run" (as `maintenance/_dated.py` does + 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`). +- **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; + the long run beyond it is not joined to it (as for the part's own + failure costs above). +- **Discounted ranges.** The 5th to 95th percentiles stay undiscounted. - **Utilisation as whole runs lost.** `utilisation=0.9` counts each planned hour and start as 0.9, an expected value. The dates when 90% of runs go ahead (the nth run to go ahead follows a negative binomial) are not worked out yet. -- **A duty that changes inside a `RepairableRBD`.** `schedule()` gives - the duty as steps over calendar time, for that later work; today a - block takes one average share, `duty()`. -- **Shuts at given times in the exact methods.** `shutdown_spec` puts - dated shuts on a diagram, which the simulations take; the exact - `expected_events` and `expected_cost` (and so `events_by_period`) take - shuts on a period only. +- **Exact values on a duty plan that changes.** A unit on such a plan + is simulated (UC-64). Where its repairs and tasks take no time it is + its operating-time process seen through `D`, so its exact curves could + be the operating-time ones at `D(t)`; not built yet. Nor are tests + counted in operating time on such a plan, or a start other than new. ## Candidates diff --git a/repyability/schedule/__init__.py b/repyability/schedule/__init__.py index f950f872..3f3245eb 100644 --- a/repyability/schedule/__init__.py +++ b/repyability/schedule/__init__.py @@ -23,11 +23,19 @@ map (the existing model-time methods, labelled with dates); ``shutdown_spec`` puts shuts on dates on a diagram, and ``Opportunity.from_recurrence`` lays them on a part's model time. +- ``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; 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. """ +from repyability.schedule._calendar import CalendarContext from repyability.schedule._duty import ( Continuous, DutyPlan, @@ -49,6 +57,7 @@ Season, ) from repyability.schedule._task import ( + LongRunValue, Task, TaskDue, WorkByPeriod, @@ -64,8 +73,17 @@ UsageDue, UsageForecast, ) +from repyability.schedule._value import ( + Condition, + Finds, + Replaces, + Services, + TaskValue, + task_value, +) __all__ = [ + "CalendarContext", "Continuous", "Crossing", "DutyPlan", @@ -87,9 +105,16 @@ "Season", "Task", "TaskDue", + "LongRunValue", + "Condition", + "Finds", + "Replaces", + "Services", + "TaskValue", "WorkByPeriod", "work_by_period", "events_by_period", "failures_by_period", "shutdown_spec", + "task_value", ] diff --git a/repyability/schedule/_calendar.py b/repyability/schedule/_calendar.py new file mode 100644 index 00000000..6266bef0 --- /dev/null +++ b/repyability/schedule/_calendar.py @@ -0,0 +1,246 @@ +"""The calendar an analysis runs on: when it starts, at which site, to +when, and each unit's duty plan (how many operating hours by when). + +A diagram's clock is calendar time from the calendar's start. Each unit +whose life is in operating time reaches it through its own duty plan +``D(t)``, the operating time from the start to ``t``: its life on the +calendar is ``R(D(t))``, a unit put into service at ``t0`` failing when +``D`` has run its operating life on from ``D(t0)``, and a task counted in +operating time falls when ``D`` reaches it. A plan that runs one share of +the time throughout is the block's ``"duty"`` share, worked out exactly; a +plan that changes (weekday shifts, a season) is followed by the +simulations. The duty plans belong to the analysis, not to the units' +plans: the same diagram runs on another site's calendar with other plans. +""" + +from dataclasses import dataclass, field +from datetime import datetime +from typing import Any, Dict, Mapping, Optional + +import numpy as np + +from repyability.utils.checks import is_number, one_of + +from ._meters import UNITS +from ._usage import DutySchedule, UsageForecast + + +@dataclass(frozen=True) +class CalendarContext: + """The calendar an analysis runs on (see the module's notes). + + Parameters + ---------- + usage : UsageForecast + The calendar's frame: its start ("now", the diagram's 0), end, + time zone and periods + (``UsageForecast.calendar(start, end)`` for one with no plan of + its own). + duty : mapping, optional + Node -> its duty plan: a ``UsageForecast`` from the same start to + at least the same end (``DutyPlan(...).forecast(...)``), or a + share of the time in (0, 1]. A node left out keeps its spec's + ``"duty"``, if any. + unit : str, optional + The unit of the diagram's models (``"hours"``, the default, + ``"days"``, ...): of its clock and of each life in operating time. + + Examples + -------- + >>> from repyability.schedule import CalendarContext, DutyPlan, Shifts + >>> from repyability.schedule import UsageForecast + >>> frame = UsageForecast.calendar("2027-01-04", "2027-01-11") + >>> shifts = DutyPlan(Shifts("Mon-Fri", "06:00", "22:00")).forecast( + ... "2027-01-04", "2027-01-11" + ... ) + >>> plan = CalendarContext(frame, {"pump": shifts}).duty_plan("pump") + >>> plan.times[:3], plan.shares[:3] + ((0.0, 6.0, 22.0), (0.0, 1.0, 0.0)) + """ + + usage: UsageForecast + duty: Mapping[Any, Any] = field(default_factory=dict) + unit: str = "hours" + + def __post_init__(self) -> None: + if not isinstance(self.usage, UsageForecast): + raise TypeError( + "usage must be a UsageForecast (DutyPlan(...).forecast(...), " + "or UsageForecast.calendar(start, end) with no plan); got " + f"{self.usage!r}." + ) + one_of("unit", self.unit, tuple(UNITS)) + if not isinstance(self.duty, Mapping): + raise TypeError( + "duty must map each node to its duty plan (a " + "UsageForecast, or a share of the time); got " + f"{self.duty!r}." + ) + object.__setattr__(self, "duty", dict(self.duty)) + for node in self.duty: + self.duty_plan(node) # checked where it is given + + # -- each unit's plan --------------------------------------------------- + + def duty_plan(self, node) -> Any: + """Node ``node``'s duty as a block's ``"duty"`` takes it: a share + of the time, or the steps of its forecast over the diagram's clock + (a ``DutySchedule`` in the calendar's unit); None for a node the + calendar gives no plan. + + Parameters + ---------- + node : hashable + The diagram's node, as named in ``duty``. + """ + if node not in self.duty: + return None + given = self.duty[node] + if is_number(given): + return float(given) + if not isinstance(given, UsageForecast): + raise TypeError( + f"The duty plan of node {node!r} must be a UsageForecast " + "(DutyPlan(...).forecast(start, end)) or a share of the " + f"time; got {given!r}." + ) + if given.start != self.usage.start: + raise ValueError( + f"The duty plan of node {node!r} starts at {given.start}, " + f"and the calendar at {self.usage.start}: forecast it from " + "the calendar's start." + ) + if given.end < self.usage.end: + raise ValueError( + f"The duty plan of node {node!r} ends at {given.end}, " + f"before the calendar does ({self.usage.end}): forecast it " + "to the calendar's end at least." + ) + steps = given.schedule(self.unit) + if len(set(steps.shares)) == 1: + return float(steps.shares[0]) + return steps + + def model_time(self, moments) -> np.ndarray: + """The diagram's clock at each moment: real time since the + calendar's start, in its unit. + + Parameters + ---------- + moments : str, datetime or sequence of them + The moments, as the calendar's ``UsageForecast`` reads them + (local to its time zone). + """ + usage = self.usage + given = [moments] if isinstance(moments, (str, datetime)) else moments + seconds = np.array( + [usage._seconds(m) - usage._start_s for m in given], dtype=float + ) + return seconds / 3600.0 / UNITS[self.unit] + + def rule_times(self, rule, at=None) -> np.ndarray: + """A recurrence rule's dates within the calendar, each at the clock + time ``at`` (midnight by default), on the diagram's clock: those + after its start (a task due at the start itself is due now, and + is not taken as done): a ``"preventive"`` spec's ``"replace_at"`` + for a task on the rule. + + Parameters + ---------- + rule : Recurrence + The recurrence rule whose dates are taken. + at : str or time, optional + The clock time on each date (``"06:00"``); midnight by default. + + Examples + -------- + >>> from repyability.schedule import CalendarContext, Recurrence + >>> from repyability.schedule import UsageForecast + >>> frame = UsageForecast.calendar("2027-01-01", "2028-01-01") + >>> quarterly = Recurrence.monthly( + ... weekday="Monday", nth=1, every=3, anchor="2027-01-01" + ... ) + >>> CalendarContext(frame, unit="days").rule_times(quarterly).tolist() + [3.0, 94.0, 185.0, 276.0] + """ + from ._forecast import _instants, _rule + + usage = self.usage + dates = _rule(rule).dates(usage.start.date(), usage.end.date()) + times = self.model_time(_instants(dates, usage._clock, at)) + end = self.model_time([usage.end])[0] + return times[(times > 0.0) & (times <= end)] + + # -- the diagram on it ---------------------------------------------------- + + def diagram(self, rbd): + """``rbd`` (a ``RepairableRBD``) on this calendar: each node the + calendar gives a plan has it as its ``"duty"``. The diagram + itself when the calendar gives no plan. + + Parameters + ---------- + rbd : RepairableRBD + The diagram, each node the calendar's ``duty`` names a unit + with a life (a spec or a ``UnitPlan``). + """ + from repyability.rbd.repairable_rbd import RepairableRBD + + components = dict(rbd._init_args["components"]) + changed = False + for node, spec in list(components.items()): + as_spec = getattr(spec, "spec", None) + if callable(as_spec) and not isinstance(spec, dict): + spec = as_spec() + if not isinstance(spec, dict): + if node in self.duty: + raise ValueError( + f"The calendar gives node {node!r} a duty plan, " + "and it is not a unit with a life (a spec or a " + "UnitPlan): leave it out of the calendar's duty." + ) + continue + plan = self.duty_plan(node) + if plan is not None: + spec = {**spec, "duty": plan} + changed = True + components[node] = spec + for node in self.duty: + if node not in components: + raise ValueError( + f"The calendar gives node {node!r} a duty plan, and " + f"the diagram has no node {node!r}." + ) + if not changed: + return rbd + return RepairableRBD(**{**rbd._init_args, "components": components}) + + # -- saving -------------------------------------------------------------- + + def to_dict(self) -> Dict[str, Any]: + """The calendar as plain data: its frame, each node's plan (a + share, or its steps on the diagram's clock) and its unit.""" + plans: Dict[str, Any] = {} + for node in self.duty: + plan = self.duty_plan(node) + plans[str(node)] = ( + plan if isinstance(plan, float) else _steps_dict(plan) + ) + return { + "usage": self.usage.to_dict(), + "duty": plans, + "unit": self.unit, + } + + +def _steps_dict(plan: DutySchedule) -> Dict[str, Any]: + return { + "unit": plan.unit, + "times": list(plan.times), + "shares": list(plan.shares), + } + + +def calendar_of(usage) -> Optional[CalendarContext]: + """``usage`` if it is a ``CalendarContext``, else None.""" + return usage if isinstance(usage, CalendarContext) else None diff --git a/repyability/schedule/_discount.py b/repyability/schedule/_discount.py new file mode 100644 index 00000000..75a575ea --- /dev/null +++ b/repyability/schedule/_discount.py @@ -0,0 +1,57 @@ +"""Money on dates at a yearly discount rate, for every schedule result that +gives a present value. + +``discount`` is the **effective yearly rate** (0.07 is 7% a year), as in +the dated replacement policies (``repyability.maintenance``): an amount +``y`` years after the date it is discounted to is worth ``(1 + +discount) ** -y`` of itself, a year being 365.25 days. The arithmetic +(``factor``, ``per_unit``, ``equivalent_annual``, ``perpetuity``, +``net`` and the conversion of a yearly rate to a +continuous one) is ``repyability.value``'s, the one convention for every +present value in RePyability; it is imported here under the names the +schedule module has always used. What is the schedule's own is the +wording of a discounted result (``percent``, ``words``). +""" + +from __future__ import annotations + +from typing import Optional + +from repyability.value._rates import ( # noqa: F401 + DAYS_A_YEAR, + HOURS_A_YEAR, + continuous, + equivalent_annual, + factor, + factor_on, + net, + per_unit, + perpetuity, + yearly, + years_from, +) + + +def percent(discount: float) -> str: + """The yearly rate in words: ``7%``, ``2.5%``.""" + from repyability.maintenance._shutdowns import _percent + + return _percent(discount) + + +def words(discount: Optional[float], start, escalation=None) -> str: + """The note every discounted result carries (``discount`` given).""" + assert discount is not None + day = start.date() if hasattr(start, "date") else start + out = f"Discounted to {day} at {percent(discount)} a year." + if escalation is not None: + overall_rate = net(discount, escalation) + assert overall_rate is not None + overall = percent(overall_rate) + out += ( + f" The costs escalate at {percent(escalation)} a year from " + "their prices today: each present value is the cost grown to " + f"when it falls and discounted, a net {overall} a year; the " + "costs by period are at today's prices." + ) + return out diff --git a/repyability/schedule/_forecast.py b/repyability/schedule/_forecast.py index a68549d9..f2372337 100644 --- a/repyability/schedule/_forecast.py +++ b/repyability/schedule/_forecast.py @@ -24,12 +24,13 @@ from dataclasses import dataclass from datetime import datetime -from typing import Any, Dict, List, Optional, Tuple +from typing import Any, Callable, Dict, List, Optional, Tuple import numpy as np from repyability.utils.checks import is_number +from . import _discount from ._meters import UNITS, Clock, clock, time_unit from ._recurrence import Recurrence, _period from ._usage import UsageForecast, _Plain @@ -39,6 +40,11 @@ RANGE_LEVELS = (5.0, 95.0) RANGE_WORDS = "the 5th to 95th percentile (90% of outcomes, two-sided)" +#: How close a part's present value is worked out by default: the +#: quadrature's error estimate, as a share of it. +NPV_TOLERANCE = 1e-3 +_YEAR_SECONDS = 3600.0 * _discount.HOURS_A_YEAR + # ------------------------------------------------------------ helpers @@ -109,6 +115,89 @@ def _period_edges(usage: UsageForecast, period: str): return found, seconds +def _tolerance(value) -> float: + if not (is_number(value) and 0.0 < float(value) < 1.0): + raise ValueError( + "npv_tolerance must be a share of the present value, more " + f"than 0 and less than 1 (such as 1e-4); got {value!r}." + ) + return float(value) + + +def _accrued_npv( + usage: UsageForecast, + seconds: np.ndarray, + unit: str, + discount: float, + tolerance: float, + costs: Callable[[np.ndarray], np.ndarray], + notes: List[str], + cost_error: float = 0.0, +): + """The present value, in each period and in all, of a part's expected + cost, which accrues as it runs: ``(by period, total, precision)``. + + ``costs(ends)`` is the expected cost in each of the consecutive + windows of operating time ending at ``ends`` (increasing, from 0), + so ``C(s)``, the expected cost by the calendar time ``s``, is their + sum to the operating time the duty plan has run by ``s``. Its + present value is the diagram's (``_common._discounted_accrual``): + ``exp(-r T) C(T) + r * integral_0^T exp(-r s) C(s) ds``, each cost + discounted from when it is expected to fall, the integral taken by + the Gauss-Kronrod rule on pieces halved until its error estimate is + within ``tolerance`` of the value. The precision is that estimate + plus what ``cost_error`` (a bound on how far ``C`` itself may be from + the true expected cost, anywhere in the forecast) can move the value: + ``cost_error * (exp(-r T) + |1 - exp(-r T)|)``. + """ + from repyability.rbd._common import ( + _DISCOUNT_ROUNDS, + _discount_pieces, + _discounted_accrual, + ) + + scale = usage._unit(unit) + base = usage._at_s("hours", usage._start_s) + rate = _discount.continuous(discount) + ends = np.asarray(seconds, float) / _YEAR_SECONDS + + def accrued(years: np.ndarray) -> np.ndarray: + """``C`` at ``years`` from the start, as one row.""" + model = usage._at_s("hours", usage._start_s + years * _YEAR_SECONDS) + model = np.maximum((model - base) / scale, 0.0) + knots, where = np.unique(model, return_inverse=True) + moving = knots > 0.0 + cumulative = np.zeros(knots.size) + if moving.any(): + cumulative[moving] = np.cumsum(costs(knots[moving])) + return cumulative[np.ravel(where)][None, :] + + present, precision = _discounted_accrual( + accrued, ends, rate, _discount_pieces(ends, float(ends[-1])), tolerance + ) + by_period = np.diff(present[0], prepend=0.0) + # A period with no running accrues nothing: exactly 0, not what its + # ends' values leave over in rounding. + running = np.diff( + usage._at_s("hours", usage._start_s + np.asarray(seconds, float)), + prepend=base, + ) + by_period[running <= 0.0] = 0.0 + total = float(present[0, -1]) + # The expected cost's own error, discounted: at most cost_error at T + # and in the integral, whose weights r exp(-r s) add up to 1 - exp(-r T). + shrink = float(np.exp(-rate * ends[-1])) + precision += cost_error * (shrink + abs(1.0 - shrink)) + if precision > tolerance * abs(total): + notes.append( + f"The present value is within {precision:.3g} of the true one " + f"({precision / total:.2g} of it), short of npv_tolerance=" + f"{tolerance:g}: {_DISCOUNT_ROUNDS} rounds of halving is the " + "most worked out." + ) + return by_period, total, precision + + def _instants(days, clock_: Clock, at) -> List[datetime]: """Each date at the clock time ``at`` (midnight by default), as a real instant at the site.""" @@ -161,7 +250,9 @@ class FailuresByPeriod(_Plain): The expected planned replacements in each period (None when run to failure). expected_cost : numpy.ndarray or None - The expected cost in each period; None for a part with no cost. + The expected cost in each period, as it falls (not discounted, + with a discount too: the present values are ``expected_npv``); + None for a part with no cost. cost_low, cost_high : numpy.ndarray or None Each period's cost range: its 5th and 95th percentiles (90% of outcomes, two-sided). @@ -176,6 +267,23 @@ class FailuresByPeriod(_Plain): What the ranges are, in words. notes : tuple of str What the forecast assumed. + discount : float or None + The yearly discount rate given; None when none was. + expected_npv : numpy.ndarray or None + With a discount: what each period's expected cost is worth at the + forecast's start, the cost discounted from when it is expected to + fall inside the period (``total`` then has ``"expected_npv"`` and + ``"npv_precision"`` too). The ranges are not discounted. + npv : float or None + The periods' ``expected_npv`` summed: the forecast's expected + cost as a present value. + npv_precision : float or None + How far the true ``npv`` can be from the one given: the error + estimate of the integral its expected cost is discounted by (0 + at a discount of 0). + eac : float or None + The equivalent annual cost: the steady cost a year over the + forecast worth ``npv``. """ period: str @@ -199,6 +307,11 @@ class FailuresByPeriod(_Plain): total: Dict[str, Any] range: str notes: Tuple[str, ...] + discount: Optional[float] = None + expected_npv: Optional[np.ndarray] = None + npv: Optional[float] = None + npv_precision: Optional[float] = None + eac: Optional[float] = None def __repr__(self) -> str: cost = ( @@ -232,6 +345,9 @@ def failures_by_period( resets: Optional[bool] = None, since_renewal: Optional[float] = None, calendar=None, + discount: Optional[float] = None, + escalation: Optional[float] = None, + npv_tolerance: float = NPV_TOLERANCE, ) -> FailuresByPeriod: """A part's expected failures, their cost and its range in each calendar period, through the map between dates and operating time. @@ -275,6 +391,26 @@ def failures_by_period( times count from the forecast's start ([`Opportunity.from_recurrence`][repyability.Opportunity.from_recurrence] lays dated shuts there). + discount : float, optional + A yearly discount rate (0.07 for 7% a year): the result then has + each period's ``expected_npv``, the expected cost as a present + value at the forecast's start, with ``npv``, ``npv_precision`` + and ``eac``. An expected cost accrues as the part runs, and each + part of it is discounted from when it is expected to fall: an + integral over the forecast, whose error estimate is + ``npv_precision``. The ranges stay undiscounted. By default None: + no present values. + escalation : float, optional + With ``discount``, the effective yearly rate every cost + escalates at from its price today (0.03 for 3% a year): the + present values (and ``eac``) take each cost grown to when it + falls, at the net yearly rate ``(1 + discount) / (1 + escalation) + - 1``. By default None: today's prices. + npv_tolerance : float, optional + How close the present value is worked out: the integral's pieces + are halved until ``npv_precision`` is within this share of + ``npv`` (the notes say when it falls short); by default 1e-3, + ten cents in a hundred dollars. Returns ------- @@ -311,6 +447,9 @@ def failures_by_period( 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) found = usage.by_period(period) ends = np.atleast_1d(usage.model_time(list(found.ends), unit=unit)) ends = np.maximum.accumulate(np.maximum(ends, 0.0)) @@ -421,6 +560,70 @@ def failures_by_period( ) if low is not None: notes.append(f"Ranges are {RANGE_WORDS}.") + expected_npv = npv = npv_precision = eac = None + if discount is not None and cost is None: + notes.append( + "No present value: the part has no cost (give " "unplanned_cost=)." + ) + elif discount is not None: + _, seconds = _period_edges(usage, period) + if discount == 0.0 or total_end <= 0.0: + expected_npv = np.array(cost, float) + npv, npv_precision = float(total["expected_cost"] or 0.0), 0.0 + else: + # Run to failure, a window's expected cost is its expected + # failures' (failures' exact counts, which cost_by_window's + # distributions only repeat, at many times the work). + cost_error = 0.0 + if policy != "run to failure": + + def costs(model_ends: np.ndarray) -> np.ndarray: + return part.cost_by_window( + model_ends, + every, + resets=resets, + age=age, + since_renewal=since_renewal, + calendar=calendar, + levels=RANGE_LEVELS, + ).mean + + else: + + def costs(model_ends: np.ndarray) -> np.ndarray: + counts = part.failures(model_ends, age=age) + return part.cu * np.diff( + np.asarray(counts.expected_failures, float), + prepend=0.0, + ) + + # The counts are linear between their grid's points: how + # far that can be from the true count is in the precision. + cost_error = part.cu * part._failures_error(total_end, age) + + expected_npv, npv, npv_precision = _accrued_npv( + usage, + seconds, + unit, + discount, + npv_tolerance, + costs, + notes, + cost_error, + ) + eac = _discount.equivalent_annual( + npv, discount, float(seconds[-1]) / _YEAR_SECONDS + ) + total["expected_npv"] = npv + total["npv_precision"] = npv_precision + notes.append( + f"{_discount.words(given, usage.start, escalation)} The " + "present values (expected_npv, npv) discount the expected " + "cost from when it is expected to fall, to within " + f"{npv_precision:.3g} in all; expected_cost" + + (" and the ranges are" if low is not None else " is") + + " not discounted." + ) return FailuresByPeriod( period=period, starts=found.starts, @@ -443,6 +646,11 @@ def failures_by_period( total=total, range=RANGE_WORDS, notes=tuple(notes), + discount=given, + expected_npv=expected_npv, + npv=npv, + npv_precision=npv_precision, + eac=eac, ) @@ -471,10 +679,24 @@ class EventsByPeriod(_Plain): cost : CostByWindow or None [`RepairableRBD.cost_by_window`][repyability.RepairableRBD.cost_by_window]'s answer, with ``cost=True``: each period's exact mean, and its range - (5th to 95th percentile) simulated. + (5th to 95th percentile) simulated. Both are the costs as they + fall, not discounted, with a discount too: the present values are + ``expected_npv``. range : str or None What the cost range is, in words (None with no cost). notes : tuple of str + discount : float or None + The yearly discount rate given; None when none was. + expected_npv : numpy.ndarray or None + With a discount: what each period's expected cost is worth at the + forecast's start, each cost discounted from when it falls + ([`expected_cost`][repyability.RepairableRBD.expected_cost] with + its ``discount_rate``, exact). The range is not discounted. + npv : float or None + The periods' ``expected_npv`` summed. + eac : float or None + The equivalent annual cost: the steady cost a year over the + forecast worth ``npv``. """ period: str @@ -486,6 +708,10 @@ class EventsByPeriod(_Plain): cost: Any range: Optional[str] notes: Tuple[str, ...] + discount: Optional[float] = None + expected_npv: Optional[np.ndarray] = None + npv: Optional[float] = None + eac: Optional[float] = None def __repr__(self) -> str: return ( @@ -505,6 +731,8 @@ def events_by_period( cost: bool = False, mc_samples: Optional[int] = None, seed: Optional[int] = None, + discount: Optional[float] = None, + escalation: Optional[float] = None, ) -> EventsByPeriod: """A ``RepairableRBD``'s expected events, and on request its cost, in each calendar period. @@ -523,10 +751,17 @@ def events_by_period( Parameters ---------- rbd : RepairableRBD - usage : UsageForecast + usage : UsageForecast or CalendarContext Gives the periods, the site's time zone and "now" (its start); ``UsageForecast.calendar(start, end)`` when there is no plan. - ``usage.duty()`` is the share a block's ``"duty"`` takes. + A [`CalendarContext`][repyability.schedule.CalendarContext] also + gives each unit its duty plan (and its unit of time, and the dates + of tasks on a recurrence rule): a plan of one share is worked out + exactly, as a block's ``"duty"``; with a plan that changes over + time (weekday shifts), each unit's life is drawn in operating time + and put on the calendar by its plan, so the events are the means + of the simulations' histories, and the cost's means simulated + too. period : str, optional ``"day"``, ``"week"``, ``"month"`` (the default), ``"quarter"`` or ``"year"``. @@ -539,7 +774,23 @@ def events_by_period( cost : bool, optional Also the cost by period (simulated range), by default False. mc_samples, seed : optional - With ``cost=True``, the simulations, as for ``cost_by_window``. + With ``cost=True``, or a duty plan that changes over time, the + simulations, as for ``cost_by_window`` (1,000 by default). + discount : float, optional + With ``cost=True``, a yearly discount rate (0.07 for 7% a year): + the result then has each period's ``expected_npv``, its expected + cost as a present value at the forecast's start, with ``npv`` and + ``eac``. Exact: the diagram's clock is calendar time, so the + yearly rate is one continuous rate per unit of it, ``ln(1 + + discount)`` over the units in a year of 365.25 days, which + [`expected_cost`][repyability.RepairableRBD.expected_cost] takes + as its ``discount_rate``. By default None: no present values. + escalation : float, optional + With ``discount``, the effective yearly rate every cost + escalates at from its price today (0.03 for 3% a year): the + present values (and ``eac``) take each cost grown to when it + falls, at the net yearly rate ``(1 + discount) / (1 + escalation) + - 1``. By default None: today's prices. Returns ------- @@ -565,12 +816,48 @@ def events_by_period( >>> [round(float(x), 3) for x in months.events.system_failures[:2]] [0.372, 0.336] """ + from ._calendar import calendar_of + + context = calendar_of(usage) + if context is not None: + if unit is not None and unit != context.unit: + raise ValueError( + f"unit={unit!r} differs from the calendar's unit " + f"({context.unit!r}): give it once, on the calendar." + ) + rbd = context.diagram(rbd) + usage, unit = context.usage, context.unit usage = _usage(usage) notes: List[str] = [] + discount = _discount.yearly(discount) + given, discount = discount, _discount.net(discount, escalation) + if discount is not None and not cost: + raise ValueError( + "discount= gives the cost as a present value: ask for the " + "cost too, with cost=True." + ) unit = _resolve_unit(unit, _model_label(rbd), "diagram", notes) found, seconds = _period_edges(usage, period) ends = seconds / 3600.0 / UNITS[unit] - events = rbd.expected_events_by_window(ends, state=state) + from repyability.rbd._covariate_schedule import on_clock + + simulated = on_clock(rbd) + if simulated or cost: + from repyability.rbd._streams import shared_seed + + # The histories, the costs and the present values are cut from + # one set of simulations, seeded once. + seed = shared_seed(seed) + if simulated: + events = _history_events(rbd, ends, state, mc_samples, seed) + notes.append( + "A unit's duty plan changes over time, so its life on the " + "calendar depends on when each unit is put into service: the " + "events are counted in the simulations' histories (means of " + f"{_runs_of(rbd, mc_samples)} runs), not exact." + ) + else: + events = rbd.expected_events_by_window(ends, state=state) costs = None if cost: costs = rbd.cost_by_window( @@ -581,12 +868,51 @@ def events_by_period( levels=RANGE_LEVELS, ) notes.append( - f"Each period's mean cost is exact; its range ({RANGE_WORDS}) " - "is simulated." + f"Each period's mean cost is simulated, and its range " + f"({RANGE_WORDS})." + if simulated + else f"Each period's mean cost is exact; its range " + f"({RANGE_WORDS}) is simulated." + ) + expected_npv = npv = eac = None + if discount is not None: + rate = _discount.per_unit(discount, UNITS[unit]) + if simulated: + present = _simulated_present( + rbd, ends, rate, state, mc_samples, seed + ) + elif rate >= 0.0: + present = rbd.expected_cost(ends, state=state, discount_rate=rate) + else: + # Costs escalating faster than the discount: a rate below 0, + # valid over the forecast's window. + from repyability.rbd import _windows + + present = _windows._discounted_cost( + rbd, ends, rate, None, None, "p", state, None + ) + running = np.atleast_1d( + np.asarray( + present if isinstance(present, np.ndarray) else present.mean, + float, + ) + ) + expected_npv = np.diff(running, prepend=0.0) + npv = float(running[-1]) + eac = _discount.equivalent_annual( + npv, discount, float(seconds[-1]) / _YEAR_SECONDS + ) + notes.append( + f"{_discount.words(given, usage.start, escalation)} The " + "present values (expected_npv, npv) discount each cost from " + "when it falls (" + + ("in each simulation" if simulated else "exact") + + "); cost (its mean and range) is not discounted, and an " + "acquisition cost is not in the periods." ) notes.append( "The diagram's clock is calendar time from the forecast's start; " - "running hours reach it through the blocks' duty." + "running hours reach it through each block's duty plan." ) return EventsByPeriod( period=period, @@ -598,9 +924,136 @@ def events_by_period( cost=costs, range=None if costs is None else RANGE_WORDS, notes=tuple(notes), + discount=given, + expected_npv=expected_npv, + npv=npv, + eac=eac, + ) + + +def _runs_of(rbd, mc_samples) -> int: + """The simulations a run of ``rbd`` takes for ``mc_samples``.""" + return int(mc_samples) if mc_samples is not None else 1000 + + +def _traced(rbd) -> None: + """Refuse what a history does not show: a task or test that takes no + time (it leaves no outage), and the tests of hidden failures (a + failure is found later than it happens).""" + lead = ( + "The events by period of a diagram whose duty plan changes over " + "time are counted in the simulations' histories" + ) + for node, task in rbd._preventive.items(): + if task.duration is None: + raise NotImplementedError( + f"{lead}, where a preventive task that takes no time " + f"(node {node!r}) leaves no trace: give it the time it " + "takes, or the duty as one share." + ) + if rbd._inspection: + node = next(iter(rbd._inspection)) + raise NotImplementedError( + f"{lead}, which do not count the tests of hidden failures " + f"(node {node!r}) yet: give the duty as one share." + ) + if rbd._shutdowns: + raise NotImplementedError( + f"{lead}, which do not count a site's shutdowns yet: give the " + "duty as one share." + ) + + +def _history_events(rbd, ends, state, mc_samples, seed): + """Each window's expected events (an ``EventsByWindow``), the means + over the simulations' histories (``simulate_timelines``): a change + down that is not planned is a failure, a planned one a preventive + task, and each outage's time in a window its downtime there.""" + from repyability.rbd.results import EventsByWindow + + _traced(rbd) + ends = np.asarray(ends, dtype=float) + runs = rbd.simulate_timelines( + float(ends[-1]), + state=state, + mc_samples=mc_samples if mc_samples is not None else 1000, + seed=seed, + ) + starts = np.concatenate(([0.0], ends[:-1])) + + def tally(lines): + out = {k: np.zeros(ends.size) for k in ("f", "p", "d", "pd")} + n = len(lines) + for i in range(n): + line = lines[i] + times, planned = line.changes, line.planned + down = np.arange(0 if line.up else 1, times.size, 2) + at = times[down] + window = np.searchsorted(ends, at, side="right") + inside = window < ends.size + np.add.at(out["f"], window[inside & ~planned[down]], 1.0) + np.add.at(out["p"], window[inside & planned[down]], 1.0) + # Outages: from each change down to the next change up. + begin = list(at) + finish = [ + times[j + 1] if j + 1 < times.size else line.end for j in down + ] + flags = list(planned[down]) + if not line.up: + begin.insert(0, 0.0) + finish.insert(0, times[0] if times.size else line.end) + flags.insert(0, False) + for a, b, flag in zip(begin, finish, flags): + span = np.clip( + np.minimum(b, ends) - np.maximum(a, starts), 0.0, None + ) + out["d"] += span + if flag: + out["pd"] += span + return {k: v / n for k, v in out.items()} + + system = tally(runs.system) + nodes = {node: tally(lines) for node, lines in runs.components.items()} + zeros = {node: np.zeros(ends.size) for node in nodes} + return EventsByWindow( + starts=starts, + ends=ends, + system_failures=system["f"], + system_planned_outages=system["p"], + system_downtime=system["d"], + node_failures={n: v["f"] for n, v in nodes.items()}, + node_corrective={n: v["f"] for n, v in nodes.items()}, + node_preventive={n: v["p"] for n, v in nodes.items()}, + node_inspections=zeros, + node_downtime={n: v["d"] for n, v in nodes.items()}, + shutdowns=np.zeros(ends.size), + system_planned_downtime=system["pd"], + system_unplanned_downtime=system["d"] - system["pd"], + node_planned_downtime={n: v["pd"] for n, v in nodes.items()}, + node_unplanned_downtime={ + n: v["d"] - v["pd"] for n, v in nodes.items() + }, ) +def _simulated_present(rbd, ends, rate, state, mc_samples, seed): + """The expected cost from the start to each end as a present value, + each cost discounted from when it falls in the simulations + (``npv_distribution``, one seeded set of histories cut at each + end).""" + out = [] + for end in np.asarray(ends, dtype=float): + run = rbd.npv_distribution( + float(end), + discount_rate=rate, + mc_samples=mc_samples, + seed=seed, + state=state, + ) + out.append(-float(run.mean)) + return np.asarray(out) + + # ---------------------------------------------------------- shuts on dates diff --git a/repyability/schedule/_recurrence.py b/repyability/schedule/_recurrence.py index ce965e4d..356e10d6 100644 --- a/repyability/schedule/_recurrence.py +++ b/repyability/schedule/_recurrence.py @@ -1119,12 +1119,32 @@ def _raw(self, lo: date) -> Iterator[date]: return if self.anchor is not None: lo = max(lo, self.anchor) - rule = self._rrule(self.anchor) + rule = self._rrule(self._counted_from(lo)) else: rule = self._rrule(lo) for moment in rule.xafter(_midnight(lo), inc=True): yield moment.date() + def _counted_from(self, lo: date) -> date: + """Where the dateutil rule counts from for the dates from ``lo`` + (on or after the anchor): the anchor moved on by a whole number of + the rule's steps, to no later than ``lo``. The dates from ``lo`` + are the anchor's own, without walking to them from it, which made + each far date cost its distance from the anchor.""" + anchor = self.anchor + assert anchor is not None + if self.rule == "weekly" or self.unit in ("days", "weeks"): + step = self.every_n * (1 if self.unit == "days" else 7) + return anchor + timedelta(days=(lo - anchor).days // step * step) + yearly = self.rule == "yearly" or self.unit == "years" + months = self.every_n * (12 if yearly else 1) + first = anchor.year * 12 + anchor.month - 1 + steps = (lo.year * 12 + lo.month - 1 - first) // months + if steps <= 0: + return anchor + index = first + steps * months + return date(index // 12, index % 12 + 1, 1) + def _walk(self, lo: date) -> Iterator[Tuple[date, Optional[date], str]]: """Each raw date from ``lo`` on with what became of it: ``(raw, final, why)``, ``final`` None when it does not count, ``why`` one diff --git a/repyability/schedule/_service.py b/repyability/schedule/_service.py new file mode 100644 index 00000000..fd6db58a --- /dev/null +++ b/repyability/schedule/_service.py @@ -0,0 +1,409 @@ +"""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 : sequence of float + The covariates in force while the unit is serviced. + stale : sequence of float + The covariates in force while it is overdue (and throughout + without the service), as many as ``fresh``. + 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. + + Parameters + ---------- + times : array_like + The times of the services, on the diagram's clock (the plan's + unit of time, from 0). + """ + 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: + """What the condition is, in words.""" + 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) + 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", stop, state + ) + 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, + stop, + own_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 <= stop) + k = np.minimum( + 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 + 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/_task.py b/repyability/schedule/_task.py index a12d9e63..6a9bbb1e 100644 --- a/repyability/schedule/_task.py +++ b/repyability/schedule/_task.py @@ -20,10 +20,12 @@ from __future__ import annotations +import math from dataclasses import dataclass from datetime import date, datetime, time, timedelta from typing import Any, Dict, List, Optional, Protocol, Sequence, Tuple +from repyability.schedule import _discount from repyability.schedule._recurrence import ( VERSION, Recurrence, @@ -243,6 +245,17 @@ class TaskDue(_ScheduleResult): Plain words on what the rules left out or moved in the period (months with no fifth Saturday, excluded dates), and on the assumptions made. + discount : float or None + The yearly discount rate given (``due(..., discount=0.07)``); + None when none was. + npv : float or None + With a discount and a cost: what the period's costs are worth on + ``start``, each discounted from the date it is done, ``cost / (1 + + discount) ** years`` with a year of 365.25 days. + eac : float or None + The equivalent annual cost: the steady cost a year over the + period worth ``npv`` (``cost`` over the period's years at a + discount of 0). """ task: str @@ -262,6 +275,57 @@ class TaskDue(_ScheduleResult): moments: Tuple[datetime, ...] = () readings: Tuple[Optional[float], ...] = () stops_after: Tuple[Optional[datetime], ...] = () + discount: Optional[float] = None + npv: Optional[float] = None + eac: Optional[float] = None + + +@dataclass(frozen=True) +class LongRunValue(_ScheduleResult): + """What a task repeating for ever is worth now: returned by + ``Task.long_run_value``. + + Attributes + ---------- + task : str + The task's name. + start : datetime.date + The date the costs are discounted to; the dates from it count. + discount : float + The yearly discount rate. + npv : float + The present value on ``start`` of the task's cost every time it + is done, for ever. + eac : float + The equivalent annual cost: the steady cost a year, for ever, + worth ``npv`` (``npv * ln(1 + discount)``). + method : str + ``"closed form"`` (a plain interval of days or weeks: a geometric + sum, exact) or ``"summed"`` (any other task: its dates to + ``summed_to``, one by one). + precision : float + The most the dates left out can add to ``npv``: 0 for a closed + form; for a sum, what a task done every day after ``summed_to`` + would add, which no task exceeds. + summed_to : datetime.date or None + The last date summed to (None for a closed form). + count : int or None + How many times the task is done to ``summed_to`` (None for a + closed form). + notes : tuple of str + What was assumed. + """ + + task: str + start: date + discount: float + npv: float + eac: float + method: str + precision: float + summed_to: Optional[date] + count: Optional[int] + notes: Tuple[str, ...] @dataclass(frozen=True) @@ -291,6 +355,18 @@ class WorkByPeriod(_ScheduleResult): no_hours, no_cost : tuple of str The tasks with no duration (or no cost), left out of ``hours`` (or ``cost``), so a total is not taken for all the work. + discount : float or None + The yearly discount rate given; None when none was. + npv : tuple of float or None + With a discount: what each period's ``cost`` is worth on the + first date, each task discounted from the date it is done. + total_npv : float or None + The periods' ``npv`` summed. + eac : float or None + The equivalent annual cost: the steady cost a year over the dates + asked for worth ``total_npv``. + notes : tuple of str + What the present values assumed (empty with no discount). """ period: str @@ -303,10 +379,33 @@ class WorkByPeriod(_ScheduleResult): tasks: Tuple[Tuple[Tuple[str, date], ...], ...] no_hours: Tuple[str, ...] no_cost: Tuple[str, ...] + discount: Optional[float] = None + npv: Optional[Tuple[float, ...]] = None + total_npv: Optional[float] = None + eac: Optional[float] = None + notes: Tuple[str, ...] = () # ------------------------------------------------------------ task +#: The years a long-run sum first runs to, before it is known how far it +#: must go. +_FIRST_YEARS = 25.0 + + +def _years(start: date, end: date) -> float: + """The length in years of a period that includes both its dates.""" + return ((end - start).days + 1) / _discount.DAYS_A_YEAR + + +def _present_value( + cost: float, discount: float, start: date, done: Sequence[date] +) -> float: + """What ``cost`` on each date of ``done`` is worth on ``start``.""" + return math.fsum( + cost * _discount.factor_on(discount, start, day) for day in done + ) + def _amount(value, name: str, what: str) -> Optional[float]: if value is None: @@ -462,7 +561,9 @@ def describe(self) -> str: text += f"; done at the visits ({self.visits.describe()})" return text - def due(self, start, end, usage=None) -> TaskDue: + def due( + self, start, end, usage=None, *, discount=None, escalation=None + ) -> TaskDue: """When the task falls due from ``start`` to ``end``, **both included**, assuming each time is done on its due date (or at its visit). @@ -476,17 +577,52 @@ def due(self, start, end, usage=None) -> TaskDue: ([`DutyPlan.forecast`][repyability.schedule.DutyPlan.forecast]), which a limit by use (``Usage``) needs; it should cover the period. + discount : float, optional + A yearly discount rate (0.07 for 7% a year): the result then + has ``npv``, the costs' present value on ``start``, each + discounted from the date it is done, and ``eac``. By default + None: no present value. + escalation : float, optional + With ``discount``, the effective yearly rate every cost + escalates at from its price today (0.03 for 3% a year): the + present values (and ``eac``) take each cost grown to when it + falls, at the net yearly rate ``(1 + discount) / (1 + escalation) + - 1``. By default None: today's prices. Returns ------- TaskDue + + Examples + -------- + $250 every 30 days from 20 November 2026, at 7% a year, over the + first year: + + >>> from repyability.schedule import Recurrence, Task + >>> task = Task( + ... "grease bearings", + ... every=Recurrence.every(30, "days", "2026-11-20"), + ... cost=250.0, + ... ) + >>> year = task.due("2026-11-20", "2027-11-19", discount=0.07) + >>> year.count, year.cost, round(year.npv, 2) + (13, 3250.0, 3144.1) """ - return self._due(start, end, {"usage": usage}) + return self._due(start, end, {"usage": usage}, discount, escalation) - def _due(self, start, end, context: Dict[str, Any]) -> TaskDue: + def _due( + self, + start, + end, + context: Dict[str, Any], + discount=None, + escalation=None, + ) -> TaskDue: """``due`` with what the limits need (a later release's usage forecast) in ``context``.""" start, end = _period(start, end) + discount = _discount.yearly(discount) + given, discount = discount, _discount.net(discount, escalation) kinds = self._limits() limits = [limit.bind(self, start, end, context) for limit in kinds] last = None if self.last_done is None else _midnight(self.last_done) @@ -556,6 +692,18 @@ def _due(self, start, end, context: Dict[str, Any]) -> TaskDue: f"Overdue at {start}: due on {dates[0]}, after it was last " f"done ({self.last_done}); assumed done on {start}.", ) + npv = eac = None + if discount is not None: + if self.cost is None: + notes.append( + "No present value: the task has no cost (give cost=)." + ) + else: + npv = _present_value(self.cost, discount, start, done_on) + eac = _discount.equivalent_annual( + npv, discount, _years(start, end) + ) + notes.append(_discount.words(given, start, escalation)) return TaskDue( task=self.name, start=start, @@ -574,6 +722,234 @@ def _due(self, start, end, context: Dict[str, Any]) -> TaskDue: moments=tuple(moments), readings=tuple(readings), stops_after=tuple(stops), + discount=given, + npv=npv, + eac=eac, + ) + + def long_run_value( + self, start, discount, *, precision: float = 1e-9, escalation=None + ) -> LongRunValue: + """What the task is worth on ``start`` repeating for ever: the + present value of its cost every time it is done from ``start`` + on, at a yearly discount rate. + + A plain interval of days or weeks (no second limit, visits, + season or excluded dates) is a geometric sum, in closed form: + ``cost / (1 - (1 + discount) ** (-days / 365.25))`` from the + first time it is done. Any other task is summed date by date + until what is left cannot matter: a task is done once a day at + most, so the dates after any day are worth less than a task done + every day from then, and the sum stops where that is under + ``precision`` of the total. + + Parameters + ---------- + start : datetime.date or str + The date the costs are discounted to; the task's dates from + it count (an overdue task is done on it). + discount : float + The yearly discount rate, more than 0 (0.07 for 7% a year). + escalation : float, optional + The effective yearly rate the cost escalates at from its price + today (0.03 for 3% a year), below ``discount``: the value is + taken at the net yearly rate ``(1 + discount) / (1 + + escalation) - 1``. By default None: today's price. + precision : float, optional + For a task that is summed: the most the dates left out may + add, as a share of the value; by default 1e-9. + + Returns + ------- + LongRunValue + + Raises + ------ + ValueError + The task has no cost; ``discount`` is 0 (the costs add up + without end: ``due`` gives a period's); its dates end (given + dates: ``due`` to the last gives the whole value); a limit is + by use (``Usage``: it follows a usage forecast, which ends); + or the rate is too low for the sum to settle to ``precision`` + by the year 9999. + + Examples + -------- + $250 every 30 days from 20 November 2026, at 7% a year: + + >>> from repyability.schedule import Recurrence, Task + >>> task = Task( + ... "grease bearings", + ... every=Recurrence.every(30, "days", "2026-11-20"), + ... cost=250.0, + ... ) + >>> value = task.long_run_value("2026-11-20", 0.07) + >>> round(value.npv), value.method + (45112, 'closed form') + """ + start = _date(start, "start") + discount = _discount.yearly(discount, required=True) + assert discount is not None + given, discount = discount, _discount.net(discount, escalation) + assert discount is not None + if escalation is not None and not discount > 0.0: + raise ValueError( + f"The cost escalates at {_discount.percent(escalation)} a " + f"year, no slower than the discount of " + f"{_discount.percent(given)}: repeating for ever, it is " + "worth without end. Ask for a period's value with " + "due(start, end, discount=, escalation=)." + ) + if not (_is_number(precision) and 0.0 < float(precision) < 1.0): + raise ValueError( + "precision must be a share of the value, more than 0 and " + f"less than 1 (such as 1e-9); got {precision!r}." + ) + self._check_for_ever(start, discount) + assert self.cost is not None + notes = [_discount.words(given, start, escalation)] + gap = self._plain_gap() + to: Optional[date] = None + count: Optional[int] = None + if self.cost == 0.0: + npv, method, left = 0.0, "closed form", 0.0 + notes.append("The task costs nothing each time.") + elif gap is not None: + # The interval repeats exactly from the second time the task + # is done (the first may be an overdue one, done on start). + assert isinstance(self.every, Recurrence) + assert self.every.anchor is not None + known = max(start, self.every.anchor, self.last_done or start) + first, second = self._due( + start, known + timedelta(days=2 * gap), {} + ).done[:2] + npv = _present_value(self.cost, discount, start, [first]) + npv += self.cost * _discount.perpetuity( + discount, + _discount.years_from(start, second), + gap / _discount.DAYS_A_YEAR, + ) + method, left = "closed form", 0.0 + notes.append( + f"Done on {first}, then every {gap} days from {second}, " + "for ever: a geometric sum." + ) + else: + npv, left, to, count = self._summed( + start, discount, float(precision) + ) + method = "summed" + notes.append( + f"Summed date by date to {to} ({count} times); a task done " + f"every day after it would add {left:.3g}, which this one " + "cannot exceed." + ) + return LongRunValue( + task=self.name, + start=start, + discount=given, + npv=npv, + eac=_discount.equivalent_annual(npv, discount, math.inf), + method=method, + precision=left, + summed_to=to, + count=count, + notes=tuple(notes), + ) + + def _check_for_ever(self, start: date, discount: float) -> None: + """Refuse what has no long-run value, saying what to run.""" + if self.cost is None: + raise ValueError( + f"Task {self.name!r} has no cost to value: give cost=." + ) + if discount == 0.0: + raise ValueError( + "With no discount (discount=0) a task repeating for ever " + "costs without end: give a yearly rate above 0, or ask for " + "a period's cost with due(start, end)." + ) + kinds = self._limits() + if not all(isinstance(kind, _CalendarLimit) for kind in kinds): + raise ValueError( + f"Task {self.name!r} has a limit by use, which follows a " + "usage forecast, and a forecast ends: ask for the present " + "value over the forecast with due(start, end, usage=..., " + "discount=...)." + ) + ends = [k.rule.given[-1] for k in kinds if k.rule.rule == "on"] + if self.visits is not None and self.visits.rule == "on": + what = "is done at visits on given dates" + last = self.visits.given[-1] + elif len(ends) == len(kinds): + what, last = "is on given dates", max(ends) + else: + return + raise ValueError( + f"Task {self.name!r} {what}, which end on {last}: " + + ( + "nothing is left of it from then." + if last < start + else f"due({start}, {last}, discount=...) gives its whole " + "present value." + ) + ) + + def _plain_gap(self) -> Optional[int]: + """The days between a plain interval's dates (every so many days + or weeks, and nothing else that moves a date); None for any other + task.""" + rule = self.every + if ( + self.also is not None + or self.visits is not None + or not isinstance(rule, Recurrence) + or rule.rule != "every" + or rule.unit not in ("days", "weeks") + or rule.season is not None + or rule.excluding + ): + return None + return rule.every_n * (7 if rule.unit == "weeks" else 1) + + def _summed(self, start: date, discount: float, precision: float): + """The task's present value summed date by date, to where a task + done every day after could add no more than ``precision`` of it: + the value, that bound, the last date summed to and the count.""" + assert self.cost is not None + day = 1.0 / _discount.DAYS_A_YEAR + rate = _discount.continuous(discount) + latest = (date.max - start).days + days = min(int(_FIRST_YEARS * _discount.DAYS_A_YEAR), latest) + # The whole value is no more than a task every day from start, so + # the bound cannot be under the precision before this many days. + soonest = -math.log(precision) / rate * _discount.DAYS_A_YEAR - 1.0 + while soonest <= latest: + end = start + timedelta(days=days) + done = self._due(start, end, {}).done + npv = _present_value(self.cost, discount, start, done) + # Every day after ``end``, for ever. + left = self.cost * _discount.perpetuity( + discount, (days + 1) * day, day + ) + if npv > 0.0 and left <= precision * npv: + return npv, left, end, len(done) + if days == latest: + break + # Where the bound falls to the precision of what is summed so + # far (the whole value is no less); twice as far with nothing + # summed yet. + if npv > 0.0: + more = math.log(left / (precision * npv)) / rate + days = days + int(more * _discount.DAYS_A_YEAR) + 1 + else: + days = 2 * days + days = min(days, latest) + raise ValueError( + f"At {_discount.percent(discount)} a year the sum does not " + f"settle to precision={precision:g} by the year 9999, as far " + "as dates go: give a looser precision=, or ask for a period's " + "present value with due(start, end, discount=...)." ) def _notes(self, start: date, end: date) -> List[str]: @@ -704,7 +1080,14 @@ def _periods(start: date, end: date, period: str): def work_by_period( - tasks: Sequence[Task], period, start, end, usage=None + tasks: Sequence[Task], + period, + start, + end, + usage=None, + *, + discount=None, + escalation=None, ) -> WorkByPeriod: """The work tasks need in each calendar period from ``start`` to ``end`` (both included): how many are done, their hours and cost, @@ -722,6 +1105,17 @@ def work_by_period( usage : UsageForecast, optional The map from dates to meter readings, for tasks with a limit by use (see ``Task.due``). + discount : float, optional + A yearly discount rate (0.07 for 7% a year): the result then has + each period's ``npv`` (its costs' present value on ``start``, each + task discounted from the date it is done), ``total_npv`` and + ``eac``. By default None: no present values. + escalation : float, optional + With ``discount``, the effective yearly rate every cost + escalates at from its price today (0.03 for 3% a year): the + present values (and ``eac``) take each cost grown to when it + falls, at the net yearly rate ``(1 + discount) / (1 + escalation) + - 1``. By default None: today's prices. Returns ------- @@ -749,10 +1143,13 @@ def work_by_period( "Each task needs its own name, to be told apart in the result." ) start, end = _period(start, end) + discount = _discount.yearly(discount) + given, discount = discount, _discount.net(discount, escalation) spans = _periods(start, end, period) firsts = [a for a, _ in spans] n = len(spans) count, hours, cost = [0] * n, [0.0] * n, [0.0] * n + worth: List[List[float]] = [[] for _ in range(n)] listed: List[List[Tuple[str, date]]] = [[] for _ in range(n)] by_task: Dict[str, Tuple[int, ...]] = {} for task in tasks: @@ -767,7 +1164,26 @@ def work_by_period( hours[index] += task.duration if task.cost is not None: cost[index] += task.cost + if discount is not None: + worth[index].append( + task.cost * _discount.factor_on(discount, start, day) + ) by_task[task.name] = tuple(mine) + npv = total_npv = eac = None + notes: List[str] = [] + if discount is not None: + npv = tuple(math.fsum(x) for x in worth) + total_npv = math.fsum(npv) + eac = _discount.equivalent_annual( + total_npv, discount, _years(start, end) + ) + notes.append(_discount.words(given, start, escalation)) + missing = [t.name for t in tasks if t.cost is None] + if missing: + notes.append( + "The present values leave out the tasks with no cost: " + f"{', '.join(missing)}." + ) return WorkByPeriod( period=period, starts=tuple(firsts), @@ -781,4 +1197,9 @@ def work_by_period( ), no_hours=tuple(t.name for t in tasks if t.duration is None), no_cost=tuple(t.name for t in tasks if t.cost is None), + discount=given, + npv=npv, + total_npv=total_npv, + eac=eac, + notes=tuple(notes), ) diff --git a/repyability/schedule/_value.py b/repyability/schedule/_value.py new file mode 100644 index 00000000..cfea0b67 --- /dev/null +++ b/repyability/schedule/_value.py @@ -0,0 +1,1059 @@ +"""What a scheduled task is worth: the cost with it against without it, +on real dates (UC-50 of this package's ``README.md``). + +``task_value(task, does, usage)`` takes the task (its dates, from +``Task.due``), what it does to a part, as plain data, and the usage +forecast, and returns a ``TaskValue``: what the part costs with the task +and without it, and the difference, by calendar period and in all, as +present values with a ``discount``. What the task does is said by the +caller, not saved on the ``Task`` (that record is the caller's): + +- ``Replaces(part)``: the task puts a new part in at every date it is + done, whatever the part's age (block replacement on dates); without + it, the part runs to failure. +- ``Finds(device, demand_rate=, consequence_cost=)``: the task tests a + protective device for a hidden failure (UC-54) and has a failure it + finds repaired; without it, the device is never tested. + +Either way each side is a count of events that accrues with the part's +operating time, each at one cost (a part's failures; the demands that +meet a device failed), and costs at instants (the task's own; the +repairs of what a test finds). With ``Replaces``, between two of the +task's dates the part is a renewal process from new, so its expected +failures to any time are a sum of ``NonRepairable.failures`` over the +stretches between the dates. With ``Finds``, the device's chance of +being failed over time is ``maintenance._finding_window``'s, with the +tests at the task's times on the device's clock. Each side's accrued +cost is discounted as ``failures_by_period`` discounts it +(``_forecast._accrued_npv``); a cost at an instant from that instant. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from datetime import date, datetime, timedelta +from typing import Any, Callable, Dict, List, Optional, Tuple + +import numpy as np + +from repyability.utils.checks import is_number + +from . import _discount +from ._forecast import ( + _YEAR_SECONDS, + NPV_TOLERANCE, + _accrued_npv, + _model_label, + _period_edges, + _resolve_unit, + _tolerance, + _usage, +) +from ._service import Condition, Services, simulated # noqa: F401 +from ._task import Task +from ._usage import _Plain + + +@dataclass(frozen=True) +class Replaces: + """What a task does: it replaces ``part`` with a new one every time it + is done, whatever the part's age (and the part is replaced when it + fails, too). Plain data for + [`task_value`][repyability.schedule.task_value]. + + Parameters + ---------- + part : NonRepairable + The part, with its life in the unit of the usage forecast's model + time and its ``unplanned_cost`` (a failure's). Its + ``planned_cost`` is the task's price unless the task has a + ``cost``. + """ + + part: Any + + def __post_init__(self) -> None: + from repyability.non_repairable import NonRepairable + + if not isinstance(self.part, NonRepairable): + raise TypeError( + "Replaces takes the part the task replaces, a " + f"NonRepairable; got {self.part!r}." + ) + + def describe(self) -> str: + """What the task does, in words.""" + return "replaces the part with a new one" + + +@dataclass(frozen=True) +class Finds: + """What a task does: it tests ``device``, a protective device (a + relief valve, a trip, a standby pump's start), for a failure nobody + would otherwise see, and a failure it finds is repaired as new. + Plain data for [`task_value`][repyability.schedule.task_value]. + + Parameters + ---------- + device : NonRepairable + The device, with its life (a failure is hidden) in the unit of + the usage forecast's model time. Its own costs are not used. + demand_rate : float + How often the protected event comes, per unit of the device's + time, at least 0. + consequence_cost : float + What a demand that meets the device failed costs, at least 0. + repair_cost : float, optional + What repairing a failure costs, found by a test or shown by a + demand; by default 0. + demands_reveal : bool, optional + Whether a demand that meets the device failed shows the failure, + which is repaired as new then (the default), with the task and + without it. False: only a test finds a failure, as + [`failure_finding`][repyability.failure_finding] has it. + """ + + device: Any + demand_rate: float = field(kw_only=True) + consequence_cost: float = field(kw_only=True) + repair_cost: float = field(default=0.0, kw_only=True) + demands_reveal: bool = field(default=True, kw_only=True) + + def __post_init__(self) -> None: + from repyability.maintenance._decisions import ( + _check_protective, + _number, + ) + from repyability.non_repairable import NonRepairable + + if not isinstance(self.device, NonRepairable): + raise TypeError( + "Finds takes the device the task tests, a NonRepairable; " + f"got {self.device!r}." + ) + _check_protective(self.device) + for name in ("demand_rate", "consequence_cost", "repair_cost"): + _number(getattr(self, name), name) + if not isinstance(self.demands_reveal, bool): + raise ValueError( + "demands_reveal must be True or False; got " + f"{self.demands_reveal!r}." + ) + + def describe(self) -> str: + """What the task does, in words.""" + return "tests the device for a hidden failure" + + +@dataclass(frozen=True) +class TaskValue(_Plain): + """What a scheduled task is worth against not doing it: returned by + [`task_value`][repyability.schedule.task_value]. + + Money is a present value at the forecast's start when a ``discount`` + is given, and the plain expected cost otherwise. Each period's + numbers are its own and add up to ``total``'s. + + Attributes + ---------- + task : str + The task's name. + does : str + What the task does, in words. + with_words, without_words : str + What "with the task" and "without it" were taken to mean. + period : str + ``"day"``, ``"week"``, ``"month"``, ``"quarter"`` or ``"year"``. + starts, ends : tuple of datetime + Each period's start and end at the site. + unit : str + The part's unit of time. + age : float + The part's age at the forecast's start, in ``unit``. + dates : tuple of datetime.date + The dates the task is done in the forecast. + model_times : numpy.ndarray + The part's clock (operating time since the forecast's start, in + ``unit``) at each time the task is done. + discount : float or None + The yearly discount rate given; None when none was. + with_task, without_task : numpy.ndarray + What the part costs in each period with the task (its failures + and the task's own cost) and without it (its failures): present + values with a discount. + value : numpy.ndarray + ``without_task - with_task``: what the task saves in each period, + net of its own cost (positive when it pays). + task_cost : numpy.ndarray + The task's own cost in each period (in ``with_task``). + cost_with, cost_without : numpy.ndarray + The same two costs undiscounted. + failures_with, failures_without : numpy.ndarray + The expected failures in each period with and without the task. + failures_avoided : numpy.ndarray + ``failures_without - failures_with``. + total : dict + The whole forecast's: ``with_task``, ``without_task``, ``value``, + ``task_cost``, ``cost_with``, ``cost_without``, + ``failures_with``, ``failures_without``, ``failures_avoided`` + and ``count`` (the times the task is done). + precision : float + How far the true total ``value`` can be from the one given: the + two sides' present values are each within their integrals' + error estimates of theirs (as + ``FailuresByPeriod.npv_precision``); 0 undiscounted. + eac : dict or None + With a discount, the equivalent annual cost of ``with_task`` and + ``without_task`` and of ``value`` over the forecast: the steady + amount a year worth each. + notes : tuple of str + What was assumed. + found : numpy.ndarray or None + With ``Finds``: the expected failures the tests find in each + period (``total["found"]`` in all). None otherwise. + unavailability_with, unavailability_without : numpy.ndarray or None + With ``Finds``: the device's mean unavailability in each period + with the task and without it, the share of the period's + 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`` + and ``failures_avoided`` count those, and ``with_task`` is the + tests' cost, the repairs' and those demands'. + """ + + task: str + does: str + with_words: str + without_words: str + period: str + starts: Tuple[datetime, ...] + ends: Tuple[datetime, ...] + unit: str + age: float + dates: Tuple[date, ...] + model_times: np.ndarray + discount: Optional[float] + with_task: np.ndarray + without_task: np.ndarray + value: np.ndarray + task_cost: np.ndarray + cost_with: np.ndarray + cost_without: np.ndarray + failures_with: np.ndarray + failures_without: np.ndarray + failures_avoided: np.ndarray + total: Dict[str, Any] + precision: float + eac: Optional[Dict[str, float]] + notes: Tuple[str, ...] + 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" + return ( + f"TaskValue({self.task!r} over {len(self.starts)} " + f"{self.period}s from {self.starts[0]:%Y-%m-%d}: {money} with " + f"{self.total['with_task']:.6g}, without " + f"{self.total['without_task']:.6g}, value " + f"{self.total['value']:.6g}; failures avoided " + f"{self.total['failures_avoided']:.4g})" + ) + + +def _price(task: Task, part, notes: List[str]) -> float: + """The planned replacement's one price: the task's cost, else the + part's planned cost; refused when both are given and differ, or + neither is.""" + planned = getattr(part, "cp", None) + if task.cost is not None and planned is not None: + if not np.isclose(task.cost, planned, rtol=1e-12, atol=0.0): + raise ValueError( + f"Task {task.name!r} costs {task.cost:g} and the part's " + f"planned_cost is {planned:g}: the task is the planned " + "replacement, so they are one price. Give the same number " + "to both, or leave one out." + ) + return float(task.cost) + if task.cost is not None: + return float(task.cost) + if planned is not None: + notes.append( + f"The task has no cost: each time it is done costs the part's " + f"planned_cost, {planned:g}." + ) + return float(planned) + raise ValueError( + f"Task {task.name!r} has no cost and the part has no " + "planned_cost: give the task's cost= (what a planned replacement " + "costs), or the part's planned_cost=." + ) + + +def _done_instants(task: Task, usage, notes: List[str]): + """The task's dates in the forecast, each with the real seconds from + the forecast's start to when it is done: midnight of its date, or, + for a limit by use done on the day it falls due, the moment the meter + reaches its reading. A date before the forecast starts (an overdue + task, done at the start) counts at the start.""" + origin, start_s = usage._origin, usage._start_s + span = usage._end_s - start_s + last = (usage.end - timedelta(microseconds=1)).date() + due = task.due(usage.start.date(), last, usage=usage) + dates: List[date] = [] + seconds: List[float] = [] + for day, moment in zip(due.done, due.moments): + if task.visits is None and day == moment.date(): + when = moment + else: + when = datetime.combine(day, datetime.min.time()) + s = (usage._clock.instant(when, "done") - origin).total_seconds() + s = max(s - start_s, 0.0) + if s < span: + dates.append(day) + seconds.append(s) + notes.extend(due.notes) + return due, dates, np.array(seconds, float) + + +def _renewals(part, age: float, times: np.ndarray): + """The part's expected failures from 0 to each of an array of model + times, as a function: run to failure from ``age`` when ``times`` is + empty, else renewed at each of ``times`` (from new after each).""" + cuts = np.unique(times) + starts = np.concatenate([[0.0], cuts[cuts > 0.0]]) + first_age = 0.0 if cuts.size and cuts[0] <= 0.0 else age + lengths = np.append(np.diff(starts), np.inf) + + def expected(ends) -> np.ndarray: + ends = np.asarray(ends, float) + out = np.zeros(ends.shape) + for k, (s, length) in enumerate(zip(starts, lengths)): + ran = np.clip(ends - s, 0.0, length) + if not np.any(ran > 0.0): + continue + out += np.asarray( + part.failures( + ran, age=first_age if k == 0 else 0.0 + ).expected_failures, + float, + ).reshape(ends.shape) + return out + + return expected + + +@dataclass(frozen=True) +class _Plan: + """The two sides of a task's value: each a count of events that + accrues with the part's operating time, at ``event_cost`` each, and, + with the task, its own cost and ``extra`` at instants.""" + + with_events: Callable[[np.ndarray], np.ndarray] + without_events: Callable[[np.ndarray], np.ndarray] + event_cost: float + extra_seconds: np.ndarray # costs at instants besides the task's own + extra_amounts: np.ndarray + error: float # how far the costs' total can be out, undiscounted + with_words: str + without_words: str + notes: Tuple[str, ...] + with_hidden: Any = None # the device's hidden failures (Finds) + without_hidden: Any = None + found: Optional[np.ndarray] = None # at each of extra_seconds + + +def _replacing(part, price, failure_cost, age, unit, times, count) -> _Plan: + """``Replaces``: block replacement at ``times`` against running to + failure.""" + return _Plan( + with_events=_renewals(part, age, times), + without_events=_renewals(part, age, np.array([])), + event_cost=failure_cost, + extra_seconds=np.array([]), + extra_amounts=np.array([]), + error=0.0, + with_words=( + f"With the task: the part replaced with a new one each time " + f"the task is done ({count} times in the forecast), at " + f"{price:g} whatever its age, and when it fails, at " + f"{failure_cost:g}; a failure does not move the task's dates." + ), + without_words=( + "Without the task: the part run to failure from the same age " + f"({age:g} {unit}) over the same dates, replaced only when it " + f"fails, at {failure_cost:g}." + ), + notes=( + "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 planned replacement takes no time on the part's clock.", + ), + ) + + +def _testing( + does: Finds, price, age, unit, times, done_s, window, count +) -> _Plan: + """``Finds``: the device tested at ``times`` against never tested.""" + from repyability.maintenance._finding_window import _hidden + + demand = float(does.demand_rate) + repair = float(does.repair_cost) + consequence = float(does.consequence_cost) + reveal = demand if does.demands_reveal else 0.0 + each = consequence + (repair if reveal > 0.0 else 0.0) + # Tests at one time on the device's clock (it did not run between + # them) are one test of it: the first finds what there is to find. + tests, first = np.unique(np.minimum(times, window), return_index=True) + first = first[tests > 0.0] # at 0 the device is working + tests = tests[tests > 0.0] + model = does.device.reliability + tested = _hidden(model, age, tests, window, reveal) + never = _hidden(model, age, np.array([]), window, reveal) + if does.demands_reveal: + shown = ( + f", and shows the failure, repaired then at {repair:g}" + if demand > 0.0 + else "" + ) + left = ( + "a failure stays until a demand meets it, which costs " + f"{consequence:g} and has it repaired at {repair:g}" + ) + else: + shown = "; only a test finds a failure" + left = ( + "a failure is never found, and every demand after it costs " + f"{consequence:g}" + ) + return _Plan( + with_events=lambda ends: demand * tested.failed_time(ends), + without_events=lambda ends: demand * never.failed_time(ends), + event_cost=each, + extra_seconds=done_s[first], + extra_amounts=repair * tested.found, + error=( + each * demand * (tested.time_error + never.time_error) + + repair * tested.found_error + ), + with_words=( + f"With the task: the device tested each time the task is " + f"done ({count} times in the forecast), at {price:g} a test; " + f"a failure a test finds repaired as new at {repair:g}; a " + f"demand (at a rate of {demand:g}, in {unit}) that meets " + f"the device failed costs {consequence:g}{shown}." + ), + without_words=( + "Without the task: the device never tested, from the same " + f"age ({age:g} {unit}) over the same dates: {left}." + ), + notes=( + "The device is taken to be working at the forecast's start. " + "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 test and a repair take no time, and a test never misses " + "a failure.", + "Demands come at random, at their rate per unit of the " + f"device's own time ({unit}), so only while it runs, and " + "independently of the device.", + ), + with_hidden=tested, + without_hidden=never, + found=tested.found, + ) + + +def _in_periods(ends: np.ndarray, hidden) -> np.ndarray: + """A device's mean unavailability in each period of operating time + ending at ``ends``: its chance of being failed then where the period + has none.""" + failed = np.diff(hidden.failed_time(ends), prepend=0.0) + ran = np.diff(ends, prepend=0.0) + at = hidden.unavailability(ends) + 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, + usage, + *, + age: float = 0.0, + unit: Optional[str] = None, + discount: Optional[float] = None, + 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 + difference, as present values with a ``discount``. + + ``Replaces(part)``: the task puts a new part in at every date it is + done (``Task.due`` over the forecast, with its visits, second limit + and ``resets``), whatever the part's age, and a failure in between is + replaced too without moving the dates (block replacement on dates). + Without the task the part runs to failure from the same age over the + same dates. Between two of the task's dates the part is a renewal + process from new, so the expected failures are + [`NonRepairable.failures`][repyability.NonRepairable.failures]' over + each stretch (exact); a failure costs the part's ``unplanned_cost`` + and the task its ``cost``. A failure's cost is discounted from when + it is expected to fall, as + [`failures_by_period`][repyability.schedule.failures_by_period] + discounts it (to within ``precision``), and the task's own cost from + when it is done. + + ``Finds(device, demand_rate=, consequence_cost=, repair_cost=)``: the + task tests a protective device for a hidden failure at every date it + is done, at the task's ``cost`` a test, and a failure it finds is + repaired as new. Demands come at ``demand_rate`` per unit of the + device's time, and one that meets the device failed costs + ``consequence_cost`` (and, by default, shows the failure, which is + repaired then). Without the task the device is never tested. The + device's chance of being failed over time, with the tests at the + task's times on its clock, is + [`failure_finding_window`][repyability.failure_finding_window]'s + (numerical, its error in ``precision``); the demands' cost is + discounted as it accrues, and a test and the repair of what it finds + from when the task is done. The result's "failures" are then the + 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, 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 + ``UsageForecast.calendar`` for a life in calendar time); its + start is "now", and its span the window valued. + age : float, optional + The part's age at the forecast's start, in ``unit``; by default 0. + A device that is tested is taken to be working then. + unit : str, optional + The unit the part's life is in; by default the one its model's + label names, else hours (with a note). + discount : float, optional + A yearly discount rate (0.07 for 7% a year): money is then a + present value at the forecast's start. By default None: plain + expected costs. + escalation : float, optional + With ``discount``, the effective yearly rate every cost + escalates at from its price today (0.03 for 3% a year): the + present values (and ``eac``) take each cost grown to when it + falls, at the net yearly rate ``(1 + discount) / (1 + escalation) + - 1``. By default None: today's prices. + period : str, optional + ``"day"``, ``"week"``, ``"month"`` (the default), ``"quarter"`` or + ``"year"``. + 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 + ------- + TaskValue + + Raises + ------ + TypeError + ``task`` is not a ``Task``, or ``does`` is neither a + ``Replaces`` nor a ``Finds``. + ValueError + The part has no ``unplanned_cost``; the task and the part give + two prices for the planned replacement, or neither gives one; a + task that tests has no ``cost``; or as ``Task.due`` and + ``failures_by_period``. + NotImplementedError + With ``Finds``: more than 2,000 tests in the forecast. + + Examples + -------- + A pump's wear ring (Weibull, scale 9,000 operating hours, shape 2.5), + 5,200 h old, $4,800 when it fails; a new one ($600) at every + 6-monthly service; the pump runs Monday to Friday, 06:00 to 22:00: + + >>> import surpyval as surv + >>> from repyability import NonRepairable + >>> from repyability.schedule import ( + ... DutyPlan, Recurrence, Replaces, Shifts, Task, task_value + ... ) + >>> ring = NonRepairable( + ... surv.Weibull.from_params([9000.0, 2.5]), unplanned_cost=4800.0 + ... ) + >>> service = Task( + ... "new wear ring", + ... every=Recurrence.every(6, "months", "2026-12-01"), + ... cost=600.0, + ... ) + >>> usage = DutyPlan(Shifts("Mon-Fri", "06:00", "22:00")).forecast( + ... "2026-11-16", "2027-12-01" + ... ) + >>> worth = task_value(service, Replaces(ring), usage, age=5200.0) + >>> [str(d) for d in worth.dates] + ['2026-12-01', '2027-06-01'] + >>> total = worth.total + >>> round(total["with_task"], 2), round(total["without_task"], 2) + (1550.82, 2987.56) + >>> round(total["value"], 2), round(total["failures_avoided"], 3) + (1436.74, 0.549) + """ + if not isinstance(task, Task): + raise TypeError(f"task must be a Task; got {task!r}.") + 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, 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) + notes: List[str] = [] + 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) + 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 " + "the task saves nothing to set against its own. Give the " + "NonRepairable unplanned_cost=." + ) + price = _price(task, part, notes) + elif task.cost is None: + raise ValueError( + f"Task {task.name!r} has no cost: give the task's cost=, what " + "one test costs (0.0 if it is free)." + ) + else: + price = float(task.cost) + + found, seconds = _period_edges(usage, period) + n = seconds.size + 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) + base = usage._at_s("hours", starts_s) + times = (usage._at_s("hours", clock_s) - base) / scale + times = np.maximum(np.asarray(times, float).reshape(done_s.shape), 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) + if isinstance(does, Services): + plan, sim = _servicing( + does, + price, + usage, + unit, + age, + times, + done_s, + seconds, + discount, + mc_samples, + seed, + confidence, + len(dates), + ) + 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: + 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) + + cost_with = each * fails_with + task_cost + if plan.extra_seconds.size: + cost_with = cost_with + by_period( + plan.extra_seconds, plan.extra_amounts + ) + 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 + eac = { + key: _discount.equivalent_annual( + float(np.sum(amounts)), discount, years + ) + for key, amounts in ( + ("with_task", money_with), + ("without_task", money_without), + ("value", value), + ) + } + notes.append( + "Operating time comes from the duty plan " + f"({usage.describe()}); the part's age is at the forecast's start." + ) + notes.extend(plan.notes) + if plan.error > 0.0: + notes.append( + "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 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 " + "cost is discounted from when it is expected to fall, each " + f"side to within its error estimate ({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)), + "value": float(np.sum(value)), + "task_cost": float(np.sum(money_task)), + "cost_with": float(np.sum(cost_with)), + "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(avoided)), + "count": len(dates), + } + 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 = { + "found": by_period(plan.extra_seconds, plan.found), + "unavailability_with": _in_periods(ends, plan.with_hidden), + "unavailability_without": _in_periods(ends, plan.without_hidden), + } + total["found"] = float(np.sum(plan.found)) + total["unavailability_with"] = float( + _in_periods(whole, plan.with_hidden)[0] + ) + total["unavailability_without"] = float( + _in_periods(whole, plan.without_hidden)[0] + ) + return TaskValue( + task=task.name, + does=does.describe(), + with_words=plan.with_words, + without_words=plan.without_words, + period=period, + starts=found.starts, + ends=found.ends, + unit=unit, + age=age, + dates=tuple(dates), + model_times=times, + discount=given, + with_task=np.asarray(money_with, float), + without_task=np.asarray(money_without, float), + value=np.asarray(value, float), + task_cost=np.asarray(money_task, float), + cost_with=cost_with, + cost_without=cost_without, + failures_with=fails_with, + failures_without=fails_without, + failures_avoided=avoided, + total=total, + precision=float(precision), + eac=eac, + notes=tuple(notes), + **hidden, + ) diff --git a/repyability/schemas/__init__.py b/repyability/schemas/__init__.py new file mode 100644 index 00000000..50c3de4c --- /dev/null +++ b/repyability/schemas/__init__.py @@ -0,0 +1,18 @@ +"""The JSON Schemas of RePyability's documents (see ``value_plan``).""" + +import json +from importlib import resources + + +def npv_schema() -> dict: + """The JSON Schema (draft 2020-12) of + [`value_plan`][repyability.value_plan]'s request and answer: its + ``$defs`` hold ``request`` and ``answer``, each a schema of its own. + + Returns + ------- + dict + The schema, as ``repyability/schemas/npv-1.json`` holds it. + """ + text = resources.files(__name__).joinpath("npv-1.json").read_text() + return json.loads(text) diff --git a/repyability/schemas/npv-1.json b/repyability/schemas/npv-1.json new file mode 100644 index 00000000..11a20e21 --- /dev/null +++ b/repyability/schemas/npv-1.json @@ -0,0 +1,146 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/derrynknife/RePyability/schemas/npv-1.json", + "title": "RePyability value_plan, schema 1", + "description": "A request to value a plan (value_plan) and its answer.", + "$defs": { + "diagram": { + "description": "A RepairableRBD as its to_dict() saves it, or a UnitPlan as its to_dict() saves it (valued as its one-node diagram, UnitPlan.diagram()).", + "type": "object" + }, + "number": { + "description": "A number; one that is not finite is written as text.", + "oneOf": [ + {"type": "number"}, + {"enum": ["inf", "-inf", "nan"]} + ] + }, + "analysis": { + "enum": [ + "expected_npv", + "expected_npv_uncertainty", + "npv_distribution", + "compare_npv", + "plan_vs_actual" + ] + }, + "request": { + "type": "object", + "properties": { + "schema": {"const": 1}, + "diagram": {"$ref": "#/$defs/diagram"}, + "analysis": {"$ref": "#/$defs/analysis"}, + "inputs": { + "description": "The analysis's inputs, by its argument names.", + "type": "object", + "properties": { + "horizon": {"type": "number", "exclusiveMinimum": 0}, + "discount_rate": {"type": "number"}, + "value_rate": { + "oneOf": [ + {"type": "number"}, + { + "type": "object", + "properties": { + "times": {"type": "array", "items": {"type": "number"}}, + "rates": {"type": "array", "items": {"type": "number"}} + }, + "required": ["rates"], + "additionalProperties": false + } + ] + }, + "periods": { + "oneOf": [ + {"type": "integer", "minimum": 1}, + {"type": "array", "items": {"type": "number"}} + ] + }, + "escalation": { + "type": "object", + "additionalProperties": {"type": "number"} + }, + "rates": {"enum": ["nominal", "real"]}, + "inflation": {"type": ["number", "null"]}, + "retire_at": {"type": ["number", "null"]}, + "salvage": { + "oneOf": [ + {"type": "number"}, + {"type": "object", "additionalProperties": {"type": "number"}}, + {"type": "null"} + ] + }, + "state": { + "type": "object", + "additionalProperties": {"type": "object"} + }, + "start_state": { + "type": "object", + "additionalProperties": {"type": "object"} + }, + "timelines": { + "type": "object", + "additionalProperties": { + "type": "object", + "required": ["end"] + } + }, + "seed": {"type": ["integer", "null"]}, + "mc_samples": {"type": ["integer", "null"], "minimum": 1} + } + }, + "other": {"$ref": "#/$defs/diagram"} + }, + "required": ["schema", "diagram", "analysis"], + "additionalProperties": false + }, + "answer": { + "type": "object", + "properties": { + "schema": {"const": 1}, + "analysis": {"$ref": "#/$defs/analysis"}, + "request": {"$ref": "#/$defs/request"}, + "units": { + "type": "object", + "properties": { + "time": {"type": ["string", "null"]}, + "money": {"const": "cost units"} + }, + "required": ["time", "money"] + }, + "route": { + "type": "object", + "properties": { + "route": {"enum": ["exact", "numerical", "simulated", "refused"]}, + "reason": {"type": "string"} + }, + "required": ["route", "reason"] + }, + "result": { + "description": "The analysis's result, its to_dict().", + "type": "object", + "properties": { + "npv": {"$ref": "#/$defs/number"}, + "mean": {"$ref": "#/$defs/number"} + } + }, + "refused": { + "type": "object", + "properties": { + "reason": {"type": "string"}, + "routes": { + "type": "object", + "additionalProperties": {"type": "string"} + } + }, + "required": ["reason", "routes"] + } + }, + "required": ["schema", "analysis", "request", "units", "route"], + "oneOf": [ + {"required": ["result"]}, + {"required": ["refused"]} + ] + } + } +} diff --git a/repyability/tests/capabilities.py b/repyability/tests/capabilities.py index 07016636..c237d1d2 100644 --- a/repyability/tests/capabilities.py +++ b/repyability/tests/capabilities.py @@ -55,7 +55,7 @@ ), ( "B-life, time to a reliability", - ("bx_life", "time_to_reliability"), + ("bx_life", "time_to_reliability", "qf"), ), ("Given the system's age", ("cs",)), ("Given the components' ages or states", ("sf_given_state",)), @@ -132,6 +132,22 @@ ("Expected cost in a window", ("expected_cost",)), ("Expected net present value", ("expected_npv",)), ("A plan against what happened", ("plan_vs_actual",)), + ( + "Simulated net present value (distribution)", + ("npv_distribution",), + ), + ( + "Best time to switch blocks' running (simulated NPV)", + ("best_switch_time",), + ), + ( + "Two plans' net present values compared", + ("compare_npv",), + ), + ( + "Least spend for a bad run's downtime (simulated)", + ("least_spend_for_downtime",), + ), ("Cost in each of a run of windows", ("cost_by_window",)), ("Simulated cost (distribution)", ("cost",)), ("Total cost of ownership", ("total_cost",)), @@ -266,6 +282,10 @@ ("bx_life_uncertainty", "time_to_reliability_uncertainty"), ), ("Of the cost rate", ("expected_cost_rate_uncertainty",)), + ( + "Of the net present value", + ("expected_npv_uncertainty",), + ), ], ), ( @@ -382,6 +402,7 @@ ( "mean_availability_uncertainty", "expected_cost_rate_uncertainty", + "expected_npv_uncertainty", ), ), ( diff --git a/repyability/tests/catalogue.py b/repyability/tests/catalogue.py index 06f2ce5c..d13f4b47 100644 --- a/repyability/tests/catalogue.py +++ b/repyability/tests/catalogue.py @@ -18,7 +18,6 @@ MGL, AlphaFactor, BetaFactor, - Calendar, CCFGroup, DegradingNode, FaultTree, @@ -26,6 +25,7 @@ LoadSharingModel, NonRepairable, NonRepairableRBD, + Opportunities, Opportunity, PerfectReliability, PerfectUnreliability, @@ -33,10 +33,13 @@ RepairableRBD, RepeatedNode, RepeatedStandbyNode, + Shocks, StandbyModel, ) +from repyability.maintenance import AgePolicy, Prices, UnitPlan from repyability.rbd import bdd, modular from repyability.rbd._usage import has_at_usage +from repyability.schedule import DutySchedule from repyability.tests.test_performance_equivalence import ( binomial_first, instrument_air, @@ -203,7 +206,7 @@ def ara_process(): Weibull life and half its age taken away at each repair, which the simulation steps with surpyval (a repair surpyval fits that is not Kijima's).""" - return surv.ARA.fit_from_parameters([300.0, 1.5], 0.5) + return surv.ARA.from_params([300.0, 1.5], 0.5) @_fitted_once @@ -337,6 +340,11 @@ def nonrepairable_kinds(): {"a": unit, "b": unit, "c": E([0.002])}, ccf_groups=[CCFGroup(["a", "b"], BetaFactor(0.1, basis="rate"))], ), + "shocks": NonRepairableRBD( + EDGES, + {"a": unit, "b": surv.Weibull.from_params([400.0, 1.5]), **rest}, + ccf_groups=[CCFGroup(["a", "b"], Shocks(1e-3, 0.5, 2e-4))], + ), "fixed": NonRepairableRBD( EDGES, {"a": FIXED(0.1), "b": FIXED(0.2), "c": FIXED(0.05)} ), @@ -663,10 +671,9 @@ def systems_of_every_kind(): def calendar_policy(life): """A calendar policy for ``life`` (#319): shuts every 60 at 2, and a failure at 10.""" - calendar = Calendar( - [Opportunity("shut", 2.0, period=60.0)], failure=10.0, anytime=None - ) - return NonRepairable(life).optimal_calendar_policy(calendar) + shuts = Opportunities([Opportunity("shut", period=60.0)], any_day=False) + part = NonRepairable(life, unplanned_cost=10.0, opportunity_cost=2.0) + return part.optimal_opportunity_policy(shuts) def repairable_kinds(): @@ -689,6 +696,80 @@ def system(a, **options): "block replacement": system( unit(preventive={"interval": 300.0, "policy": "block"}) ), + # One unit's maintenance plan as a node: the node its spec + # gives (UC-63 of the maintenance README). + "a maintenance plan": system( + UnitPlan( + life, + repair, + tasks=(AgePolicy(interval=300.0, cost=4.0),), + prices=Prices(repair=2.0, downtime=1.0), + ) + ), + # A life that is a diagram: a subassembly (a series pair) + # replaced whole at its failure, taken by its functions. + "a life that is a diagram": system( + unit( + reliability=NonRepairableRBD( + [("s", "x"), ("x", "y"), ("y", "t")], + {"x": W([400.0, 2.0]), "y": W([400.0, 2.0])}, + ) + ) + ), + # A plan valued alone, with its own money: its salvage, its + # prices' growth and its retirement (UC-65 of the maintenance + # README), the one node of its diagram. + "a plan valued alone": UnitPlan( + life, + repair, + tasks=(AgePolicy(interval=300.0, cost=4.0),), + prices=Prices(repair=2.0, downtime=1.0), + salvage=3.0, + escalation=1e-3, + retire_at=250.0, + ).diagram(), + # Replaced at the times of a plan, and after the last no more + # (block replacement at any list of times). + "replaced at given times": system( + unit( + preventive={ + "replace_at": [150.0, 400.0, 700.0], + "duration": W([4, 2]), + "cost": 20.0, + }, + repair_cost=5.0, + ), + ), + # Upgraded at a time: its units have another life from then, + # at a capital cost (worked out over a horizon, and simulated). + "upgraded at a time": system( + unit( + upgrade={ + "at": 250.0, + "reliability": W([900, 2.0]), + "cost": 50.0, + }, + repair_cost=5.0, + ), + ), + # Upgraded, and block-replaced before and after (the + # upgrade as one more replacement): over a horizon. + "upgraded at a time, block-replaced": system( + unit( + preventive={ + "policy": "block", + "interval": 200.0, + "cost": 3.0, + "duration": surv.ExactEventTime.from_params([2.0]), + }, + upgrade={ + "at": 300.0, + "reliability": W([900, 2.0]), + "cost": 50.0, + }, + repair_cost=5.0, + ), + ), "block replacement, in no time": system( unit( repairability="instant", @@ -1004,6 +1085,22 @@ def system(a, **options): replace_cost=10.0, ) ), + # A duty plan that changes over time: lives and tasks in + # operating time put on the calendar through it (simulated). + "on a duty plan that changes, maintained by running hours": system( + unit( + duty=DutySchedule( + "hours", (0.0, 40.0, 100.0), (1.0, 0.0, 0.5) + ), + preventive={ + "interval": 75.0, + "basis": "operating", + "duration": E([2.0]), + "cost": 2.0, + }, + replace_cost=10.0, + ) + ), "operated part of the time, tested by running hours": system( unit( duty=0.5, @@ -1049,6 +1146,11 @@ def system(a, **options): unit(priority=1), repair_crews=1, downtime_cost_rate=5.0 ), "enough repair crews": system(unit(), repair_crews=3), + "paid repair crews": system( + unit(priority=1, repair_cost=2.0), + repair_crews=1, + crew_cost_rate=0.5, + ), "too meshed": too_meshed( lambda: RepairableRBD( BRIDGE, {n: unit(repair_cost=2.0) for n in "abcde"} @@ -1128,6 +1230,46 @@ def system(a, **options): CCFGroup(["a", "b", "d"], AlphaFactor([0.95, 0.04, 0.01])) ], ), + "shocks, revealed": RepairableRBD( + EDGES, + { + "a": { + "reliability": W([400.0, 1.5]), + "repairability": E([0.5]), + }, + "b": { + "reliability": W([300.0, 2.0]), + "repairability": W([3.0, 2.0]), + }, + "c": { + "reliability": E([0.002]), + "repairability": E([0.5]), + }, + }, + ccf_groups=[CCFGroup(["a", "b"], Shocks(1e-3, 0.5, 2e-4))], + ), + "shocks, tested": RepairableRBD( + EDGES, + { + **{ + node: { + "reliability": W([600.0, 1.5]), + "repairability": "instant", + "inspection": { + "interval": 100.0, + "coverage": 0.8, + "full_test": 300.0, + }, + } + for node in "ab" + }, + "c": { + "reliability": E([0.002]), + "repairability": E([0.5]), + }, + }, + ccf_groups=[CCFGroup(["a", "b"], Shocks(1e-3, 0.5))], + ), "common cause, Weibull": system( unit(), ccf_groups=[CCFGroup(["a", "b"], BetaFactor(0.1))] ), @@ -1275,6 +1417,102 @@ def system(a, **options): } }, ), + # Outages at given times whose job leaves a block as if 50 + # old (simulated). + "outages restoring to an age": RepairableRBD( + EDGES, + { + "a": unit( + preventive={ + "shutdown": "outage", + "restore_to": 50.0, + "cost": 2.0, + } + ), + "b": unit(), + "c": unit(), + }, + shutdowns={ + "outage": { + "times": [150.0, 400.0, 700.0], + "duration": 8.0, + "scope": ["a"], + } + }, + ), + # Outages at given times, each renewing a block: exact over + # a horizon (no long run). + "outages at given times, renewing": RepairableRBD( + EDGES, + { + "a": unit( + preventive={"shutdown": "outage", "cost": 2.0}, + repair_cost=5.0, + ), + "b": unit(), + "c": unit(), + }, + shutdowns={ + "outage": { + "times": [150.0, 400.0, 700.0], + "duration": 8.0, + "scope": ["a", "c"], + "cost": 30.0, + } + }, + ), + # A block renewed at two shutdowns, a short stop on a period + # and longer outages at given times, each renewal taking its + # own shut's length: exact over a horizon (no long run). + "a block renewed at several shutdowns": RepairableRBD( + EDGES, + { + "a": unit( + preventive={ + "shutdown": ["stop", "outage"], + "cost": 2.0, + }, + repair_cost=5.0, + ), + "b": unit(), + "c": unit(), + }, + shutdowns={ + "stop": {"period": 100.0, "duration": 1.0, "scope": ["a"]}, + "outage": { + "times": [250.0, 640.0], + "duration": 12.0, + "scope": ["a", "c"], + "cost": 30.0, + }, + }, + ), + # Outages at given times that renew a block under age + # replacement if it is old enough then (simulated). + "outages renewing opportunistically": RepairableRBD( + EDGES, + { + "a": unit( + preventive={ + "policy": "age", + "interval": 300.0, + "cost": 2.0, + }, + repair_cost=5.0, + ), + "b": unit(), + "c": unit(), + }, + shutdowns={ + "outage": { + "times": [150.0, 400.0, 700.0], + "duration": 8.0, + "scope": ["a", "b"], + "cost": 30.0, + "opportunistic": {"a": 100.0}, + } + }, + ), "shutdown in no time": RepairableRBD( EDGES, { @@ -1365,6 +1603,22 @@ def system(a, **options): downtime_cost_rate=5.0, capacity={"a": 5.0, "b": 5.0, "c": 10.0}, ), + # One crew, and a call-out crew once two jobs wait. + "a call-out crew": RepairableRBD( + EDGES, + { + node: { + "reliability": E([0.002]), + "repairability": E([0.05]), + "priority": priority, + "repair_cost": 3.0, + } + for node, priority in zip("abc", (1, 0, 0)) + }, + repair_crews=1, + call_out={"when_waiting": 2, "fee": 40.0, "rate": 6.0}, + downtime_cost_rate=5.0, + ), } ) return out diff --git a/repyability/tests/test_analysis_routes.py b/repyability/tests/test_analysis_routes.py index 6872a834..40db47cb 100644 --- a/repyability/tests/test_analysis_routes.py +++ b/repyability/tests/test_analysis_routes.py @@ -111,6 +111,7 @@ def probabilities(rbd): "cs": lambda rbd: rbd.cs(X, 10.0), "time_to_reliability": lambda rbd: rbd.time_to_reliability(0.5), "bx_life": lambda rbd: rbd.bx_life(10), + "qf": lambda rbd: rbd.qf(0.5), "remaining_life": lambda rbd: rbd.remaining_life(0.5, state={}), "mean_residual_life": lambda rbd: rbd.mean_residual_life(state={}), "sf_given_state": lambda rbd: rbd.sf_given_state(X, state={}), @@ -279,6 +280,18 @@ def replaced(rbd): "plan_vs_actual": lambda rbd: rbd.plan_vs_actual( quiet_logs(rbd), 100.0, 200.0, discount_rate=0.01, value_rate=1.0 ), + "npv_distribution": lambda rbd: rbd.npv_distribution( + 200.0, discount_rate=0.01, value_rate=1.0, mc_samples=20, seed=1 + ), + "best_switch_time": lambda rbd: rbd.best_switch_time( + {"a": [[1.0], [2.0]]}, [1.0, 2.0], 200.0, mc_samples=20, seed=1, scan=3 + ), + "least_spend_for_downtime": lambda rbd: rbd.least_spend_for_downtime( + 200.0, 10.0, mc_samples=20, seed=1 + ), + "compare_npv": lambda rbd: rbd.compare_npv( + rbd, 200.0, discount_rate=0.01, value_rate=1.0, mc_samples=20, seed=1 + ), "expected_events_by_window": lambda rbd: rbd.expected_events_by_window( width=100.0, count=2 ), @@ -318,6 +331,16 @@ def replaced(rbd): uncertain(rbd), n_draws=2, seed=1 ) ), + "expected_npv_uncertainty": ( + lambda rbd: rbd.expected_npv_uncertainty( + 200.0, + uncertain(rbd), + discount_rate=0.01, + value_rate=1.0, + n_draws=2, + seed=1, + ) + ), "uncertainty_importance": lambda rbd: rbd.uncertainty_importance( uncertainty=uncertain(rbd) ), @@ -938,8 +961,15 @@ def alone(node): (nonrepairable["nested"], "sf", "refused"), (nonrepairable["nested"], "random", "simulated"), ], - "Common-cause groups: analyses given ages, and the MTTF of a group " - "splitting a failure probability": [ + "Common-cause groups: analyses given ages for members of different " + "ages or a group splitting a failure probability, and the MTTF of " + "such a group": [ + (nonrepairable["common cause by rate"], "sf_given_state", "exact"), + ( + nonrepairable["common cause by rate"], + "remaining_life", + "numerical", + ), (ccf, "sf", "exact"), (ccf, "birnbaum_importance", "exact"), (ccf, "fussell_vesely", "exact"), @@ -975,6 +1005,10 @@ def alone(node): (repairable["too meshed"], "point_availability", "refused"), ], "Common-cause groups in a repairable diagram": [ + (repairable["shocks, revealed"], "availability", "simulated"), + (repairable["shocks, revealed"], "mean_availability", "refused"), + (repairable["shocks, tested"], "availability", "simulated"), + (repairable["shocks, tested"], "point_availability", "refused"), (timed_group, "mean_availability", "numerical"), (timed_group, "birnbaum_importance", "numerical"), (timed_group, "point_availability", "numerical"), @@ -1008,8 +1042,19 @@ def alone(node): (crew, "point_availability", "numerical"), (crew, "expected_cost", "numerical"), (crew, "point_capacity", "numerical"), + (crew, "allocate_redundancy", "exact"), (crew, "availability_allocation", "refused"), (repairable["one repair crew"], "mean_availability", "refused"), + ( + repairable["common cause, one repair crew"], + "mean_availability", + "exact", + ), + ( + repairable["common cause, one repair crew"], + "point_availability", + "numerical", + ), ], "Standby groups (a duty unit and its spares, repaired)": [ (group, "mean_availability", "exact"), @@ -1109,6 +1154,16 @@ def alone(node): "refused", ), ("shutdowns at given times, restoring", "cost", "simulated"), + ( + "outages at given times, renewing", + "expected_npv", + "numerical", + ), + ( + "outages at given times, renewing", + "mean_availability", + "refused", + ), ) ], "Planned against unplanned downtime, and the failures a plan " @@ -1138,6 +1193,11 @@ def alone(node): "maintenance_effect", "simulated", ), + ( + repairable["outages at given times, renewing"], + "maintenance_effect", + "numerical", + ), ], "Replacement on condition by a measured degradation level": [ (repairable["replaced on condition by level"], name, route) diff --git a/repyability/tests/test_api_consistency.py b/repyability/tests/test_api_consistency.py index 23c1c74d..23b4b165 100644 --- a/repyability/tests/test_api_consistency.py +++ b/repyability/tests/test_api_consistency.py @@ -27,7 +27,7 @@ from repyability.rbd.ccf import with_parameters from repyability.rbd.uncertainty import draw_ccf_models from repyability.utils import deprecation -from repyability.utils.deprecation import NEXT_REMOVAL +from repyability.utils.deprecation import NEXT_REMOVAL, REMOVED_IN_0_22 W, E = surv.Weibull.from_params, surv.Exponential.from_params F = FixedEventProbability.from_params @@ -192,12 +192,15 @@ def test_the_spares_demand_values_are_properties(): assert demand.std == pytest.approx(np.sqrt(10.0), rel=1e-4) -def test_what_0_19_deprecates_goes_in_0_20(): - # 0.19 and 0.19.1 deprecate nothing; a deprecation in 0.20's - # development goes in NEXT_REMOVAL (0.20), and this fails as a - # reminder once the version reaches it. +def test_what_0_20_deprecates_goes_in_0_21(): + # 0.19 deprecated nothing, so 0.20 removes nothing. What 0.20 + # deprecates goes in NEXT_REMOVAL (0.21; test_opportunities.py and + # test_exact_or_horizon.py remind of each), and a deprecation in + # 0.21's development in REMOVED_IN_0_22. This fails as a reminder + # once the version reaches the next removal. version = tuple(map(int, __version__.split("."))) assert version < tuple(map(int, NEXT_REMOVAL.split("."))) + assert NEXT_REMOVAL == "0.21" and REMOVED_IN_0_22 == "0.22" def test_a_deprecation_warns_until_the_next_removal(): diff --git a/repyability/tests/test_bdd_core.py b/repyability/tests/test_bdd_core.py index 1707df6f..b78283d1 100644 --- a/repyability/tests/test_bdd_core.py +++ b/repyability/tests/test_bdd_core.py @@ -311,12 +311,89 @@ def test_the_orders_are_topological(): number = {**index, "s": -1, "t": -2} p = {number[n]: {number[u] for u in us} for n, us in pred.items()} s = {number[n]: {number[u] for u in us} for n, us in succ.items()} - for sequence in ( - bdd.order(index.values(), p, s, -1, -2), - bdd._breadth_first(sorted(index.values()), p, s, -1), - bdd._greedy(sorted(index.values()), p, s, -1, -2), - ): + candidates = [ + candidate(sorted(index.values()), p, s, -1, -2) + for candidate in bdd.CANDIDATES.values() + ] + chosen = bdd.order(index.values(), p, s, -1, -2) + costs = [bdd._cost(c, p, s, -1, -2) for c in candidates] + # The cheapest is kept, the earliest of equals. + assert chosen == candidates[costs.index(min(costs))] + for sequence in candidates: assert sorted(sequence) == sorted(index.values()) position = {v: i for i, v in enumerate(sequence)} for v in sequence: assert all(u == -1 or position[u] < position[v] for u in p[v]) + + +def meshed(n, seed, p=0.2): + """A random acyclic diagram of ``n`` nodes, each joined to each later + one with probability ``p``.""" + rng = np.random.default_rng(seed) + edges = { + (i, j) for i in range(n) for j in range(i + 1, n) if rng.random() < p + } + for i in range(n): + if not any(a == i for a, _ in edges): + edges.add((i, "t")) + if not any(b == i for _, b in edges): + edges.add(("s", i)) + return sorted(edges, key=str) + + +@pytest.mark.parametrize("seed", range(4)) +def test_every_order_decides_the_same_structure(seed, monkeypatch): + # A meshed core built in each candidate order: other plans, one + # structure (its probabilities, gradients, path and cut sets). + rng = np.random.default_rng(seed) + edges = meshed(18, seed) + nodes = sorted({n for e in edges for n in e} - {"s", "t"}) + k = {n: 2 for n in nodes[seed::5]} + rbd = RBD(edges, k=k, on_infeasible_rbd="ignore") + p = {n: float(rng.uniform(0.2, 0.95)) for n in nodes} + q = {n: 1.0 - v for n, v in p.items()} + plans, results = set(), [] + for name, candidate in bdd.CANDIDATES.items(): + monkeypatch.setattr(bdd, "CANDIDATES", {name: candidate}) + graph = decompose(rbd.G, "s", "t", core="bdd") + assert graph.from_graph + plans.add(repr(graph.core_plan())) + results.append( + ( + graph.value_and_gradient(p, q), + graph.path_sets(), + graph.cut_sets(), + ) + ) + monkeypatch.undo() + assert len(plans) > 1 + (works, fails, gradient), paths, cuts = results[0] + for (w, f, g), other_paths, other_cuts in results[1:]: + assert w == pytest.approx(works, rel=1e-15, abs=1e-15) + assert f == pytest.approx(fails, rel=1e-15, abs=1e-15) + assert set(g) == set(gradient) + for n in g: + assert g[n] == pytest.approx(gradient[n], rel=1e-13, abs=1e-15) + assert other_paths == paths and other_cuts == cuts + + +def test_looking_ahead_narrows_the_frontier(): + # On meshed diagrams the order that looks a vertex ahead is never + # costlier than the plain greedy one here, and is cheaper on most. + cheaper = 0 + for seed in range(2, 8): + rbd = RBD(meshed(50, seed, 0.15)) + reduction = modular._Reduction(rbd.G, "s", "t") + reduction.run() + args = ( + sorted(reduction.alive), + reduction.pred, + reduction.succ, + modular._SOURCE, + modular._SINK, + ) + plain = bdd._cost(bdd._greedy(*args), *args[1:]) + ahead = bdd._cost(bdd._look_ahead(*args), *args[1:]) + assert ahead <= plain + cheaper += ahead < plain + assert cheaper >= 4 diff --git a/repyability/tests/test_call_out_crew.py b/repyability/tests/test_call_out_crew.py new file mode 100644 index 00000000..5130d7de --- /dev/null +++ b/repyability/tests/test_call_out_crew.py @@ -0,0 +1,516 @@ +"""A call-out crew (``call_out``): one more repair crew that comes when +``when_waiting`` jobs wait, at a fee each time and a rate while engaged, +and leaves at the first end of a job that leaves a crew with no waiting +job to take. + +The crews' Markov chain has it (``_crew_chain``) and the Python event +loop's queue follows the same rule (``_events._Crews``). Here: the rule +itself, the chain against states solved by hand and against the +simulation, the costs in the long run, over time and discounted (against +the transient solution worked out with a matrix exponential), and what +refuses.""" + +import json +import math +from fractions import Fraction + +import numpy as np +import pytest +import surpyval as surv +from scipy.linalg import expm + +from repyability import RepairableRBD +from repyability.rbd import _compiled, _crew_chain, _event_loop +from repyability.rbd import routes as r +from repyability.rbd._events import Event, _Crews + +E = surv.Exponential.from_params +LAM, MU = 0.02, 0.1 +FEE, RATE = 40.0, 6.0 + + +def parallel(n): + nodes = "abcdef"[:n] + return [("s", x) for x in nodes] + [(x, "t") for x in nodes] + + +def three(call_out=None, crews=1, **options): + """Three alike units in parallel, one repair crew.""" + return RepairableRBD( + parallel(3), + { + node: { + "reliability": E([LAM]), + "repairability": E([MU]), + "repair_cost": 3.0, + } + for node in "abc" + }, + repair_crews=crews, + call_out=call_out, + downtime_cost_rate=5.0, + **options, + ) + + +def contract(k=2, fee=FEE, rate=RATE): + return {"when_waiting": k, "fee": fee, "rate": rate} + + +def by_hand(): + """``three(contract(2))`` solved by hand. Its states, by the jobs + under repair and waiting: A (0, 0), B (1, 0), C (1, 1), D (2, 1: the + third failure made two wait, the call-out crew took one), F (2, 0: + still engaged, until a job ends with none waiting). Balance, with + ``rho = lam / mu``: ``B = 3 rho A``, ``C = 2 rho B / (1 + rho)``, + ``F = rho C / 2``, ``D = (rho + 2) F / 2``.""" + lam, mu = ( + Fraction(LAM).limit_denominator(), + Fraction(MU).limit_denominator(), + ) + rho = lam / mu + a = Fraction(1) + b = 3 * rho * a + c = 2 * rho * b / (1 + rho) + f = rho * c / 2 + d = (rho + 2) * f / 2 + total = a + b + c + d + f + return { + "availability": float(1 - d / total), + "calls": float(lam * c / total), + "engaged": float((d + f) / total), + } + + +def generator(): + """The five states' generator, in the order A, B, C, D, F, the rate at + which the call-out crew is called in each, and where it is engaged.""" + q = np.zeros((5, 5)) + q[0, 1] = 3 * LAM + q[1, 0], q[1, 2] = MU, 2 * LAM + q[2, 1], q[2, 3] = MU, LAM + q[3, 4] = 2 * MU + q[4, 3], q[4, 1] = LAM, 2 * MU + q -= np.diag(q.sum(axis=1)) + calls = np.array([0.0, 0.0, LAM, 0.0, 0.0]) + engaged = np.array([0.0, 0.0, 0.0, 1.0, 1.0]) + return q, calls, engaged + + +# -- the rule --------------------------------------------------------------- + + +def test_the_queue_calls_the_crew_and_lets_it_go(): + crews = _Crews(1, "abcd", {"c": 1.0}, call_when=2) + + def due(node, t, length): + return crews.request(node, t, Event(t + length, node, True)) + + assert due("a", 0.0, 10.0).time == 10.0 # the crew's + assert due("b", 1.0, 5.0) is None and crews.call(1.0) is None + assert due("c", 2.0, 4.0) is None + # Two wait: the call-out crew comes, for the job of the highest + # priority, which never waited. + node, wait, ends = crews.call(2.0) + assert (node, wait, ends.time) == ("c", 0.0, 6.0) + assert crews.engaged and crews.calls == 1 + # One crew only: more waiting jobs call no other. + assert due("d", 3.0, 1.0) is None and crews.call(3.0) is None + # A job ends with jobs waiting: its crew takes the next (first due). + node, wait, ends = crews.release("c", 6.0) + assert (node, wait, ends.time) == ("b", 5.0, 11.0) + node, wait, ends = crews.release("a", 10.0) + assert (node, wait, ends.time) == ("d", 7.0, 11.0) + assert crews.engaged + # The first end of a job with none waiting: the call-out crew goes, + # and the crew that came free has the job left. + assert crews.release("b", 11.0) is None + assert not crews.engaged and crews.free == 0 + assert crews.close(20.0) == (1, 9.0) + assert crews.release("d", 11.0) is None and crews.free == 1 + + +def test_time_engaged_is_closed_at_the_end_of_the_window(): + crews = _Crews(1, "ab", {}, call_when=1) + crews.request("a", 0.0, Event(50.0, "a", True)) + assert crews.request("b", 4.0, Event(60.0, "b", True)) is None + assert crews.call(4.0)[0] == "b" + assert crews.close(10.0) == (1, 6.0) + + +# -- the chain -------------------------------------------------------------- + + +def test_the_chain_has_the_states_solved_by_hand(): + rbd = three(contract(2)) + states = rbd.crew_states() + assert len(states.probabilities) == 1 + 3 + 6 + 3 + 3 + hand = by_hand() + p = states.probabilities + assert rbd.mean_availability() == pytest.approx( + hand["availability"], rel=1e-13 + ) + assert float(p @ states.call_out_rate) == pytest.approx( + hand["calls"], rel=1e-13 + ) + assert float(p @ states.call_out_engaged) == pytest.approx( + hand["engaged"], rel=1e-13 + ) + assert rbd.expected_cost_rate() - three( + contract(2, 0.0, 0.0) + ).expected_cost_rate() == pytest.approx( + FEE * hand["calls"] + RATE * hand["engaged"], rel=1e-12 + ) + + +def test_two_units_called_at_the_first_wait_fail_independently(): + # Each failure has a crew at once, so each unit is down lam / (lam + + # mu) of the time on its own: the call-out crew is engaged while both + # are down, and called when one fails with the other down. + la, lb, mu = 0.03, 0.01, 0.2 + rbd = RepairableRBD( + parallel(2), + { + "a": {"reliability": E([la]), "repairability": E([mu])}, + "b": {"reliability": E([lb]), "repairability": E([mu])}, + }, + repair_crews=1, + call_out={"when_waiting": 1, "fee": FEE, "rate": RATE}, + ) + qa, qb = la / (la + mu), lb / (lb + mu) + assert rbd.mean_availability() == pytest.approx(1 - qa * qb, rel=1e-13) + calls = qa * (1 - qb) * lb + qb * (1 - qa) * la + assert rbd.expected_cost_rate() == pytest.approx( + FEE * calls + RATE * qa * qb, rel=1e-13 + ) + + +def test_a_crew_never_called_changes_nothing(): + # Three units, one under repair: two wait at most. + plain, never = three(), three(contract(3)) + assert never.mean_availability() == plain.mean_availability() + assert never.expected_cost_rate() == plain.expected_cost_rate() + windows = np.array([5.0, 50.0, 500.0]) + for rate in (0.0, 0.01): + np.testing.assert_array_equal( + never.expected_cost(windows, discount_rate=rate).mean, + plain.expected_cost(windows, discount_rate=rate).mean, + ) + np.testing.assert_array_equal( + never.point_availability(windows), plain.point_availability(windows) + ) + a = never.cost(200.0, mc_samples=50, seed=3, control_variate=False) + b = plain.cost(200.0, mc_samples=50, seed=3, control_variate=False) + assert a.mean == b.mean and a.by_category == b.by_category + + +def test_called_at_the_first_wait_it_is_a_crew_more_to_the_units(): + one, two = three(contract(1, 0.0, 0.0)), three(crews=2) + assert one.mean_availability() == pytest.approx( + two.mean_availability(), rel=1e-14 + ) + t = np.array([3.0, 30.0, 300.0]) + np.testing.assert_allclose( + one.point_availability(t), two.point_availability(t), rtol=1e-12 + ) + assert one.mean_time_to_first_failure() == pytest.approx( + two.mean_time_to_first_failure(), rel=1e-12 + ) + a = one.availability(300.0, mc_samples=40, seed=5, control_variate=False) + b = two.availability(300.0, mc_samples=40, seed=5, control_variate=False) + assert a.sample_mean_availability == b.sample_mean_availability + + +def test_the_states_are_counted_as_they_are_built(): + priorities, instant = [1.0, 0.0, 0.0, 0.0, 2.0], [False] * 4 + [True] + for crews in (1, 2): + for when in (1, 2, 3): + built = _crew_chain.solve( + list("abcde"), + [0.1] * 5, + [1.0] * 4 + [math.inf], + priorities, + crews, + when, + ) + assert _crew_chain.state_count( + priorities, instant, crews, when + ) == len(built.states) + assert built.probabilities.sum() == pytest.approx(1.0) + # Engaged exactly with a job more than the crews under repair. + assert [len(s[0]) > crews for s in built.states] == list( + built.engaged + ) + + +def test_too_many_states_are_refused(): + rbd = RepairableRBD( + parallel(6) + [("s", "g"), ("g", "t"), ("s", "h"), ("h", "t")], + { + node: {"reliability": E([LAM]), "repairability": E([MU])} + for node in "abcdefgh" + }, + repair_crews=1, + call_out={"when_waiting": 7}, + ) + with pytest.raises(NotImplementedError, match="more than the 15,000"): + rbd.mean_availability() + + +# -- over time, and discounted ------------------------------------------------ + + +def test_the_costs_over_time_are_the_transient_solution_s(): + q, calls, engaged = generator() + cost = FEE * calls + RATE * engaged + start = np.array([1.0, 0.0, 0.0, 0.0, 0.0]) + paid = three(contract(2)) + free = three(contract(2, 0.0, 0.0)) + windows = np.array([4.0, 40.0, 400.0]) + for rate in (0.0, 0.03): + # The integral of exp(-r t) p(t) cost from 0 to T, by the matrix + # exponential of [[Q - r, cost], [0, 0]]. + block = np.zeros((6, 6)) + block[:5, :5] = q - rate * np.eye(5) + block[:5, 5] = cost + want = [float((start @ expm(block * T)[:5, 5])) for T in windows] + got = paid.expected_cost(windows, discount_rate=rate) + np.testing.assert_allclose( + got.by_category["crews"], want, rtol=1e-6 if rate else 1e-10 + ) + none = free.expected_cost(windows, discount_rate=rate) + np.testing.assert_allclose(none.by_category["crews"], 0.0, atol=0.0) + np.testing.assert_allclose( + got.mean - none.mean, + want, + rtol=1e-6 if rate else 1e-10, + ) + + +def test_salaries_and_the_call_out_crew_share_the_category(): + T, rate, salary = 100.0, 0.02, 0.5 + both = three(contract(2), crew_cost_rate=salary) + called = three(contract(2)) + for r_ in (0.0, rate): + salaries = salary * T if not r_ else salary * -math.expm1(-r_ * T) / r_ + assert both.expected_cost(T, discount_rate=r_).by_category[ + "crews" + ] == pytest.approx( + called.expected_cost(T, discount_rate=r_).by_category["crews"] + + salaries, + rel=1e-12, + ) + assert both.expected_cost_rate() == pytest.approx( + called.expected_cost_rate() + salary, rel=1e-13 + ) + + +def test_the_contract_s_value_is_the_difference_of_two_npvs(): + T, rate = 400.0, 0.01 + without, with_it = three(), three(contract(2)) + a = without.expected_npv(T, discount_rate=rate, periods=4) + b = with_it.expected_npv(T, discount_rate=rate, periods=4) + crews = sum( + row["present_value"] + for row in b.cash_flows + if row["category"] == "crews" + ) + assert -crews == pytest.approx( + with_it.expected_cost(T, discount_rate=rate).by_category["crews"], + rel=1e-9, + ) + # It costs its fees and rate, and saves down time: the system's is + # shorter with it. + down = [ + abs(result.cost_by_category["system_downtime"]) for result in (a, b) + ] + assert down[1] < down[0] + assert b.npv - a.npv == pytest.approx( + -( + with_it.expected_cost(T, discount_rate=rate).mean + - without.expected_cost(T, discount_rate=rate).mean + ), + rel=1e-9, + ) + + +# -- the simulation ----------------------------------------------------------- + + +def mixed(call_out): + """Four units with priorities and an instant repair, two crews.""" + return RepairableRBD( + parallel(4), + { + "a": { + "reliability": E([0.05]), + "repairability": E([0.2]), + "priority": 2, + "repair_cost": 4.0, + }, + "b": {"reliability": E([0.08]), "repairability": E([0.1])}, + "c": { + "reliability": E([0.03]), + "repairability": "instant", + "priority": 1, + }, + "d": {"reliability": E([0.06]), "repairability": E([0.15])}, + }, + k={"t": 2}, + repair_crews=2, + call_out=call_out, + downtime_cost_rate=7.0, + ) + + +@pytest.mark.parametrize( + "build, call_out", + [ + (three, contract(2)), + (three, contract(1, FEE, 0.0)), + (three, contract(2, 0.0, RATE)), + (mixed, contract(1)), + (mixed, contract(2)), + ], +) +def test_the_simulation_agrees_with_the_chain(build, call_out): + T, n = 300.0, 4000 + rbd = build(call_out) + exact = rbd.expected_cost(T) + run = rbd.availability( + T, mc_samples=n, seed=20261120, control_variate=False + ) + cost = run.cost + assert cost.by_category["crews"] > 0.0 + assert abs(cost.sample_mean - exact.mean) < 3.5 * cost.mean_se + # The crews' category alone: the call-outs (fee) and the time engaged + # (rate), to within the same error (the whole cost's bounds it: the + # other categories vary with it). + assert cost.by_category["crews"] == pytest.approx( + exact.by_category["crews"], abs=3.5 * cost.mean_se + ) + # The system's time down, against each simulation's. + down = T - np.asarray(run.uptimes) + error = down.std(ddof=1) / math.sqrt(n) + assert abs(down.mean() - rbd.expected_events(T).system_downtime) < ( + 3.5 * error + ) + + +def test_a_run_s_default_means_have_the_call_out_crew(): + # The exact means (the control variates) and the conditional run's. + rbd = three(contract(2)) + T = 200.0 + cost = rbd.cost(T, mc_samples=200, seed=4) + assert cost.mean == pytest.approx(rbd.expected_cost(T).mean, rel=1e-9) + assert cost.by_category["crews"] == pytest.approx( + rbd.expected_cost(T).by_category["crews"], rel=1e-9 + ) + + +def test_units_of_a_standby_group_call_the_crew_in_the_simulation_only(): + rbd = RepairableRBD( + [("s", "g"), ("g", "t")], + { + "g": { + "reliability": E([LAM]), + "repairability": E([MU]), + "standby": {"units": 3, "k": 1}, + } + }, + repair_crews=1, + call_out=contract(1), + ) + with pytest.raises(NotImplementedError, match="standby group"): + rbd.mean_availability() + report = rbd.analysis_routes() + assert report["mean_availability"].route == r.REFUSED + assert report["availability"].route == r.SIMULATED + run = rbd.availability(500.0, mc_samples=200, seed=2) + assert run.cost.by_category["crews"] > 0.0 + # A crew at once for every unit but the third: as two crews, but for + # the cost. + two = RepairableRBD( + [("s", "g"), ("g", "t")], + { + "g": { + "reliability": E([LAM]), + "repairability": E([MU]), + "standby": {"units": 3, "k": 1}, + } + }, + repair_crews=2, + ) + assert ( + run.sample_mean_availability + == two.availability( + 500.0, mc_samples=200, seed=2 + ).sample_mean_availability + ) + + +# -- what it is given, saved and refused -------------------------------------- + + +@pytest.mark.parametrize( + "call_out, match", + [ + (3, "must be a dict"), + ({"fee": 1.0}, "when_waiting"), + ({"when_waiting": 1, "price": 1.0}, "when_waiting"), + ({"when_waiting": 0}, "whole number, at least 1"), + ({"when_waiting": 1.5}, "whole number"), + ({"when_waiting": 1, "fee": -1.0}, "non-negative"), + ({"when_waiting": 1, "rate": "2"}, "must be a number"), + ], +) +def test_a_call_out_that_is_not_one_is_refused(call_out, match): + with pytest.raises(ValueError, match=match): + three(call_out) + + +def test_it_needs_crews_to_wait_for(): + with pytest.raises(ValueError, match="repair_crews is None"): + three(contract(), crews=None) + # With a crew for every job none waits: it is never called, and + # costs nothing. + enough = three(contract(1), crews=3) + assert enough.expected_cost_rate() == three(crews=3).expected_cost_rate() + assert not RepairableRBD( + parallel(2), + { + node: {"reliability": E([LAM]), "repairability": E([MU])} + for node in "ab" + }, + repair_crews=2, + call_out=contract(1), + ).has_costs + + +def test_it_is_saved_and_loaded(): + rbd = three(contract(2, 12.5, 0.75), crew_cost_rate=0.25) + saved = json.loads(json.dumps(rbd.to_dict())) + assert saved["call_out"] == {"when_waiting": 2, "fee": 12.5, "rate": 0.75} + loaded = RepairableRBD.from_dict(saved) + assert loaded.call_out == rbd.call_out + assert loaded.expected_cost_rate() == rbd.expected_cost_rate() + assert "call_out" not in three().to_dict() + + +def test_the_compiled_engine_hands_it_to_python(): + rbd = three(contract(2)) + plan = _event_loop._stream_plan(rbd, 1.0, 0, False)[0] + assert _compiled.unsupported(rbd, plan, None, numba=True) == ( + "a call-out crew" + ) + assert _compiled.unsupported(three(), plan, None, numba=True) is None + assert rbd.analysis_routes()["availability"].engine == "python" + + +def test_runs_are_not_priced_from_histories_that_do_not_record_it(): + rbd = three(contract(2)) + with pytest.raises(NotImplementedError, match="call-out crew"): + rbd.npv_distribution(100.0, mc_samples=10, seed=1) + assert rbd.analysis_routes()["npv_distribution"].route == r.REFUSED + # Unpriced, it only changes the histories. + three(contract(2, 0.0, 0.0)).npv_distribution(100.0, mc_samples=10, seed=1) diff --git a/repyability/tests/test_catalogue.py b/repyability/tests/test_catalogue.py index 88309ac6..b6da2de8 100644 --- a/repyability/tests/test_catalogue.py +++ b/repyability/tests/test_catalogue.py @@ -37,6 +37,7 @@ RepeatedStandbyNode, StandbyModel, ) +from repyability.maintenance import UnitPlan from repyability.rbd import routes from repyability.rbd._bayesian_life import as_life from repyability.rbd._degradation import is_degradation @@ -58,7 +59,11 @@ "AlphaFactor", "AnalysisRoute", "AnalysisRoutes", + # A contract's terms on availability: an input to npv_distribution. + "AvailabilityContract", "BetaFactor", + # A common-cause group's model: shocks at a rate of their own. + "Shocks", # A calendar of opportunities, priced (#319): a calendar policy's input. "Calendar", "CCFGroup", @@ -72,6 +77,8 @@ "Network", "NodeState", "Opportunity", + # Opportunities collected, in model time or on dates: a policy's input. + "Opportunities", "PhasedMission", "MissionPhase", "BlockSetting", @@ -94,6 +101,18 @@ "SimulationChunk", "Timeline", "Timelines", + "ValueSchedule", + # A maintenance plan's parts (the plan itself is a node). + "AgePolicy", + "AtShutdown", + "BlockPolicy", + "CalendarReplacement", + "ConditionPolicy", + "ImperfectRepair", + "Inspection", + "Prices", + "Restoration", + "Upgrade", } #: The node classes a NonRepairableRBD takes as a node's model. NONREPAIRABLE_NODES = { @@ -112,6 +131,7 @@ #: The node classes a RepairableRBD takes, as a component or its life. REPAIRABLE_NODES = { DegradingNode, + UnitPlan, NonRepairable, PerfectReliability, PosteriorPredictive, @@ -229,6 +249,9 @@ def nonrepairable_kinds(rbd, models, options) -> set: def repairable_kinds(rbd, components, options) -> set: found = set() for component in components.values(): + if isinstance(component, UnitPlan): + found.add("UnitPlan") + component = component.spec() if not isinstance(component, dict): found |= model_kinds(component) continue @@ -256,6 +279,10 @@ def repairable_kinds(rbd, components, options) -> set: found.add("capacities") if options.get("downtime_cost_rate"): found.add("downtime_cost_rate") + if options.get("crew_cost_rate"): + found.add("crew_cost_rate") + if options.get("call_out"): + found.add("call_out") if options.get("repair_crews") is not None: found.add("repair crews") if any(isinstance(c, RepairableRBD) for c in components.values()): @@ -292,6 +319,7 @@ def required_repairable() -> set: | {"repairability 'instant'"} | {"a k-out-of-n vote", "capacities", "downtime_cost_rate"} | {"repair crews", "repair crews around a nested RepairableRBD"} + | {"crew_cost_rate", "call_out"} | { "BetaFactor common cause, probability basis", "MGL common cause, probability basis", diff --git a/repyability/tests/test_ccf.py b/repyability/tests/test_ccf.py index 665690b4..c7cc2b72 100644 --- a/repyability/tests/test_ccf.py +++ b/repyability/tests/test_ccf.py @@ -587,7 +587,9 @@ def test_alpha_factor_validation(): assert AlphaFactor(ALPHAS).required_group_size() == 3 with pytest.raises(ValueError, match="members"): CCFGroup(["a", "b"], AlphaFactor(ALPHAS)) - with pytest.raises(ValueError, match="BetaFactor, MGL or AlphaFactor"): + with pytest.raises( + ValueError, match="BetaFactor, MGL, AlphaFactor or Shocks" + ): CCFGroup(["a", "b"], "alpha") diff --git a/repyability/tests/test_ccf_repairable_modules.py b/repyability/tests/test_ccf_repairable_modules.py index f8b4c4ff..5e137e8d 100644 --- a/repyability/tests/test_ccf_repairable_modules.py +++ b/repyability/tests/test_ccf_repairable_modules.py @@ -558,21 +558,21 @@ def test_the_split_refuses_before_building_it(monkeypatch): @pytest.mark.parametrize("basis", ["probability", "rate"]) -def test_groups_with_limited_crews_refuse_rather_than_drop_the_groups(basis): - # The crews' chain does not take common causes in: the long-run values - # refused only over time, and gave the system without its groups in - # the long run; then each component's own, which a shared failure - # changes too, as one member waits for the crew (#251). +def test_groups_with_limited_crews_are_in_the_crews_chain(basis): + # A shared failure makes one member wait for the crew, so neither the + # groups' own chains nor the crews' chain without the groups has the + # values: the long run once gave the system without its groups, then + # refused, and the crews' chain now takes the groups in (#251). units = {n: revealed(1e-3, 0.1) for n in "abc"} edges = [("s", "a"), ("s", "b"), ("a", "c"), ("b", "c"), ("c", "t")] + options = {"repair_crews": 1, "downtime_cost_rate": 5.0} rbd = RepairableRBD( edges, units, ccf_groups=[CCFGroup(["a", "b"], BetaFactor(0.1, basis=basis))], - repair_crews=1, - downtime_cost_rate=5.0, + **options, ) - message = "crews' Markov chain does not take common causes in" + plain = RepairableRBD(edges, units, **options) for method in ( "mean_availability", "mean_unavailability", @@ -587,14 +587,16 @@ def test_groups_with_limited_crews_refuse_rather_than_drop_the_groups(basis): "barlow_proschan_importance", "parameter_sensitivity", "expected_cost_rate", - "capacity_distribution", "point_availability", "mission_availability", ): args = (100.0,) if method.startswith(("point", "mission")) else () - with pytest.raises(NotImplementedError, match=message): - getattr(rbd, method)(*args) - assert rbd.analysis_routes()[method].route == "refused", method + got = getattr(rbd, method)(*args) + assert rbd.analysis_routes()[method].route != "refused", method + if method != "parameter_sensitivity": + assert got != getattr(plain, method)(*args), method + # The shared cause makes the pair fail together more often. + assert rbd.mean_unavailability() > plain.mean_unavailability() # The simulations take both. assert rbd.analysis_routes()["availability"].route == "simulated" rbd.availability(100.0, mc_samples=20, seed=1) diff --git a/repyability/tests/test_ccf_same_age.py b/repyability/tests/test_ccf_same_age.py new file mode 100644 index 00000000..6ee52fb2 --- /dev/null +++ b/repyability/tests/test_ccf_same_age.py @@ -0,0 +1,338 @@ +"""Common causes for wear-out lives: a group splitting the failure rate +at its members' one age, against the same model drawn as nodes (each +member's own causes with survival ``R^(1 - beta)``, the shared cause one +node in series with ``R^beta``), and a shock at a constant rate as a node +in series with members of different ages, against its closed form.""" + +import numpy as np +import pytest +import surpyval as surv + +from repyability import ( + MGL, + BetaFactor, + CCFGroup, + NodeState, + NonRepairableRBD, +) + +PARALLEL = [("s", "p1"), ("s", "p2"), ("p1", "t"), ("p2", "t")] +WITH_SHARED = [ + ("s", "p1"), + ("s", "p2"), + ("p1", "shared"), + ("p2", "shared"), + ("shared", "t"), +] +X = np.array([0.0, 500.0, 2000.0, 6000.0, 15000.0]) + + +class Share: + """The life whose cumulative hazard is ``share`` times a model's: + survival ``R ** share``, written from the cumulative hazard.""" + + def __init__(self, model, share): + self.model, self.share = model, share + + def Hf(self, x): + return self.share * self.model.Hf(x) + + def sf(self, x): + return np.exp(-self.Hf(x)) + + def ff(self, x): + return -np.expm1(-self.Hf(x)) + + +def group_of(model, beta): + return NonRepairableRBD( + PARALLEL, + {"p1": model, "p2": model}, + ccf_groups=[CCFGroup(["p1", "p2"], BetaFactor(beta, basis="rate"))], + ) + + +def drawn(own, shared): + return NonRepairableRBD( + WITH_SHARED, {"p1": own, "p2": own, "shared": shared} + ) + + +def weibull_split(alpha, k, beta): + """The Weibull's two parts in closed form: the same shape, the scale + times ``share ** (-1 / k)``.""" + return ( + surv.Weibull.from_params([alpha * (1 - beta) ** (-1 / k), k]), + surv.Weibull.from_params([alpha * beta ** (-1 / k), k]), + ) + + +def test_exponential_members_have_no_age(): + """A constant hazard's share is a shock at a constant rate, so the + group at any common age is the group from new, and both are the pair + of rate ``(1 - beta) lam`` in series with one of rate ``beta lam``.""" + lam, beta = 1e-4, 0.1 + group = group_of(surv.Exponential.from_params([lam]), beta) + new = group.sf(X) + r = np.exp(-(1 - beta) * lam * X) + closed = np.exp(-beta * lam * X) * (1 - (1 - r) ** 2) + assert new == pytest.approx(closed, rel=1e-12, abs=0) + for age in (0.0, 700.0, 40000.0): + aged = group.sf_given_state(X, {"p1": age, "p2": age}) + assert aged == pytest.approx(new, rel=1e-12, abs=0) + by_nodes = drawn( + surv.Exponential.from_params([(1 - beta) * lam]), + surv.Exponential.from_params([beta * lam]), + ) + assert by_nodes.sf(X) == pytest.approx(new, rel=1e-12, abs=0) + + +@pytest.mark.parametrize("beta", [0.05, 0.3]) +@pytest.mark.parametrize("age", [0.0, 1500.0, 9000.0]) +def test_weibull_members_against_the_split_drawn_as_nodes(beta, age): + alpha, k = 8000.0, 2.5 + group = group_of(surv.Weibull.from_params([alpha, k]), beta) + by_nodes = drawn(*weibull_split(alpha, k, beta)) + state = {"p1": age, "p2": age} + everything = {**state, "shared": age} + assert group.sf(X) == pytest.approx(by_nodes.sf(X), rel=1e-12, abs=0) + assert group.sf_given_state(X, state) == pytest.approx( + by_nodes.sf_given_state(X, everything), rel=1e-12, abs=0 + ) + assert group.remaining_life(0.9, state) == pytest.approx( + by_nodes.remaining_life(0.9, everything), rel=1e-9 + ) + assert group.mean_residual_life(state) == pytest.approx( + by_nodes.mean_residual_life(everything), rel=1e-9 + ) + + +@pytest.mark.parametrize("age", [0.0, 3000.0]) +def test_lognormal_members_against_the_split_drawn_as_nodes(age): + """A life with no closed form for ``R ** beta``.""" + life, beta = surv.LogNormal.from_params([8.5, 0.6]), 0.2 + group = group_of(life, beta) + by_nodes = drawn(Share(life, 1 - beta), Share(life, beta)) + state = {"p1": age, "p2": age} + everything = {**state, "shared": age} + assert group.sf_given_state(X, state) == pytest.approx( + by_nodes.sf_given_state(X, everything), rel=1e-12, abs=0 + ) + assert group.mean_residual_life(state) == pytest.approx( + by_nodes.mean_residual_life(everything), rel=1e-9 + ) + + +def test_the_common_age_against_its_closed_form(): + """``R_s(x | a) (1 - (1 - r(x | a))^2)``, each part's survival from + age ``a`` its share of the members' cumulative hazard from then.""" + life, beta, age = surv.LogNormal.from_params([8.5, 0.6]), 0.2, 3000.0 + H = life.Hf(age + X) - life.Hf(age) + r, shared = np.exp(-(1 - beta) * H), np.exp(-beta * H) + closed = shared * (1 - (1 - r) ** 2) + group = group_of(life, beta) + state = {"p1": NodeState(age=age), "p2": NodeState(age=age)} + assert group.sf_given_state(X, state) == pytest.approx( + closed, rel=1e-12, abs=0 + ) + # A member works while neither its own causes nor the shared one has + # struck; with it failed, the other works with probability + # P(other works, it failed) / P(it failed). + importance = group.importances_given_state(X[1:], state) + r, shared = r[1:], shared[1:] + given_failed = shared * r * (1 - r) / (1 - shared * r) + assert importance["birnbaum"]["p1"] == pytest.approx( + 1 - given_failed, rel=1e-10 + ) + assert importance["birnbaum"]["p2"] == pytest.approx( + importance["birnbaum"]["p1"], rel=1e-12 + ) + + +def test_an_mgl_group_by_rate_at_a_common_age(): + """Each specific set's cause takes its share of the members' hazard + from their age on: the group from new at the conditional + probabilities.""" + life = surv.Weibull.from_params([8000.0, 2.5]) + names = ["a", "b", "c"] + edges = [("s", n) for n in names] + [(n, "t") for n in names] + model = MGL(0.1, 0.3, basis="rate") + rbd = NonRepairableRBD( + edges, + {n: life for n in names}, + k={"t": 2}, + ccf_groups=[CCFGroup(names, model)], + ) + age = 4000.0 + H = life.Hf(age + X) - life.Hf(age) + own, causes = model._causes(names) + # Sum over which causes have struck: the system works with two of + # the three members up. + total = np.zeros_like(H) + for mask in range(2 ** len(causes)): + weight = np.ones_like(H) + struck = set() + for j, (members, c) in enumerate(causes): + fires = -np.expm1(-c * H) + if mask >> j & 1: + weight = weight * fires + struck |= members + else: + weight = weight * (1 - fires) + left = len(names) - len(struck) + r = np.exp(-own * H) + if left == 3: + works = r**3 + 3 * r**2 * (1 - r) + elif left == 2: + works = r**2 + else: + works = 0.0 + total = total + weight * works + assert rbd.sf_given_state(X, {n: age for n in names}) == pytest.approx( + total, rel=1e-12, abs=0 + ) + + +def test_no_state_is_from_new(): + group = group_of(surv.Weibull.from_params([8000.0, 2.5]), 0.1) + assert group.sf_given_state(X, {}) == pytest.approx( + group.sf(X), rel=1e-15, abs=0 + ) + + +def test_the_simulated_mean_covers_the_exact_one(): + """The simulations draw the shared cause through the members' + quantile function.""" + group = group_of(surv.LogNormal.from_params([8.5, 0.6]), 0.2) + interval = group.mean_time_to_failure_interval(seed=0) + assert interval.lower <= group.mean() <= interval.upper + + +@pytest.mark.parametrize( + "state", + [ + {"p1": 4000.0}, + {"p1": 4000.0, "p2": 1000.0}, + {"p1": NodeState(alive=False), "p2": NodeState(alive=False)}, + { + "p1": NodeState(age=10.0), + "p2": NodeState( + age=10.0, model=surv.Weibull.from_params([9000.0, 2.5]) + ), + }, + ], +) +def test_members_in_different_states_are_refused(state): + group = group_of(surv.Weibull.from_params([8000.0, 2.5]), 0.1) + for call in ( + lambda: group.sf_given_state(100.0, state), + lambda: group.remaining_life(0.9, state), + lambda: group.mean_residual_life(state), + lambda: group.importances_given_state(100.0, state), + ): + with pytest.raises(NotImplementedError, match="node in series"): + call() + + +def test_a_probability_split_is_refused_naming_the_rate_split(): + life = surv.Weibull.from_params([8000.0, 2.5]) + rbd = NonRepairableRBD( + PARALLEL, + {"p1": life, "p2": life}, + ccf_groups=[CCFGroup(["p1", "p2"], BetaFactor(0.1))], + ) + with pytest.raises(NotImplementedError, match="basis='rate'"): + rbd.sf_given_state(100.0, {"p1": 10.0, "p2": 10.0}) + assert rbd.analysis_routes()["sf_given_state"].route == "refused" + by_rate = group_of(life, 0.1).analysis_routes() + assert by_rate["sf_given_state"].route == "exact" + assert by_rate["importances_given_state"].route == "exact" + assert by_rate["remaining_life"].route == "numerical" + assert by_rate["mean_residual_life"].route == "numerical" + + +# A shock at a constant rate that fails every member: a node in series. +PUMP = surv.Weibull.from_params([8000.0, 2.5]) +VALVE = surv.Weibull.from_params([20000.0, 1.5]) +RATE = 2e-5 + + +def aged(model, age, x): + return np.exp(-(model.Hf(age + x) - model.Hf(age))) + + +def test_a_lethal_shock_in_series_with_members_of_different_ages(): + """``R_sys = exp(-rate x) R_independent(x | ages)``.""" + pair = NonRepairableRBD( + WITH_SHARED, + { + "p1": PUMP, + "p2": PUMP, + "shared": surv.Exponential.from_params([RATE]), + }, + ) + old, young = aged(PUMP, 6000.0, X), aged(PUMP, 1000.0, X) + closed = np.exp(-RATE * X) * (1 - (1 - old) * (1 - young)) + state = {"p1": NodeState(age=6000.0), "p2": NodeState(age=1000.0)} + assert pair.sf_given_state(X, state) == pytest.approx( + closed, rel=1e-12, abs=0 + ) + # The shock has no age. + assert pair.sf_given_state(X, {**state, "shared": 5e4}) == pytest.approx( + closed, rel=1e-12, abs=0 + ) + + +def test_a_lethal_shock_as_a_repeated_node_across_branches(): + """Two trains, a pump and a valve each; the shock fails both pumps: + by the law of total probability on the shock, against the trains' + own closed form.""" + trains = NonRepairableRBD( + [ + ("s", "c1"), + ("c1", "p1"), + ("p1", "v1"), + ("v1", "t"), + ("s", "c2"), + ("c2", "p2"), + ("p2", "v2"), + ("v2", "t"), + ], + { + "p1": PUMP, + "p2": PUMP, + "v1": VALVE, + "v2": VALVE, + "c1": surv.Exponential.from_params([RATE]), + "c2": "c1", + }, + ) + one = aged(PUMP, 6000.0, X) * aged(VALVE, 3000.0, X) + two = aged(PUMP, 1000.0, X) * aged(VALVE, 500.0, X) + closed = np.exp(-RATE * X) * (1 - (1 - one) * (1 - two)) + state = {"p1": 6000.0, "p2": 1000.0, "v1": 3000.0, "v2": 500.0} + assert trains.sf_given_state(X, state) == pytest.approx( + closed, rel=1e-12, abs=0 + ) + + +def test_a_lethal_shock_against_a_direct_integral(): + """The mean life from new: the integral of the closed-form + reliability, by quadrature of its own.""" + from scipy.integrate import quad + + pair = NonRepairableRBD( + WITH_SHARED, + { + "p1": PUMP, + "p2": PUMP, + "shared": surv.Exponential.from_params([RATE]), + }, + ) + + def reliability(t): + r = float(PUMP.sf(t)) + return np.exp(-RATE * t) * (1 - (1 - r) ** 2) + + direct = quad(reliability, 0, 4e4, epsabs=0, epsrel=1e-12, limit=200)[0] + assert pair.mean() == pytest.approx(direct, rel=1e-9) diff --git a/repyability/tests/test_crew_allocation.py b/repyability/tests/test_crew_allocation.py new file mode 100644 index 00000000..653e4b6f --- /dev/null +++ b/repyability/tests/test_crew_allocation.py @@ -0,0 +1,404 @@ +"""Redundancy allocation with limited repair crews +(``allocate_redundancy``, ``_crew_allocation``): a copy is one more job +for the crews, so each design is worked out whole, from the crews' Markov +chain of its components and their copies. + +Here: a design's values against the same design drawn out as a diagram +(every copy a node of its own, behind a junction); the search against +every design in its box; the limit of a crew for every job against the +search for independent components; the bound the search prunes by; and +what refuses.""" + +import itertools +import math + +import numpy as np +import pytest +import surpyval as surv + +from repyability import ( + BetaFactor, + CCFGroup, + PerfectReliability, + RepairableRBD, +) +from repyability.rbd import _crew_allocation, _crew_chain +from repyability.rbd import routes as r + +E = surv.Exponential.from_params +W = surv.Weibull.from_params +HORIZON = 300.0 +#: Three components in series: failure rate, repair rate, price, options. +SPECS = { + "a": (0.01, 0.1, 400.0, {}), + "b": (0.02, 0.2, 250.0, {"downtime_cost": 0.3}), + "c": (0.005, 0.05, 900.0, {"priority": 1}), +} + + +def unit(rate, repair, price, **options): + return { + "reliability": E([rate]), + "repairability": E([repair]), + "acquisition_cost": price, + "repair_cost": 5.0, + **options, + } + + +def spec(node): + rate, repair, price, options = SPECS[node] + return unit(rate, repair, price, **options) + + +def line(crews=2, **options): + """``a``, ``b`` and ``c`` in series, sharing the crews.""" + return RepairableRBD( + [("s", "a"), ("a", "b"), ("b", "c"), ("c", "t")], + {node: spec(node) for node in SPECS}, + repair_crews=crews, + downtime_cost_rate=20.0, + **options, + ) + + +def drawn(counts, crews=2, **options): + """The line with ``counts`` copies of each node drawn out: every copy + a node of its own, a node's copies in parallel behind a junction.""" + components, edges, before = {}, [], "s" + for node, n in zip(SPECS, counts): + junction = ("after", node) + components[junction] = PerfectReliability + for copy in range(n): + name = (node, copy) + components[name] = spec(node) + edges += [(before, name), (name, junction)] + before = junction + edges.append((before, "t")) + return RepairableRBD( + edges, + components, + repair_crews=crews, + downtime_cost_rate=20.0, + **options, + ) + + +BOX = {"a": 2, "b": 3, "c": 2} + + +def every_design(**options): + """Each design of the box and its total cost, drawn out.""" + return { + counts: drawn(counts, **options).total_cost(HORIZON) + for counts in itertools.product( + *(range(1, BOX[node] + 1) for node in SPECS) + ) + } + + +# -- a design's values -------------------------------------------------------- + + +@pytest.mark.parametrize( + "options", + [ + {}, + {"crew_cost_rate": 0.4}, + {"call_out": {"when_waiting": 1, "fee": 30.0, "rate": 2.0}}, + ], + ids=["plain", "salaries", "a call-out crew"], +) +def test_a_design_is_the_diagram_with_its_copies_drawn_out(options): + rbd = line(**options) + evaluate = _crew_allocation.Evaluator(rbd, list(SPECS)) + for counts in [(1, 1, 1), (2, 1, 1), (1, 3, 2), (2, 2, 2)]: + design, diagram = evaluate(counts), drawn(counts, **options) + assert design.unavailability == pytest.approx( + diagram.mean_unavailability(), rel=1e-12 + ) + assert design.cost_rate == pytest.approx( + diagram.expected_cost_rate(), rel=1e-12 + ) + assert design.acquisition == diagram.acquisition_cost + # One of each is the diagram itself. + assert evaluate((1, 1, 1)).cost_rate == pytest.approx( + rbd.expected_cost_rate(), rel=1e-13 + ) + + +def test_alike_copies_are_counted_not_told_apart(): + # The chain of copies counted against the chain of every copy. + rates, repairs, priorities = [0.02, 0.05], [0.1, 0.3], [0.0, 1.0] + counted = _crew_chain.solve( + "ab", rates, repairs, priorities, 2, 2, (), [3, 2] + ) + each = _crew_chain.solve( + range(5), + [0.02] * 3 + [0.05] * 2, + [0.1] * 3 + [0.3] * 2, + [0.0] * 3 + [1.0] * 2, + 2, + 2, + ) + assert len(counted.states) < len(each.states) + assert _crew_chain.state_count( + priorities, [False, False], 2, 2, [3, 2] + ) == len(counted.states) + for k, copies in enumerate(([0, 1, 2], [3, 4])): + # Those up, on average, and whether any is. + assert float( + counted.probabilities @ counted.working[:, k] + ) == pytest.approx( + float(each.probabilities @ each.up[:, copies].sum(axis=1)), + rel=1e-12, + ) + assert float( + counted.probabilities @ counted.up[:, k] + ) == pytest.approx( + float(each.probabilities @ each.up[:, copies].any(axis=1)), + rel=1e-12, + ) + # The call-out crew's call-outs and time engaged. + for vector in ("calls", "engaged"): + assert float( + counted.probabilities @ getattr(counted, vector) + ) == pytest.approx( + float(each.probabilities @ getattr(each, vector)), rel=1e-12 + ) + + +# -- the search --------------------------------------------------------------- + + +@pytest.mark.parametrize( + "options", + [{}, {"call_out": {"when_waiting": 2, "fee": 30.0, "rate": 2.0}}], + ids=["plain", "a call-out crew"], +) +def test_the_search_finds_the_best_design_of_the_box(options): + designs = every_design(**options) + best = min(designs, key=designs.get) + result = line(**options).allocate_redundancy(HORIZON, max_units=BOX) + assert tuple(result.units[node] for node in SPECS) == best + assert result.total_cost == pytest.approx(designs[best], rel=1e-12) + assert result.availability == pytest.approx( + drawn(best, **options).mean_availability(), rel=1e-12 + ) + # Not at a corner of the box: the search chose it. + assert best not in ((1, 1, 1), tuple(BOX.values())) + assert result.method == "exact" + assert "repair crews' Markov chain" in result.basis + # One step at a time does no better. + greedy = line(**options).allocate_redundancy( + HORIZON, max_units=BOX, method="greedy" + ) + assert greedy.total_cost >= result.total_cost - 1e-9 + assert greedy.method == "greedy" + + +def test_the_search_keeps_to_an_availability(): + designs = every_design() + target = 0.97 + within = { + counts: cost + for counts, cost in designs.items() + if drawn(counts).mean_availability() >= target + } + assert 0 < len(within) < len(designs) + best = min(within, key=within.get) + result = line().allocate_redundancy( + HORIZON, max_units=BOX, min_availability=target + ) + assert tuple(result.units[node] for node in SPECS) == best + assert result.availability >= target + with pytest.raises(ValueError, match="even with a crew for every job"): + line().allocate_redundancy( + HORIZON, max_units=1, min_availability=0.999999 + ) + # Within the least any crews could give, but not with one crew. + one = line(crews=1) + floor = _crew_allocation.Unlimited(one, list(SPECS))((2, 2, 2)) + least = min( + _crew_allocation.Evaluator(one, list(SPECS))(counts).unavailability + for counts in itertools.product((1, 2), repeat=3) + ) + assert floor < least + with pytest.raises(ValueError, match="waits too long"): + one.allocate_redundancy( + HORIZON, + max_units=2, + min_availability=1.0 - 0.5 * (floor + least), + ) + + +def test_value_earned_is_downtime_that_costs(): + rbd = line() + valued = rbd.allocate_redundancy( + HORIZON, max_units=BOX, objective="npv", value_rate=15.0 + ) + dearer = RepairableRBD( + [("s", "a"), ("a", "b"), ("b", "c"), ("c", "t")], + {node: spec(node) for node in SPECS}, + repair_crews=2, + downtime_cost_rate=35.0, + ).allocate_redundancy(HORIZON, max_units=BOX) + assert valued.units == dearer.units + assert valued.npv == pytest.approx( + 15.0 * HORIZON * valued.availability - valued.total_cost, rel=1e-12 + ) + assert "repair crews' Markov chain" in valued.basis + + +def test_a_crew_for_every_job_is_the_search_for_independent_components(): + # Nine crews for at most nine jobs: none waits, and the chain's + # designs are those of independent components. + free = line(crews=None).allocate_redundancy(HORIZON, max_units=3) + counts, design = _crew_allocation.search( + line(crews=9), list(SPECS), [3, 3, 3], None, "exact", HORIZON, 0.0 + ) + assert dict(zip(SPECS, counts)) == free.units + assert design.acquisition + HORIZON * design.cost_rate == pytest.approx( + free.total_cost, rel=1e-10 + ) + assert 1.0 - design.unavailability == pytest.approx( + free.availability, rel=1e-12 + ) + # With as many crews as components the diagram itself takes the + # search for independent components: copies are then given crews too. + assert ( + line(crews=3).allocate_redundancy(HORIZON, max_units=3).units + == free.units + ) + + +def test_no_design_is_down_less_than_with_a_crew_for_every_job(): + rng = np.random.default_rng(89) + for _ in range(12): + rates = rng.uniform(0.005, 0.05, 3) + repairs = rng.uniform(0.05, 0.5, 3) + k = int(rng.integers(1, 3)) + rbd = RepairableRBD( + [("s", n) for n in "abc"] + [(n, "t") for n in "abc"], + { + n: unit(rates[i], repairs[i], 10.0, priority=int(i == 1)) + for i, n in enumerate("abc") + }, + k={"t": k}, + repair_crews=int(rng.integers(1, 3)), + downtime_cost_rate=1.0, + ) + evaluate = _crew_allocation.Evaluator(rbd, list("abc")) + unlimited = _crew_allocation.Unlimited(rbd, list("abc")) + for counts in itertools.product((1, 2, 3), repeat=3): + floor = unlimited(counts) + assert floor <= evaluate(counts).unavailability * (1 + 1e-12) + # More copies of anything lower the floor. + for i in range(3): + more = counts[:i] + (counts[i] + 1,) + counts[i + 1 :] + assert unlimited(more) <= floor * (1 + 1e-12) + assert unlimited((math.inf,) * 3) == 0.0 + + +def test_a_copy_can_make_the_system_worse(): + # Why the search for independent components' bounds do not hold: a + # copy of the spare path's unit takes the one crew from the unit + # the system needs. + rbd = RepairableRBD( + [("s", "a"), ("a", "b"), ("a", "z"), ("b", "t"), ("z", "t")], + { + "a": unit(0.02, 0.05, 10.0), + "b": unit(0.2, 0.05, 10.0, priority=1), + "z": unit(0.001, 1.0, 10.0), + }, + repair_crews=1, + downtime_cost_rate=1.0, + ) + evaluate = _crew_allocation.Evaluator(rbd, ["b"]) + assert evaluate((2,)).unavailability > evaluate((1,)).unavailability + + +# -- what refuses ------------------------------------------------------------- + + +def test_a_design_too_large_for_the_chain_is_refused_by_name(): + nodes = "abcdefg" + rbd = RepairableRBD( + [("s", nodes[0])] + list(zip(nodes, nodes[1:])) + [(nodes[-1], "t")], + { + n: unit(0.01 + 0.001 * i, 0.1, 1.0, priority=i) + for i, n in enumerate(nodes) + }, + repair_crews=1, + downtime_cost_rate=1000.0, + ) + with pytest.raises(NotImplementedError, match="needs the design") as e: + rbd.allocate_redundancy(HORIZON, max_units=4) + assert "15,000 states" in str(e.value) and "compare()" in str(e.value) + # Bounded, it is worked out. + assert rbd.allocate_redundancy(HORIZON, nodes=["a"], max_units=2).units + + +def test_a_copy_that_costs_nothing_to_buy_needs_a_cap(): + free = RepairableRBD( + [("s", "a"), ("a", "b"), ("b", "t")], + { + "a": {"reliability": E([0.01]), "repairability": E([0.1])}, + "b": unit(0.01, 0.1, 10.0), + }, + repair_crews=1, + downtime_cost_rate=5.0, + ) + with pytest.raises(ValueError, match="costs nothing to buy"): + free.allocate_redundancy(HORIZON, nodes=["a", "b"]) + assert free.allocate_redundancy( + HORIZON, nodes=["a", "b"], max_units={"a": 2} + ).units["a"] in (1, 2) + + +def test_what_the_chain_of_copies_does_not_take_refuses(): + with pytest.raises(NotImplementedError, match="whole trains"): + line().allocate_redundancy(HORIZON, trains={"ab": ["a", "b"]}) + grouped = RepairableRBD( + [("s", "a"), ("s", "b"), ("a", "c"), ("b", "c"), ("c", "t")], + {n: unit(0.01, 0.1, 10.0) for n in "abc"}, + repair_crews=1, + ccf_groups=[CCFGroup(["a", "b"], BetaFactor(0.1, basis="rate"))], + downtime_cost_rate=5.0, + ) + with pytest.raises(NotImplementedError, match="common-cause") as e: + grouped.allocate_redundancy(HORIZON, max_units=2) + assert "compare()" in str(e.value) + assert grouped.analysis_routes()["allocate_redundancy"].route == r.REFUSED + weibull = RepairableRBD( + [("s", "a"), ("a", "b"), ("b", "t")], + { + "a": { + "reliability": W([100.0, 2.0]), + "repairability": E([0.1]), + "acquisition_cost": 10.0, + }, + "b": unit(0.01, 0.1, 10.0), + }, + repair_crews=1, + downtime_cost_rate=5.0, + ) + with pytest.raises(NotImplementedError, match="exponential lives"): + weibull.allocate_redundancy(HORIZON, max_units=2) + assert weibull.analysis_routes()["allocate_redundancy"].route == r.REFUSED + + +def test_the_report_and_the_other_allocations(): + rbd = line() + report = rbd.analysis_routes() + assert report["allocate_redundancy"].route == r.EXACT + assert "crews' Markov chain" in report["allocate_redundancy"].reason + # Targets of availability move one component at a time: they still + # assume a crew each, and say what does not. + for method, call in ( + ("availability_allocation", lambda: rbd.availability_allocation(0.9)), + ("mttf_mttr_allocation", lambda: rbd.mttf_mttr_allocation(0.9)), + ): + assert report[method].route == r.REFUSED + with pytest.raises(NotImplementedError, match="allocate_redundancy"): + call() diff --git a/repyability/tests/test_crew_chain.py b/repyability/tests/test_crew_chain.py index bc15f2d9..97701130 100644 --- a/repyability/tests/test_crew_chain.py +++ b/repyability/tests/test_crew_chain.py @@ -343,8 +343,8 @@ def test_a_chain_too_large_to_solve_is_refused(): def test_what_assumes_independent_components_is_refused(): - # The allocations; the importance measures and the values over time - # come from the chain (#146: see test_chains_over_time.py). + # The allocations of targets; the importance measures and the values + # over time come from the chain (#146: see test_chains_over_time.py). rbd = units(3, 0.1, 0.5, 1, acquisition_cost=1.0) report = rbd.analysis_routes() for name in ( @@ -363,11 +363,14 @@ def test_what_assumes_independent_components_is_refused(): for name, call in { "availability_allocation": lambda: rbd.availability_allocation(0.99), "mttf_mttr_allocation": lambda: rbd.mttf_mttr_allocation(0.99), - "allocate_redundancy": lambda: rbd.allocate_redundancy(100.0), }.items(): with pytest.raises(NotImplementedError, match="allocations") as error: call() assert report[name].reason == str(error.value) + # The redundancy allocation works each design out from the chain + # (see test_crew_allocation.py). + assert report["allocate_redundancy"].route == r.EXACT + assert rbd.allocate_redundancy(100.0, max_units=2).units assert report["mean_availability"].route == r.EXACT assert report["expected_cost_rate"].route == r.EXACT diff --git a/repyability/tests/test_crew_salaries.py b/repyability/tests/test_crew_salaries.py new file mode 100644 index 00000000..eb448453 --- /dev/null +++ b/repyability/tests/test_crew_salaries.py @@ -0,0 +1,264 @@ +"""Repair crews that cost something (``crew_cost_rate``): ``repair_crews`` +crews at ``crew_cost_rate`` each cost ``n c`` per unit time, whatever +happens. Every cost result has it under ``"crews"``: ``n c`` in the long +run, ``n c T`` over a window and ``n c (1 - exp(-r T)) / r`` discounted, +and the same amount added to every simulated run. Without it every value +is as it was.""" + +import math + +import numpy as np +import pytest +import surpyval as surv + +from repyability import RepairableRBD, Timeline + +E = surv.Exponential.from_params +PAIR = [("s", "a"), ("s", "b"), ("a", "t"), ("b", "t")] +LINE = [("s", "p"), ("p", "t")] +CREWS, RATE = 1, 3.0 +PAID = CREWS * RATE + + +def unit(**extra): + return { + "reliability": E([0.1]), + "repairability": E([1.0]), + "repair_cost": 100.0, + **extra, + } + + +def pair(**options): + """Two units in parallel, one repair crew for both.""" + return RepairableRBD( + PAIR, + {"a": unit(), "b": unit()}, + repair_crews=CREWS, + downtime_cost_rate=50.0, + **options, + ) + + +def present(T, r): + """The crews' salaries from 0 to ``T``, discounted at ``r``.""" + return PAID * T if not r else PAID * (1.0 - np.exp(-r * T)) / r + + +def test_the_long_run_cost_rate_adds_the_salaries(): + unpaid, paid = pair(), pair(crew_cost_rate=RATE) + assert paid.expected_cost_rate() == pytest.approx( + unpaid.expected_cost_rate() + PAID, rel=1e-15 + ) + assert paid.total_cost(100.0) == pytest.approx( + unpaid.total_cost(100.0) + 100.0 * PAID, rel=1e-14 + ) + + +@pytest.mark.parametrize("r", [0.0, 0.05]) +def test_a_window_adds_the_closed_forms(r): + windows = np.array([10.0, 50.0, 100.0]) + unpaid = pair().expected_cost(windows, discount_rate=r) + paid = pair(crew_cost_rate=RATE).expected_cost(windows, discount_rate=r) + np.testing.assert_allclose( + paid.by_category["crews"], present(windows, r), rtol=1e-15 + ) + np.testing.assert_allclose(unpaid.by_category["crews"], 0.0, atol=0.0) + np.testing.assert_allclose( + paid.mean, unpaid.mean + present(windows, r), rtol=1e-13 + ) + for category, values in unpaid.by_category.items(): + if category != "crews": + np.testing.assert_allclose( + paid.by_category[category], values, rtol=1e-13 + ) + + +def test_the_cash_flow_table_adds_up_to_the_closed_form(): + r, T = 0.05, 100.0 + result = pair(crew_cost_rate=RATE).expected_npv( + T, discount_rate=r, periods=4 + ) + rows = [row for row in result.cash_flows if row["category"] == "crews"] + assert [row["period"] for row in rows] == [1, 2, 3, 4] + assert all(row["component"] is None for row in rows) + # Each period's own, from its start to its end. + for row in rows: + start, end = row["start"], row["end"] + assert -row["present_value"] == pytest.approx( + present(end, r) - present(start, r), rel=1e-12 + ) + assert -row["undiscounted"] == pytest.approx( + PAID * (end - start), rel=1e-12 + ) + total = -math.fsum(row["present_value"] for row in rows) + assert total == pytest.approx(present(T, r), rel=1e-13) + assert result.cost_by_category["crews"] == pytest.approx( + present(T, r), rel=1e-13 + ) + unpaid = pair().expected_npv(T, discount_rate=r, periods=4) + assert result.cost == pytest.approx(unpaid.cost + present(T, r), 1e-13) + assert result.undiscounted_cost == pytest.approx( + unpaid.undiscounted_cost + PAID * T, rel=1e-13 + ) + + +def test_each_simulated_run_pays_the_same_salaries(): + T = 100.0 + options = dict(t_simulation=T, mc_samples=200, seed=1) + unpaid = pair().cost(**options) + paid = pair(crew_cost_rate=RATE).cost(**options) + # Added to each run after it: the runs are otherwise the same. + np.testing.assert_array_equal(paid.samples, unpaid.samples + PAID * T) + assert paid.by_category["crews"] == pytest.approx(PAID * T, rel=1e-15) + assert unpaid.by_category["crews"] == 0.0 + assert paid.mean == pytest.approx(unpaid.mean + PAID * T, rel=1e-13) + assert paid.mean == pytest.approx( + math.fsum(paid.by_category.values()), rel=1e-12 + ) + own = pair(crew_cost_rate=RATE).cost( + control_variate=False, conditional=False, **options + ) + assert own.mean == pytest.approx( + math.fsum(own.by_category.values()), rel=1e-12 + ) + + +def test_the_spread_by_window_pays_each_window_its_salaries(): + paid = pair(crew_cost_rate=RATE).cost_by_window( + width=25.0, count=4, mc_samples=50, seed=2 + ) + unpaid = pair().cost_by_window(width=25.0, count=4, mc_samples=50, seed=2) + np.testing.assert_allclose(paid.mean, unpaid.mean + 25.0 * PAID) + np.testing.assert_allclose( + paid.samples, unpaid.samples + 25.0 * PAID, rtol=0.0, atol=1e-9 + ) + + +def test_a_simulated_npv_pays_the_discounted_salaries(): + r, T = 0.05, 100.0 + options = dict(discount_rate=r, mc_samples=100, seed=3) + paid = pair(crew_cost_rate=RATE).npv_distribution(T, **options) + unpaid = pair().npv_distribution(T, **options) + assert paid.cost_by_category["crews"] == pytest.approx( + present(T, r), rel=1e-13 + ) + np.testing.assert_allclose( + paid.cost_samples, unpaid.cost_samples + present(T, r), rtol=1e-13 + ) + + +def test_a_plan_against_its_log_pays_the_crews_as_planned(): + line = RepairableRBD( + LINE, + {"p": unit()}, + repair_crews=1, + crew_cost_rate=RATE, + ) + result = line.plan_vs_actual( + {"p": Timeline.from_outages([(30.0, 31.0)], end=50.0)}, + 50.0, + 100.0, + discount_rate=0.01, + periods=[25.0, 50.0, 100.0], + ) + planned = [ + r for r in result.expected_cash_flows if r["category"] == "crews" + ] + actual = [r for r in result.actual_cash_flows if r["category"] == "crews"] + assert [r["period"] for r in actual] == [1, 2] + for want, got in zip(planned, actual): + assert got["present_value"] == pytest.approx( + want["present_value"], rel=1e-12 + ) + assert result.variance_by_category.get("crews", 0.0) == pytest.approx( + 0.0, abs=1e-9 + ) + + +def test_unpriced_crews_change_nothing(): + windows = np.array([20.0, 100.0]) + for unpaid, zero in ((pair(), pair(crew_cost_rate=0.0)),): + assert unpaid.expected_cost_rate() == zero.expected_cost_rate() + np.testing.assert_array_equal( + unpaid.expected_cost(windows, discount_rate=0.05).mean, + zero.expected_cost(windows, discount_rate=0.05).mean, + ) + options = dict(t_simulation=50.0, mc_samples=40, seed=4) + np.testing.assert_array_equal( + unpaid.cost(**options).samples, zero.cost(**options).samples + ) + assert "crew_cost_rate" not in zero.to_dict() + + +def test_salaries_alone_are_priced(): + rbd = RepairableRBD( + PAIR, + {"a": unit(repair_cost=0.0), "b": unit(repair_cost=0.0)}, + repair_crews=2, + crew_cost_rate=RATE, + ) + assert rbd.has_costs + assert rbd.expected_cost_rate() == 2 * RATE + assert float(rbd.expected_cost(10.0).mean) == 20 * RATE + result = rbd.cost(t_simulation=10.0, mc_samples=20, seed=5) + np.testing.assert_array_equal(result.samples, np.full(20, 20 * RATE)) + + +def test_more_crews_cost_more_salaries(): + one, two = pair(crew_cost_rate=RATE), RepairableRBD( + PAIR, + {"a": unit(), "b": unit()}, + repair_crews=2, + downtime_cost_rate=50.0, + crew_cost_rate=RATE, + ) + assert float(two.expected_cost(10.0).by_category["crews"]) == 20 * RATE + assert float(one.expected_cost(10.0).by_category["crews"]) == 10 * RATE + + +def test_interval_choices_as_if_unlimited_keep_the_salaries(): + def system(**options): + return RepairableRBD( + PAIR, + { + name: { + "reliability": surv.Weibull.from_params([100.0, 3.0]), + "repairability": E([0.5]), + "repair_cost": 100.0, + "preventive": {"interval": 40.0, "cost": 10.0}, + } + for name in "ab" + }, + repair_crews=1, + downtime_cost_rate=50.0, + **options, + ) + + unpaid = system().optimal_replacement_intervals( + assume_unlimited_crews=True + ) + paid = system(crew_cost_rate=RATE).optimal_replacement_intervals( + assume_unlimited_crews=True + ) + assert paid.intervals == unpaid.intervals + assert paid.cost_rate == pytest.approx(unpaid.cost_rate + PAID, 1e-15) + with pytest.raises(ValueError, match="salaries alone"): + system(crew_cost_rate=RATE).optimal_replacement_intervals( + assume_unlimited_crews=True, max_cost_rate=PAID + ) + + +def test_a_crew_cost_needs_crews_and_is_a_number(): + with pytest.raises(ValueError, match="repair_crews"): + RepairableRBD(PAIR, {"a": unit(), "b": unit()}, crew_cost_rate=1.0) + for bad in (-1.0, math.inf, "3", True): + with pytest.raises(ValueError, match="crew_cost_rate"): + pair(crew_cost_rate=bad) + + +def test_a_crew_cost_is_saved(): + rbd = pair(crew_cost_rate=RATE) + back = RepairableRBD.from_dict(rbd.to_dict()) + assert back.crew_cost_rate == RATE + assert back.expected_cost_rate() == rbd.expected_cost_rate() diff --git a/repyability/tests/test_crews_ccf.py b/repyability/tests/test_crews_ccf.py new file mode 100644 index 00000000..2e0bb3eb --- /dev/null +++ b/repyability/tests/test_crews_ccf.py @@ -0,0 +1,431 @@ +"""Common-cause groups in the repair crews' Markov chain (#251). + +With limited repair crews a shared cause's failures queue for the crews +with the other components', so a group's own chain does not follow them: +the crews' chain takes the groups in. A shared cause strikes at its rate +and fails the members it names that are up, which join the queue one +after another in the cause's order, as the simulation's do +(``_event_loop._strike``). Here: the chain against states solved by hand, +against the chain without groups, against the groups' own chain where no +job waits, and against the simulation (which is given nothing of the +chain); the failure frequency against the chain's own flows; and what +still refuses.""" + +import math +from fractions import Fraction + +import numpy as np +import pytest +import surpyval as surv + +from repyability import ( + MGL, + AlphaFactor, + BetaFactor, + CCFGroup, + RepairableRBD, +) +from repyability.rbd import _crew_chain, _crews +from repyability.rbd import routes as r + +E = surv.Exponential.from_params +LAM, MU, BETA = 0.02, 0.1, 0.3 +PAIR = [("s", "a"), ("s", "b"), ("a", "t"), ("b", "t")] +#: ``a`` in series with ``b`` or ``z``: which of ``a`` and ``b`` a crew +#: takes first matters. +LADDER = [("s", "a"), ("a", "b"), ("a", "z"), ("b", "t"), ("z", "t")] + + +def unit(rate=LAM, repair=MU, **extra): + return {"reliability": E([rate]), "repairability": E([repair]), **extra} + + +def pair(beta=BETA, crews=1, model=None, **options): + """Two alike units in parallel in a common-cause group, one crew.""" + groups = None + if beta is not None: + groups = [ + CCFGroup(["a", "b"], model or BetaFactor(beta, basis="rate")) + ] + return RepairableRBD( + PAIR, + {"a": unit(), "b": unit()}, + repair_crews=crews, + ccf_groups=groups, + **options, + ) + + +def ladder(members="ab", crews=1, model=None, priority=None, **options): + components = { + m: unit(priority=(priority or {}).get(m, 0), repair_cost=3.0) + for m in "ab" + } + components["z"] = unit(0.03, 0.2) + return RepairableRBD( + LADDER, + components, + repair_crews=crews, + ccf_groups=[ + CCFGroup(list(members), model or BetaFactor(0.5, basis="rate")) + ], + downtime_cost_rate=5.0, + **options, + ) + + +def flows(rbd): + """The system's failures per unit time from the chain's own flows: over + every transition that is a failure (a component's, or a strike), its + rate where the system is up before it and down after.""" + chain = _crews._crew_chain(rbd) + states = rbd.crew_states() + up = np.array( + [ + rbd.is_system_working( + {n: bool(states.node_availability[n][s]) for n in rbd.nodes}, + "p", + ) + for s in range(len(chain.probabilities)) + ], + dtype=float, + ) + sources, targets, rates, _ = chain.transitions + return float( + np.sum( + chain.probabilities[sources] + * rates + * up[sources] + * (1.0 - up[targets]) + ) + ) + + +# -- the chain ---------------------------------------------------------------- + + +def test_two_members_and_one_crew_are_the_chain_solved_by_hand(): + # By the number down (0, 1, 2), with rho = lam / mu: one fails at its + # own cause (2 (1 - beta) lam), both at the shared one (beta lam), the + # second at every cause it has (lam), and one is repaired at a time. + # Balance at 0 and across the cut below 2: + # p1 = (2 - beta) rho p0, p2 = rho (beta p0 + p1). + rho = Fraction(LAM).limit_denominator() / Fraction(MU).limit_denominator() + beta = Fraction(BETA).limit_denominator() + p0 = Fraction(1) + p1 = (2 - beta) * rho * p0 + p2 = rho * (beta * p0 + p1) + total = p0 + p1 + p2 + rbd = pair() + assert rbd.mean_unavailability() == pytest.approx( + float(p2 / total), rel=1e-13 + ) + # Its failures: the shared cause from 0, the other unit from 1. + lam = Fraction(LAM).limit_denominator() + assert rbd.system_failure_frequency() == pytest.approx( + float((beta * lam * p0 + lam * p1) / total), rel=1e-13 + ) + # A strike queues the members in the cause's order: a is repaired + # first. The states with both down: a's repair with b waiting, from + # the strike or b's failure; b's with a waiting, from a's failure. + chain = _crews._crew_chain(rbd) + p = dict(zip(chain.states, chain.probabilities)) + mu = float(Fraction(MU).limit_denominator()) + assert p[((0,), (1,))] * mu == pytest.approx( + BETA * LAM * p[((), ())] + LAM * p[((0,), ())], rel=1e-12 + ) + assert p[((1,), (0,))] * mu == pytest.approx( + LAM * p[((1,), ())], rel=1e-12 + ) + + +def test_no_shared_part_is_the_chain_without_groups(): + plain, none = pair(None), pair(0.0) + assert none.mean_availability() == plain.mean_availability() + assert none.system_failure_frequency() == plain.system_failure_frequency() + t = np.array([2.0, 20.0, 200.0]) + np.testing.assert_array_equal( + none.point_availability(t), plain.point_availability(t) + ) + np.testing.assert_array_equal( + _crews._crew_chain(none).probabilities, + _crews._crew_chain(plain).probabilities, + ) + + +@pytest.mark.parametrize( + "model", + [ + BetaFactor(0.2, basis="rate"), + MGL(0.25, basis="rate"), + AlphaFactor([0.8, 0.2], basis="rate"), + ], +) +def test_a_crew_each_is_the_groups_own_long_run(model): + # With a crew for every component no job waits: the chain with the + # shared causes is then the group's own (which the diagram takes + # where its crews do not limit it). + free = ladder(crews=None, model=model) + limited = ladder(crews=1, model=model) + own, shared = _crews._crew_causes(limited, list("abz")) + assert shared and own["a"] < LAM and own["z"] == 0.03 + chain = _crew_chain.solve( + list("abz"), + [own[n] for n in "abz"], + [MU, MU, 0.2], + [0.0] * 3, + 3, + 0, + shared, + ) + up = np.array( + [ + free.is_system_working(dict(zip("abz", map(bool, row))), "p") + for row in chain.up + ], + dtype=float, + ) + assert float(chain.probabilities @ up) == pytest.approx( + free.mean_availability(), rel=1e-12 + ) + for k, node in enumerate("abz"): + assert chain.availability(node) == pytest.approx( + free.node_availability()[node], rel=1e-12 + ) + + +@pytest.mark.parametrize("members", ["ab", "ba"]) +@pytest.mark.parametrize("crews", [1, 2]) +def test_the_failure_frequency_is_the_chain_s_flows(members, crews): + rbd = ladder(members, crews) + frequency = rbd.system_failure_frequency() + assert frequency == pytest.approx(flows(rbd), rel=1e-12) + # Its terms: each component's own cause, and the group's shared ones. + shares = rbd.barlow_proschan_importance() + assert set(shares) == {"a", "b", "z", tuple(members)} + assert sum(shares.values()) == pytest.approx(1.0, rel=1e-12) + assert shares[tuple(members)] > 0.0 + # The up and down times follow. + assert rbd.mean_up_time() == pytest.approx( + rbd.mean_availability() / frequency, rel=1e-12 + ) + + +def test_the_order_of_a_cause_s_members_is_the_queue_s(): + # Struck together with the crew free, the first in the cause's order + # is repaired first, whatever the priorities (they order the jobs + # that wait): a first keeps the system up more. + first, last = ladder("ab"), ladder("ba") + assert first.mean_availability() > last.mean_availability() + 1e-3 + urgent = ladder("ba", priority={"a": 1}) + assert urgent.mean_availability() > last.mean_availability() + assert urgent.mean_availability() < first.mean_availability() + + +def test_a_member_held_is_struck_no_more_and_the_others_still_are(): + # Held working, a never fails; b still fails at its whole rate, its + # own cause's and the shared one's: the same system with no group. + grouped = ladder("ab") + plain = RepairableRBD( + LADDER, + {"a": unit(), "b": unit(), "z": unit(0.03, 0.2)}, + repair_crews=1, + ) + for held in ({"working_nodes": ["a"]}, {"broken_nodes": ["a"]}): + assert grouped.mean_availability(**held) == pytest.approx( + plain.mean_availability(**held), rel=1e-13 + ) + # Birnbaum's measure holds each node both ways. + importance = grouped.birnbaum_importance() + assert importance["a"] == pytest.approx( + grouped.mean_availability(working_nodes=["a"]) + - grouped.mean_availability(broken_nodes=["a"]), + rel=1e-12, + ) + + +# -- over time ---------------------------------------------------------------- + + +def test_the_rate_s_parts_add_up_to_the_availability_s_slope(): + rbd = ladder("ab") + t = np.array([3.0, 12.0, 40.0]) + rate = rbd.availability_rate(t) + step = 1e-4 + slope = ( + rbd.point_availability(t + step) - rbd.point_availability(t - step) + ) / (2 * step) + np.testing.assert_allclose(rate.rate, slope, rtol=1e-6) + assert ("a", "b") in rate.node_rate + np.testing.assert_allclose( + sum(np.asarray(v) for v in rate.node_rate.values()), + rate.rate, + rtol=1e-10, + ) + # A strike only takes the system down. + assert np.all(np.asarray(rate.node_rate[("a", "b")]) < 0.0) + + +def test_the_window_s_failures_are_split_by_cause(): + rbd = ladder("ab") + T = 150.0 + events = rbd.expected_events(T) + # The members fail at their whole rate while up: own and shared. + for node in "ab": + assert events.node_failures[node] == pytest.approx( + LAM * (T - events.node_downtime[node]), rel=1e-10 + ) + # In the long run the window's failures grow at the frequency. + long, longer = ( + rbd.expected_events(T).system_failures for T in (4000.0, 5000.0) + ) + assert (longer - long) / 1000.0 == pytest.approx( + rbd.system_failure_frequency(), rel=1e-9 + ) + + +# -- the simulation ----------------------------------------------------------- + + +def call_out(): + """Three members' worth of jobs for one crew and a call-out crew.""" + return RepairableRBD( + [("s", n) for n in "abcd"] + [(n, "t") for n in "abcd"], + { + "a": unit(0.05, 0.15), + "b": unit(0.05, 0.15, priority=1), + "c": unit(0.04, 0.2, priority=2, repair_cost=4.0), + "d": unit(0.04, 0.2, repair_cost=4.0), + }, + k={"t": 3}, + repair_crews=1, + call_out={"when_waiting": 2, "fee": 30.0, "rate": 4.0}, + ccf_groups=[ + CCFGroup(["a", "b"], MGL(0.4, basis="rate")), + CCFGroup(["d", "c"], AlphaFactor([0.7, 0.3], basis="rate")), + ], + downtime_cost_rate=6.0, + ) + + +@pytest.mark.parametrize( + "build", + [ + lambda: ladder("ab"), + lambda: ladder("ba", crews=2, priority={"a": 1}), + call_out, + lambda: ladder("ab", model=BetaFactor(0.3)), + ], + ids=["one crew", "two crews", "two groups, a call-out crew", "by Q"], +) +def test_the_simulation_agrees_with_the_chain(build): + T, n = 300.0, 6000 + rbd = build() + run = rbd.availability( + T, mc_samples=n, seed=20261121, control_variate=False + ) + events = rbd.expected_events(T) + down = T - np.asarray(run.uptimes) + assert abs(down.mean() - events.system_downtime) < 3.5 * ( + down.std(ddof=1) / math.sqrt(n) + ) + # The failures of a run are no fewer than Poisson's spread apart. + failures = run.system_failures / n + assert abs(failures - events.system_failures) < 3.5 * math.sqrt( + 2.0 * events.system_failures / n + ) + for node in rbd.nodes: + assert run.node_downtime[node] / n == pytest.approx( + events.node_downtime[node], rel=0.03 + ), node + cost = run.cost + assert abs(cost.sample_mean - rbd.expected_cost(T).mean) < ( + 3.5 * cost.mean_se + ) + # The point availability, at the simulation's own times. + at = np.array([5.0, 25.0, 100.0, 250.0]) + timeline = np.interp(at, run.timeline, run.availability) + exact = rbd.point_availability(at) + spread = np.sqrt(exact * (1.0 - exact) / n) + assert np.all(np.abs(timeline - exact) < 3.5 * spread + 1e-3) + + +# -- what refuses, and what the report says ----------------------------------- + + +def test_the_report_says_the_chain_has_the_groups(): + rbd = ladder("ab") + report = rbd.analysis_routes() + for method in ( + "mean_availability", + "node_availability", + "system_failure_frequency", + "barlow_proschan_importance", + "birnbaum_importance", + "criticality_importance", + "expected_cost_rate", + ): + assert report[method].route == r.EXACT, method + for method in ( + "point_availability", + "mission_availability", + "expected_events", + "expected_cost", + "availability_rate", + ): + assert report[method].route == r.NUMERICAL, method + + +def test_a_cause_of_three_members_is_left_to_the_simulation(): + rbd = RepairableRBD( + [("s", n) for n in "abc"] + [(n, "t") for n in "abc"], + {n: unit() for n in "abc"}, + repair_crews=1, + ccf_groups=[CCFGroup(list("abc"), BetaFactor(0.2, basis="rate"))], + ) + with pytest.raises(NotImplementedError, match="one that strikes 3") as e: + rbd.mean_availability() + assert "availability() or cost()" in str(e.value) + with pytest.raises(NotImplementedError, match="one that strikes 3"): + rbd.point_availability(10.0) + report = rbd.analysis_routes() + assert report["mean_availability"].route == r.REFUSED + assert report["availability"].route == r.SIMULATED + rbd.availability(50.0, mc_samples=20, seed=1) + # Three members whose causes strike two at most are taken. + pairs = RepairableRBD( + [("s", n) for n in "abc"] + [(n, "t") for n in "abc"], + {n: unit() for n in "abc"}, + repair_crews=1, + ccf_groups=[ + CCFGroup(list("abc"), AlphaFactor([0.7, 0.3, 0.0], basis="rate")) + ], + ) + assert 0.0 < pairs.mean_availability() < 1.0 + + +def test_members_the_chain_has_no_place_for_refuse(): + instant = RepairableRBD( + LADDER, + { + "a": {"reliability": E([LAM]), "repairability": "instant"}, + "b": {"reliability": E([LAM]), "repairability": "instant"}, + "z": unit(), + }, + repair_crews=1, + ccf_groups=[CCFGroup(["a", "b"], BetaFactor(0.2, basis="rate"))], + ) + with pytest.raises(NotImplementedError, match="repaired instantly"): + instant.mean_availability() + tested = RepairableRBD( + LADDER, + { + **{m: unit(inspection={"interval": 50.0}) for m in "ab"}, + "z": unit(), + }, + repair_crews=1, + ccf_groups=[CCFGroup(["a", "b"], BetaFactor(0.2, basis="rate"))], + ) + with pytest.raises(NotImplementedError, match="inspections"): + tested.mean_availability() + assert tested.analysis_routes()["availability"].route == r.SIMULATED diff --git a/repyability/tests/test_diagram_life.py b/repyability/tests/test_diagram_life.py new file mode 100644 index 00000000..f243cb89 --- /dev/null +++ b/repyability/tests/test_diagram_life.py @@ -0,0 +1,140 @@ +"""A ``NonRepairableRBD`` as a unit's life (UC-66 of the maintenance +README): a subassembly replaced whole at its failure, taken by its +functions, its ``qf`` inverting its ``ff`` to near machine precision.""" + +import math + +import numpy as np +import pytest +import surpyval as surv + +from repyability import NonRepairable, NonRepairableRBD, RepairableRBD +from repyability.maintenance import AgePolicy, Prices, UnitPlan +from repyability.rbd import routes +from repyability.rbd.serialisation import rbd_from_json, rbd_to_json + +LAMBDA = 0.01 +E = surv.Exponential.from_params([LAMBDA]) +REPAIR = surv.Exponential.from_params([0.5]) +PARALLEL = [("s", "a"), ("s", "b"), ("a", "t"), ("b", "t")] +SERIES = [("s", "a"), ("a", "b"), ("b", "t")] +SHARES = np.array( + [1e-14, 1e-9, 1e-6, 1e-3, 0.1, 0.3, 0.5, 0.7, 0.9, 0.999, 1 - 1e-9] +) + + +def pair_of(edges, model): + return NonRepairableRBD(edges, {"a": model, "b": model}) + + +def parallel_qf(p): + """The parallel pair of exponentials' quantile, ``1 - exp(-l t) = + sqrt(p)``, each tail in its precise form.""" + root = np.sqrt(p) + return ( + np.where(p <= 0.5, -np.log1p(-root), -np.log((1 - p) / (1 + root))) + / LAMBDA + ) + + +def test_a_parallel_pair_s_quantile_is_its_closed_form(): + found = pair_of(PARALLEL, E).qf(SHARES) + np.testing.assert_allclose(found, parallel_qf(SHARES), rtol=1e-13) + + +def test_a_series_pair_s_quantile_is_the_one_model_it_is(): + # Two Weibulls of shape 2 in series are one Weibull, scale / sqrt(2). + weibull = surv.Weibull.from_params([100.0, 2.0]) + one = surv.Weibull.from_params([100.0 / math.sqrt(2.0), 2.0]) + np.testing.assert_allclose( + pair_of(SERIES, weibull).qf(SHARES), one.qf(SHARES), rtol=1e-13 + ) + + +def test_the_quantile_s_ends_and_refusals(): + pair = pair_of(PARALLEL, E) + assert pair.qf(0.0) == 0.0 + assert pair.qf(1.0) == math.inf + assert isinstance(pair.qf(0.5), float) + assert pair.qf(np.array([[0.25, 0.5]])).shape == (1, 2) + with pytest.raises(ValueError, match=r"\[0, 1\]"): + pair.qf(1.5) + fixed = NonRepairableRBD( + SERIES, + {"a": surv.FixedEventProbability.from_params(0.1), "b": E}, + ) + if fixed.is_fixed: + with pytest.raises(routes.Refused): + fixed.qf(0.5) + + +# -- a unit whose life is a diagram ------------------------------------------- + +WEIBULL = surv.Weibull.from_params([100.0, 2.0]) +ONE = surv.Weibull.from_params([100.0 / math.sqrt(2.0), 2.0]) + + +def unit(life) -> RepairableRBD: + return UnitPlan( + life, + REPAIR, + tasks=(AgePolicy(interval=60.0, cost=1.0, duration=REPAIR),), + prices=Prices(repair=5.0, downtime=1.0), + ).diagram() + + +def test_a_unit_whose_life_is_a_diagram_is_the_unit_of_that_life(): + # Exact and numerical routes, to 1e-12 (fixed before running). + mine, theirs = unit(pair_of(SERIES, WEIBULL)), unit(ONE) + for name in ("mean_availability", "expected_cost_rate"): + assert getattr(mine, name)() == pytest.approx( + getattr(theirs, name)(), rel=1e-12 + ), name + t = np.array([10.0, 50.0, 200.0]) + np.testing.assert_allclose( + mine.point_availability(t), theirs.point_availability(t), rtol=1e-12 + ) + assert mine.expected_npv(300.0, discount_rate=1e-3).npv == pytest.approx( + theirs.expected_npv(300.0, discount_rate=1e-3).npv, rel=1e-12 + ) + + +def test_its_simulations_are_those_of_that_life(): + mine, theirs = unit(pair_of(SERIES, WEIBULL)), unit(ONE) + options = dict( + t_simulation=300.0, mc_samples=200, seed=3, control_variate=False + ) + a = mine.availability(**options) + b = theirs.availability(**options) + assert a.mean_availability == pytest.approx(b.mean_availability, rel=1e-12) + runs = dict(discount_rate=1e-3, mc_samples=100, seed=8) + np.testing.assert_allclose( + mine.npv_distribution(300.0, **runs).samples, + theirs.npv_distribution(300.0, **runs).samples, + rtol=1e-12, + ) + + +def test_a_repaired_parallel_pair_is_up_its_mttf_over_its_cycle(): + pair = pair_of(PARALLEL, E) + rbd = UnitPlan(pair, REPAIR).diagram() + mttf = 1.5 / LAMBDA # 1/l + 1/(2 l) + assert rbd.mean_availability() == pytest.approx( + mttf / (mttf + 2.0), rel=1e-12 + ) + + +def test_a_diagram_is_a_life_wherever_a_life_is(): + pair = pair_of(PARALLEL, E) + part = NonRepairable(pair, unplanned_cost=5.0) + assert part.reliability is pair + spec = RepairableRBD( + [("s", "u"), ("u", "t")], + {"u": {"reliability": pair, "repairability": REPAIR}}, + ) + loaded = rbd_from_json(rbd_to_json(spec)) + assert loaded.mean_availability() == pytest.approx( + spec.mean_availability(), rel=1e-12 + ) + route = spec.analysis_routes()["mean_availability"] + assert route.route in (routes.EXACT, routes.NUMERICAL) diff --git a/repyability/tests/test_discounted_long_run.py b/repyability/tests/test_discounted_long_run.py new file mode 100644 index 00000000..3663dcb8 --- /dev/null +++ b/repyability/tests/test_discounted_long_run.py @@ -0,0 +1,582 @@ +"""The discounted long run (Fox, 1966): age replacement, a calendar of +opportunities in model time and a site's shuts on real dates, each +choosing the policy with the least equivalent annual cost (EAC) at a +discount rate, checked against independent workings: the present value +by quadrature of the density, a simulation of the discounted renewal +costs, a long finite-horizon discounted programme, and the +undiscounted answers the discounted ones come to as the rate goes to +0.""" + +import math +import warnings + +import numpy as np +import pytest +import surpyval as surv +from scipy.integrate import quad + +from repyability import ( + Calendar, + NonRepairable, + Opportunity, + Shutdown, + Shutdowns, + StandbyModel, +) +from repyability.maintenance._replacement import _Ages, _Grid, _sweep +from repyability.schedule import DutyPlan, Recurrence, Shifts + +# The 0.14 and 0.19 forms (Calendar, Shutdown, Shutdowns, prices on the +# opportunities, optimal_calendar_policy) still work, deprecated: these +# tests keep them unchanged, and test_opportunities.py the new forms. +pytestmark = pytest.mark.filterwarnings( + "ignore:.*(is deprecated|puts a price on the opportunities):FutureWarning" +) + +HOURS_A_YEAR = 8760.0 + + +def bearing(cp=1.0, cu=5.0, life=None): + unit = NonRepairable(life or surv.Weibull.from_params([1000, 2.5])) + unit.set_costs_planned_and_unplanned(cp=cp, cu=cu) + return unit + + +def a_year(rate): + """A yearly rate as a continuous one an hour.""" + return math.log1p(rate) / HOURS_A_YEAR + + +def fox_eac(life, cp, cu, rate, age): + """Fox's equivalent annual cost at ``age``, written out from the + density by quadrature: ``r * [cu F_r(T) + cp D(T)] / [1 - F_r(T) - + D(T)]``, ``F_r`` the discounted chance of failing first and ``D`` the + discounted chance of reaching ``age``.""" + failed = quad( + lambda t: math.exp(-rate * t) * float(np.ravel(life.df(t))[0]), + 0.0, + age, + limit=200, + )[0] + kept = math.exp(-rate * age) * float(np.ravel(life.sf(age))[0]) + return rate * (cu * failed + cp * kept) / (1.0 - failed - kept) + + +def fox_run_to_failure(life, cu, rate): + """Running to failure's EAC: ``r cu L / (1 - L)``, ``L`` the Laplace + transform of the life at ``rate``.""" + laplace = quad( + lambda t: math.exp(-rate * t) * float(np.ravel(life.df(t))[0]), + 0.0, + np.inf, + limit=400, + )[0] + return rate * cu * laplace / (1.0 - laplace) + + +# ------------------------------------------------------- age replacement + + +def test_rate_zero_is_the_undiscounted_policy_unchanged(): + unit = bearing() + plain = unit.optimal_replacement_policy() + assert unit.optimal_replacement_policy(discount_rate=0.0) == plain + assert unit.optimal_replacement_policy(discount_rate=0) == plain + assert unit.find_optimal_replacement(discount_rate=0.0) == plain.interval + assert plain.discount_rate == 0.0 and plain.npv == math.inf + assert plain.eac == plain.cost_rate + # The doctest's numbers, as before. + assert round(plain.interval, 1) == 493.0 + assert round(plain.cost_rate, 6) == 0.003462 + + +def test_the_discounted_age_minimises_fox_s_cost(): + unit = bearing() + rate = 0.002 # a unit of the life's time: strong, to show the effect + policy = unit.optimal_replacement_policy(discount_rate=rate) + life = unit.reliability + ages = np.linspace(300.0, 1200.0, 1801) + costs = [fox_eac(life, 1.0, 5.0, rate, a) for a in ages] + best = ages[int(np.argmin(costs))] + assert policy.interval == pytest.approx(best, abs=0.6) + assert policy.eac == pytest.approx( + fox_eac(life, 1.0, 5.0, rate, policy.interval), rel=1e-7 + ) + assert policy.eac == pytest.approx(min(costs), rel=1e-6) + assert policy.npv == pytest.approx(policy.eac / rate) + # cost_rate keeps its meaning: the undiscounted rate at the age chosen. + assert policy.cost_rate == pytest.approx( + float(unit._cost_rate(policy.interval)) + ) + + +def test_the_present_value_agrees_with_a_simulation(): + # Draw the renewal process and add up its discounted costs, to where + # a cost is discounted to exp(-25). + unit = bearing() + rate = 0.002 + policy = unit.optimal_replacement_policy(discount_rate=rate) + age = policy.interval + rng = np.random.default_rng(7) + n = 40_000 + clock = np.zeros(n) + total = np.zeros(n) + while clock.min() < 25.0 / rate: + life = 1000.0 * rng.weibull(2.5, n) + failed = life < age + clock = clock + np.where(failed, life, age) + total += np.exp(-rate * clock) * np.where(failed, 5.0, 1.0) + error = total.std(ddof=1) / math.sqrt(n) + assert abs(total.mean() - policy.npv) < 4.0 * error + + +@pytest.mark.parametrize("yearly", [0.05, 0.10]) +def test_discounting_puts_the_replacement_off_for_a_part_that_wears_out( + yearly, +): + unit = bearing() + plain = unit.find_optimal_replacement() + found = unit.find_optimal_replacement(discount_rate=a_year(yearly)) + assert found > plain + assert ( + unit.find_optimal_replacement(discount_rate=a_year(2 * yearly)) > found + ) + days = bearing().find_optimal_replacement( + discount_rate=math.log1p(yearly) / 365.0 + ) + assert days > found + + +def test_as_the_rate_goes_to_zero_it_comes_to_the_cost_rate_optimum(): + unit = bearing() + plain = unit.optimal_replacement_policy() + previous = math.inf + for rate in (1e-4, 1e-5, 1e-6, 1e-8, 1e-10): + policy = unit.optimal_replacement_policy(discount_rate=rate) + gap = abs(policy.interval - plain.interval) + assert gap <= previous + 1e-6 + previous = gap + assert policy.eac < plain.cost_rate + assert policy.interval == pytest.approx(plain.interval, rel=1e-6) + assert policy.eac == pytest.approx(plain.cost_rate, rel=1e-6) + + +def test_discounting_can_make_running_to_failure_best(): + # cp close to cu: replacing pays undiscounted, but put off far enough + # by a high rate, the failures are cheaper. + unit = bearing(cp=4.0, cu=5.0) + life = unit.reliability + assert math.isfinite(unit.find_optimal_replacement()) + policy = unit.optimal_replacement_policy(discount_rate=3e-3) + assert policy.interval == math.inf + rtf = fox_run_to_failure(life, 5.0, 3e-3) + assert policy.eac == pytest.approx(rtf, rel=1e-6) + ages = np.linspace(200.0, 6000.0, 300) + best = min(fox_eac(life, 4.0, 5.0, 3e-3, a) for a in ages) + assert best >= rtf * (1 - 1e-9) + # cost_rate is running to failure's undiscounted: cu / MTTF. + assert policy.cost_rate == pytest.approx(5.0 / float(life.mean())) + + +@pytest.mark.parametrize( + "life", + [ + surv.Exponential.from_params([0.01]), + surv.Weibull.from_params([1e3, 0.8]), + ], +) +def test_a_life_that_does_not_wear_out_is_run_to_failure(life): + unit = bearing(life=life) + policy = unit.optimal_replacement_policy(discount_rate=1e-3) + assert policy.interval == math.inf + assert policy.eac == pytest.approx( + fox_run_to_failure(life, 5.0, 1e-3), rel=1e-6 + ) + + +def test_a_limited_failure_population_is_searched_when_discounted(): + # Undiscounted, running to failure is free in the long run; discounted + # it is not, and the search says which wins. + life = surv.Weibull.from_params([1000, 3.0], lfp_p=0.9) + unit = bearing(life=life) + assert unit.find_optimal_replacement() == math.inf + policy = unit.optimal_replacement_policy(discount_rate=1e-3) + sf = life.sf + rtf = ( + 1e-3 + * 5.0 + * ( + 1.0 + - 1e-3 + * quad( + lambda t: math.exp(-1e-3 * t) * float(np.ravel(sf(t))[0]), + 0.0, + np.inf, + limit=400, + )[0] + ) + / ( + 1e-3 + * quad( + lambda t: math.exp(-1e-3 * t) * float(np.ravel(sf(t))[0]), + 0.0, + np.inf, + limit=400, + )[0] + ) + ) + assert policy.eac <= rtf * (1 + 1e-6) + if math.isfinite(policy.interval): + assert policy.eac == pytest.approx( + fox_eac(life, 1.0, 5.0, 1e-3, policy.interval), rel=1e-6 + ) + + +def test_a_non_parametric_estimate_is_scanned_on_its_grid(): + # Failures at 10, 20, 30, 40: R(u) = 1 - u / 40 exactly. + unit = bearing(life=surv.KaplanMeier.fit([10, 20, 30, 40]), cp=1, cu=4) + rate = 0.02 + + def eac(t): + length = quad(lambda u: math.exp(-rate * u) * (1 - u / 40), 0, t)[0] + failed = quad(lambda u: math.exp(-rate * u) / 40, 0, t)[0] + kept = math.exp(-rate * t) * (1 - t / 40) + return (4 * failed + kept) / length + + ages = np.linspace(0.01, 40.0, 4000) + best = ages[int(np.argmin([eac(a) for a in ages]))] + policy = unit.optimal_replacement_policy(discount_rate=rate) + assert policy.interval == pytest.approx(best, abs=0.02) + assert policy.eac == pytest.approx(eac(policy.interval), rel=1e-5) + assert policy.interval > unit.find_optimal_replacement() + + +def test_a_standby_arrangement_is_discounted_too(): + # Two exponential units, cold standby: an Erlang-2 life, which wears + # out. + each = surv.Exponential.from_params([0.001]) + unit = bearing(life=StandbyModel([each, each]), cp=1.0, cu=10.0) + rate = 5e-4 + + def erlang_eac(t): + lam = 0.001 + sf = lambda u: math.exp(-lam * u) * (1 + lam * u) # noqa: E731 + length = quad(lambda u: math.exp(-rate * u) * sf(u), 0, t)[0] + failed = quad( + lambda u: math.exp(-rate * u) * lam**2 * u * math.exp(-lam * u), + 0, + t, + )[0] + kept = math.exp(-rate * t) * sf(t) + return (10.0 * failed + kept) / length + + ages = np.linspace(100.0, 3000.0, 2901) + best = ages[int(np.argmin([erlang_eac(a) for a in ages]))] + policy = unit.optimal_replacement_policy(discount_rate=rate) + assert policy.interval == pytest.approx(best, rel=2e-3) + assert policy.eac == pytest.approx(erlang_eac(policy.interval), rel=1e-4) + + +@pytest.mark.parametrize("rate", [-0.1, math.inf, "0.1", True]) +def test_a_discount_rate_out_of_range_is_refused(rate): + with pytest.raises(ValueError, match="discount_rate must be a number"): + bearing().optimal_replacement_policy(discount_rate=rate) + + +# ------------------------------------------------- a calendar in model time + +BEARING = NonRepairable( + surv.Weibull.from_params([1000.0, 2.5]), + planned_cost=1.0, + unplanned_cost=5.0, +) +SHUTS = Calendar( + [ + Opportunity("quarterly", 3.0, period=91.0), + Opportunity("annual", 1.0, period=364.0), + ], + failure=20.0, + anytime=None, +) +A_DAY_30 = math.log(1.3) / 364.0 + + +@pytest.mark.parametrize("method", ["dp", "integration"]) +def test_a_calendar_at_rate_zero_is_unchanged(method): + plain = BEARING.optimal_calendar_policy(SHUTS, method=method) + zero = BEARING.optimal_calendar_policy( + SHUTS, method=method, discount_rate=0.0 + ) + assert zero == plain + assert zero.npv == math.inf and zero.eac == plain.cost_rate + + +def test_a_calendar_with_only_any_day_is_discounted_age_replacement(): + policy = BEARING.optimal_calendar_policy(Calendar(), discount_rate=1e-3) + age = BEARING.optimal_replacement_policy(discount_rate=1e-3) + assert policy.eac == pytest.approx(age.eac, rel=1e-3) + planned = policy.next_replacement(age=0.0).time + assert planned == pytest.approx(age.interval, abs=2 * policy.step) + assert policy.eac == pytest.approx(1e-3 * policy.npv) + + +def test_the_calendar_s_present_value_is_a_long_horizon_s(): + # A plain backward sweep over many cycles from nothing, discounted a + # step at a time, comes to the long run's present value. + policy = BEARING.optimal_calendar_policy(SHUTS, discount_rate=A_DAY_30) + ages = _Ages(BEARING, policy.step, None) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + grid = _Grid(SHUTS, None, policy.step) + costs, _ = grid.prices(0, grid.cycle) + cycles = int(math.ceil(40.0 / (A_DAY_30 * 364.0))) + values, _, _ = _sweep( + np.zeros(ages.size + 1), + np.tile(costs, cycles), + ages.p, + 20.0, + math.exp(-A_DAY_30 * policy.step), + ) + assert policy.npv == pytest.approx(values[0], rel=1e-9) + low, high = policy.settings["npv_bounds"] + assert low <= policy.npv <= high + + +def test_the_grid_and_the_quadrature_agree_discounted(): + dp = BEARING.optimal_calendar_policy(SHUTS, discount_rate=A_DAY_30) + by_quadrature = BEARING.optimal_calendar_policy( + SHUTS, method="integration", discount_rate=A_DAY_30 + ) + assert by_quadrature.npv == pytest.approx(dp.npv, rel=1e-3) + assert by_quadrature._threshold(0.0) == pytest.approx( + dp._threshold(0.0), abs=1.0 + ) + + +def test_discounting_raises_the_calendar_s_thresholds(): + plain = BEARING.optimal_calendar_policy(SHUTS) + policy = BEARING.optimal_calendar_policy(SHUTS, discount_rate=A_DAY_30) + assert policy._threshold(0.0) > plain._threshold(0.0) + assert policy.eac < policy.cost_rate + # The long-run figures are the chosen rule's, undiscounted. + rule = {"annual": policy._threshold(0.0)} + assert policy.cost_rate == pytest.approx( + BEARING.calendar_policy_cost(SHUTS, rule), rel=1e-6 + ) + + +def test_a_calendar_s_rate_going_to_zero_comes_to_the_long_run_average(): + plain = BEARING.optimal_calendar_policy(SHUTS) + policy = BEARING.optimal_calendar_policy(SHUTS, discount_rate=1e-9) + assert policy.eac == pytest.approx(plain.cost_rate, rel=1e-6) + assert policy.schedule() == plain.schedule() + + +@pytest.mark.parametrize( + "calendar, options, match", + [ + ( + SHUTS, + {"method": "sampling"}, + "sampling.*no discount_rate.*horizon=", + ), + ( + Calendar([Opportunity("turnaround", 1.0, dates=[100.0, 400.0])]), + {}, + "given dates.*horizon=", + ), + ( + Calendar( + [ + Opportunity("a", 1.0, period=7.0), + Opportunity("b", 1.0, period=93.0), + Opportunity("c", 1.0, period=401.0), + ], + anytime=None, + ), + {"method": "dp"}, + "too long to discount.*horizon=", + ), + ], +) +def test_a_calendar_not_discounted_exactly_is_refused( + calendar, options, match +): + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + with pytest.raises(NotImplementedError, match=match): + BEARING.optimal_calendar_policy( + calendar, discount_rate=1e-3, **options + ) + + +def test_a_site_takes_discount_not_discount_rate(): + site = Shutdowns([], any_day=4.0) + with pytest.raises(ValueError, match="a site takes discount="): + BEARING.optimal_calendar_policy(site, discount_rate=1e-3) + + +# ---------------------------------------------- a site's shuts on dates + +NOW = "2026-11-16" +PLANT_PART = NonRepairable( + surv.Weibull.from_params([1000.0, 2.5]), unplanned_cost=20.0 +) +STOP = Shutdown( + "stop", Recurrence.every(4, "weeks", "2026-11-21"), replace_cost=3.0 +) +TURNAROUND = Shutdown( + "turnaround", dates=["2027-03-03", "2028-09-09"], replace_cost=0.5 +) + + +def site_policy(site, **options): + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + return PLANT_PART.optimal_calendar_policy( + site, unit="days", now=NOW, **options + ) + + +@pytest.mark.parametrize( + "site", [Shutdowns([STOP]), Shutdowns([STOP, TURNAROUND])] +) +def test_a_site_at_zero_discount_is_unchanged(site): + plain = site_policy(site) + zero = site_policy(site, discount=0.0) + assert zero.cost == plain.cost and zero.route_text == plain.route_text + assert zero.discount is None and zero.measure == "cost per year" + + +def test_a_site_s_discounted_long_run_is_a_long_horizon_s(): + site = Shutdowns([STOP]) + policy = site_policy(site, discount=0.3) + assert policy.route == "exact" and policy.discount == 0.3 + assert policy.measure == "equivalent annual cost" + assert policy.cost == pytest.approx(math.log1p(0.3) * policy.npv) + # The horizon route, its own programme on the real dates, to 50 + # years: what lies past it is discounted to about 2e-6. + horizon = site_policy(site, horizon="2076-11-16", discount=0.3) + assert horizon.cost == pytest.approx(policy.npv, rel=2e-4) + plain = site_policy(site) + assert policy.cost < plain.cost + assert policy.rule.thresholds["stop"][0] > plain.rule.thresholds["stop"][0] + assert policy.cost_rate == pytest.approx(plain.cost_rate, rel=1e-2) + + +def test_a_site_s_rate_going_to_zero_comes_to_the_long_run_average(): + site = Shutdowns([STOP]) + plain = site_policy(site) + policy = site_policy(site, discount=1e-9) + assert policy.cost == pytest.approx(plain.cost, rel=1e-6) + assert policy.rule.thresholds == plain.rule.thresholds + + +def test_any_day_alone_is_discounted_age_replacement(): + site = Shutdowns([], any_day=4.0) + part = NonRepairable( + surv.Weibull.from_params([1000.0, 2.5]), + planned_cost=4.0, + unplanned_cost=20.0, + ) + policy = part.optimal_calendar_policy( + site, unit="days", now=NOW, discount=0.07 + ) + age = part.optimal_replacement_policy( + discount_rate=math.log1p(0.07) / 365.25 + ) + assert policy.cost == pytest.approx(age.eac * 365.25, rel=1e-9) + assert policy.rule.thresholds["any other day"][0] == pytest.approx( + age.interval + ) + + +@pytest.mark.parametrize("failure_timing", ["half_step", "exact"]) +def test_the_dated_window_is_discounted_with_the_long_run_after_it( + failure_timing, +): + site = Shutdowns([STOP, TURNAROUND]) + policy = site_policy(site, discount=0.3, failure_timing=failure_timing) + assert policy.route == "dated_then_long_run" + assert policy.discount == 0.3 + assert policy.measure == "equivalent annual cost" + long_run = site_policy( + Shutdowns([STOP]), discount=0.3, failure_timing=failure_timing + ) + assert policy.cost == pytest.approx(long_run.cost) + assert policy.rule.thresholds == long_run.rule.thresholds + # The window's decisions are those of a long discounted horizon over + # the same real dates. + horizon = site_policy( + site, + horizon="2060-11-16", + discount=0.3, + failure_timing=failure_timing, + ) + assert policy.schedule("2028-09-09") == horizon.schedule("2028-09-09") + plain = site_policy(site, failure_timing=failure_timing) + assert policy.dated_cost < plain.dated_cost + assert "discounted long run at 30% a year" in policy.route_text + + +def test_a_dated_window_running_to_failure_after_it_is_discounted(): + policy = site_policy(Shutdowns([TURNAROUND]), discount=0.07) + life = PLANT_PART.reliability + rate = math.log1p(0.07) / 365.25 + assert policy.long_run_route == "run_to_failure" + assert policy.cost == pytest.approx( + fox_run_to_failure(life, 20.0, rate) * 365.25, rel=1e-6 + ) + + +@pytest.mark.parametrize( + "site, options, match", + [ + ( + Shutdowns([STOP]), + {"method": "averaged"}, + "long-run average, which is not discounted", + ), + ( + Shutdowns([STOP]), + {"method": "sampling"}, + "long-run average, which is not discounted", + ), + ( + Shutdowns( + [ + Shutdown( + "annual", + Recurrence.yearly( + month="November", weekday="Tuesday", nth=1 + ), + replace_cost=1.0, + ) + ] + ), + {}, + "discounted long run needs shuts that repeat", + ), + (Shutdowns([STOP]), {"discount": -0.1}, "yearly rate"), + ], +) +def test_a_site_not_discounted_exactly_is_refused(site, options, match): + options = {"discount": 0.07, **options} + with pytest.raises(ValueError, match=match): + site_policy(site, **options) + + +def test_a_duty_plan_with_a_discounted_long_run_is_refused(): + plan = DutyPlan(Shifts("Mon-Fri", "06:00", "22:00")) + with pytest.raises(ValueError, match="steady pace"): + site_policy(Shutdowns([STOP]), plan=plan, discount=0.07) + + +def test_compare_prices_each_rule_at_the_discounted_long_run(): + # Each simpler rule is priced as the policy is: its discounted long + # run, exactly (its EAC), so none beats the policy's own. + policy = site_policy(Shutdowns([STOP]), discount=0.07) + rows = policy.compare() + assert {r.measure for r in rows} == {"equivalent annual cost"} + assert all(r.cost >= policy.cost * (1 - 1e-9) for r in rows) + assert all(r.npv == pytest.approx(r.cost / math.log1p(0.07)) for r in rows) diff --git a/repyability/tests/test_downtime_risk.py b/repyability/tests/test_downtime_risk.py new file mode 100644 index 00000000..7f6a4f65 --- /dev/null +++ b/repyability/tests/test_downtime_risk.py @@ -0,0 +1,238 @@ +"""The least spend that keeps a bad run's downtime under a limit (UC-68 of +the maintenance README): ``RepairableRBD.least_spend_for_downtime`` and +the money module's risk measures (``repyability.value._risk``).""" + +import math + +import numpy as np +import pytest +import surpyval as surv +from scipy import optimize, stats + +from repyability import RepairableRBD +from repyability.maintenance import Prices, UnitPlan +from repyability.value import _risk + +E = surv.Exponential.from_params +W = surv.Weibull.from_params +ONE = [("s", "p"), ("p", "t")] +YEAR = 8760.0 +FAIL, REPAIR = 1e-3, 0.02 # a pump: 1,000 h between failures, 50 h repairs + + +def pump(**more): + return RepairableRBD( + ONE, + {"p": {"reliability": E([FAIL]), "repairability": E([REPAIR])}}, + **more, + ) + + +def worn(**preventive): + """A wearing unit, its 8 h task every 8,000 h, repairs of 72 h.""" + spec = { + "reliability": W([4000.0, 3.0]), + "repairability": E([1 / 72.0]), + "repair_cost": 2000.0, + "preventive": { + "interval": 8000.0, + "cost": 300.0, + "duration": surv.ExactEventTime.from_params([8.0]), + **preventive, + }, + } + return RepairableRBD(ONE, {"p": spec}) + + +INTERVALS = {"p": [4000.0, 2000.0, 1000.0, 500.0]} + + +def downtime_cdf(x, fail, repair, T, tail=1e-14): + """P(time down in [0, T] <= x) for a unit up at 0 with exponential + lives and repairs (an alternating renewal process): uniformised at + rate L, given n jumps the n + 1 spacings are Dirichlet(1, ..., 1), so + k of them spent down sum to T * Beta(k, n + 1 - k); the chance of k + comes from the uniformised chain.""" + L = max(fail, repair) + up_stays, down_stays = 1.0 - fail / L, 1.0 - repair / L + top = int(stats.poisson.isf(tail, L * T)) + 1 + u = min(max(x / T, 0.0), 1.0) + total = 0.0 + dp = np.zeros((2, top + 2)) + dp[0, 0] = 1.0 + for n in range(top + 1): + pk = dp.sum(axis=0)[: n + 2] + inner = pk[0] + (pk[n + 1] if u >= 1.0 else 0.0) + k = np.arange(1, n + 1) + if k.size: + inner += float(pk[1 : n + 1] @ stats.beta.cdf(u, k, n + 1 - k)) + total += stats.poisson.pmf(n, L * T) * inner + new = np.zeros_like(dp) + new[0] += dp[0] * up_stays + dp[1] * (1.0 - down_stays) + new[1, 1:] += dp[0, :-1] * (1.0 - up_stays) + dp[1, :-1] * down_stays + dp = new + return total + + +def test_the_exact_downtime_distribution_at_its_ends(): + # Never failing by T has chance exp(-fail T); never up is impossible. + assert downtime_cdf(0.0, FAIL, REPAIR, YEAR) == pytest.approx( + math.exp(-FAIL * YEAR), rel=1e-9 + ) + assert downtime_cdf(YEAR, FAIL, REPAIR, YEAR) == pytest.approx(1.0) + + +def test_a_single_unit_against_the_exact_percentile(): + exact = optimize.brentq( + lambda x: downtime_cdf(x, FAIL, REPAIR, YEAR) - 0.95, 1.0, YEAR + ) + density = ( + downtime_cdf(exact + 1.0, FAIL, REPAIR, YEAR) + - downtime_cdf(exact - 1.0, FAIL, REPAIR, YEAR) + ) / 2.0 + n = 4000 + found = pump().least_spend_for_downtime(YEAR, 1e6, mc_samples=n, seed=21) + design = found.design + # The quantile's standard error, sqrt(p (1 - p) / n) / f(q). + se = math.sqrt(0.95 * 0.05 / n) / density + assert abs(design.estimate - exact) < 4 * se + assert design.bound >= design.estimate + assert design.planned["mean_hours"] == 0.0 + assert found.met and found.bound_method.startswith("order statistic") + + +def test_the_quantile_bound_is_the_binomial_order_statistic(): + ordered = np.arange(1.0, 101.0) + bound = _risk.quantile_bound(ordered, 0.9, 0.95) + k = int(bound) # the k-th smallest + assert stats.binom.cdf(k - 1, 100, 0.9) >= 0.95 + assert stats.binom.cdf(k - 2, 100, 0.9) < 0.95 + assert _risk.quantile_bound(ordered[:10], 0.99, 0.95) == math.inf + assert _risk.tail_mean(ordered, 0.9) == pytest.approx(95.5) + + +def test_at_level_one_half_a_symmetric_loss_gives_its_median(): + values = stats.norm.rvs(size=2001, random_state=np.random.default_rng(6)) + found = _risk.risk(values, 0.5, "var", 0.95) + assert found.estimate == float(np.median(values)) + + +def test_redundancy_meets_any_target_at_a_rising_spend(): + spends = [] + for limit in (200.0, 50.0, 10.0, 1.0): + found = pump().least_spend_for_downtime( + YEAR, limit, redundancy={"p": 5000.0}, mc_samples=1000, seed=40 + ) + assert found.met and found.design.bound <= limit + spends.append(found.design.spend) + assert spends == sorted(spends) and spends[-1] > spends[0] + + +def test_more_spend_never_raises_the_frontier(): + found = worn().least_spend_for_downtime( + YEAR, + 10.0, + downtime="all", + intervals=INTERVALS, + mc_samples=1000, + seed=41, + ) + spends = [d.spend for d in found.frontier] + risks = [d.estimate for d in found.frontier] + assert spends == sorted(spends) + assert all(a > b for a, b in zip(risks, risks[1:])) + + +def test_cutting_unplanned_downtime_raises_planned_downtime(): + found = worn().least_spend_for_downtime( + YEAR, + 10.0, + downtime="unplanned", + intervals=INTERVALS, + mc_samples=1000, + seed=42, + ) + planned = [d.planned["mean_hours"] for d in found.frontier] + unplanned = [d.unplanned["bad_hours"] for d in found.frontier] + assert found.met + assert planned == sorted(planned) and planned[-1] > planned[0] + assert unplanned == sorted(unplanned, reverse=True) + + +def test_planned_downtime_is_the_floor_named(): + found = worn().least_spend_for_downtime( + YEAR, 10.0, intervals=INTERVALS, mc_samples=1000, seed=43 + ) + assert not found.met and found.floor == "planned" + assert "planned task downtime" in found.stopped + + +def test_the_budget_is_the_floor_named(): + found = pump().least_spend_for_downtime( + YEAR, + 100.0, + redundancy={"p": 5000.0}, + budget=3000.0, + mc_samples=500, + seed=44, + ) + assert not found.met and found.floor == "budget" + assert "budget" in found.stopped + + +def test_seeded_and_in_cost(): + one = pump(downtime_cost_rate=100.0).least_spend_for_downtime( + YEAR, + 5e4, + measure="cost", + redundancy={"p": 5000.0}, + mc_samples=500, + seed=45, + ) + again = pump(downtime_cost_rate=100.0).least_spend_for_downtime( + YEAR, + 5e4, + measure="cost", + redundancy={"p": 5000.0}, + mc_samples=500, + seed=45, + ) + hours = pump().least_spend_for_downtime( + YEAR, 500.0, redundancy={"p": 5000.0}, mc_samples=500, seed=45 + ) + assert [d.estimate for d in one.frontier] == [ + d.estimate for d in again.frontier + ] + assert one.frontier[0].estimate == pytest.approx( + 100.0 * hours.frontier[0].estimate, rel=1e-12 + ) + assert one.frontier[0].unplanned["bad_cost"] == pytest.approx( + 100.0 * hours.frontier[0].unplanned["bad_hours"], rel=1e-12 + ) + + +def test_a_plan_alone_takes_its_diagram_route(): + plan = UnitPlan(E([FAIL]), E([REPAIR]), prices=Prices(repair=10.0)) + mine = plan.least_spend_for_downtime( + YEAR, 100.0, redundancy={"unit": 5000.0}, mc_samples=500, seed=46 + ) + theirs = plan.diagram().least_spend_for_downtime( + YEAR, 100.0, redundancy={"unit": 5000.0}, mc_samples=500, seed=46 + ) + assert mine.design.estimate == theirs.design.estimate + assert plan.analysis_routes()["least_spend_for_downtime"].route == ( + "simulated" + ) + + +def test_refusals(): + with pytest.raises(ValueError, match="needs downtime to cost"): + pump().least_spend_for_downtime(YEAR, 10.0, measure="cost") + with pytest.raises(ValueError, match="no preventive task"): + pump().least_spend_for_downtime(YEAR, 10.0, intervals={"p": [100]}) + with pytest.raises(ValueError, match="level"): + pump().least_spend_for_downtime(YEAR, 10.0, level=1.0) + with pytest.raises(ValueError, match="price of a copy"): + pump().least_spend_for_downtime(YEAR, 10.0, redundancy={"p": 0.0}) + with pytest.raises(ValueError, match="limit"): + pump().least_spend_for_downtime(YEAR, -1.0) diff --git a/repyability/tests/test_duty_plans.py b/repyability/tests/test_duty_plans.py new file mode 100644 index 00000000..8f9b2d7c --- /dev/null +++ b/repyability/tests/test_duty_plans.py @@ -0,0 +1,253 @@ +"""Duty plans that change over time, and the calendar an analysis runs on +(UC-64 of the schedule README). + +A block's ``"duty"`` takes a share of the time or a ``DutySchedule``: on a +plan that changes, its life is drawn in operating hours and put on the +calendar through the plan (``_duty.PlannedLife``), and a task counted in +operating time falls when the plan reaches it. A unit whose repairs and +tasks take no time is then its operating-time process seen through the +plan, ``M(D(t))``, which the exact methods give on the one-node diagram +with no duty. +""" + +import math + +import numpy as np +import pytest +import surpyval as surv + +from repyability import NodeState, RepairableRBD +from repyability.rbd import _compiled, _event_loop +from repyability.rbd._duty import PlannedLife +from repyability.rbd.serialisation import rbd_from_json, rbd_to_json +from repyability.schedule import ( + CalendarContext, + DutyPlan, + DutySchedule, + Recurrence, + Shifts, + UsageForecast, + events_by_period, +) + +ONE = [("s", "a"), ("a", "t")] +W = surv.Weibull.from_params([400.0, 2.0]) +PLAN = DutySchedule( + "hours", (0.0, 1000.0, 2000.0, 3000.0), (1.0, 0.25, 0.0, 0.5) +) + + +def planned(**more): + spec = {"reliability": W, "repairability": "instant", "repair_cost": 1.0} + return RepairableRBD(ONE, {"a": {**spec, **more, "duty": PLAN}}) + + +# -- the plan's clock ------------------------------------------------------- + + +def test_the_operating_time_and_its_inverse(): + life = PlannedLife(W, PLAN, "a") + t = np.array([0.0, 500.0, 1000.0, 1400.0, 2500.0, 3000.0, 3600.0]) + np.testing.assert_array_equal( + life.operating(t), [0.0, 500.0, 1000.0, 1100.0, 1250.0, 1250.0, 1550.0] + ) + # The first time each is reached: a stretch at no duty is passed over. + assert [life.inverse(h) for h in (0.0, 1100.0, 1250.0, 1550.0)] == [ + 0.0, + 1400.0, + 2000.0, + 3600.0, + ] + np.testing.assert_allclose(life.sf(t), W.sf(life.operating(t))) + + +def test_a_life_is_drawn_in_operating_hours_from_when_it_starts(): + life = PlannedLife(W, PLAN, "a") + u = 0.3 + x = float(W.qf(np.array([u]))[0]) + # Put in at 1500 h (1125 operating hours), it fails when the plan + # has run x more. + assert life.life_left(1500.0, 0.0, u) == life.inverse(1125.0 + x) - 1500.0 + + +def test_a_plan_of_one_share_is_that_duty_to_the_bit(): + one = DutySchedule("hours", (0.0,), (0.25,)) + spec = { + "reliability": W, + "repairability": surv.Exponential.from_params([0.1]), + } + by_plan = RepairableRBD(ONE, {"a": {**spec, "duty": one}}) + by_share = RepairableRBD(ONE, {"a": {**spec, "duty": 0.25}}) + assert by_plan.components["a"].reliability.params.tolist() == ( + by_share.components["a"].reliability.params.tolist() + ) + a = by_plan.availability(2000.0, mc_samples=200, seed=4) + b = by_share.availability(2000.0, mc_samples=200, seed=4) + np.testing.assert_array_equal(a.availability, b.availability) + + +# -- the simulation against the operating-time process ---------------------- + + +@pytest.mark.parametrize( + "task", + [ + None, + {"policy": "block", "interval": 300.0}, + {"policy": "age", "interval": 300.0}, + ], + ids=["run to failure", "block", "age"], +) +def test_a_unit_is_its_operating_process_seen_through_its_plan(task): + more = ( + {} if task is None else {"preventive": {**task, "basis": "operating"}} + ) + rbd = planned(**more) + end = 4000.0 + hours = rbd.components["a"].reliability.operating(end) + spec = {"reliability": W, "repairability": "instant", "repair_cost": 1.0} + if task is not None: + spec["preventive"] = dict(task) + exact = RepairableRBD(ONE, {"a": spec}).expected_events_by_window( + np.array([hours]) + ) + run = rbd.cost(end, mc_samples=4000, seed=7) + # Bounds fixed before the run: four standard errors. + assert abs(run.mean - exact.node_failures["a"][0]) < 4.0 * run.mean_se + + +def test_a_usage_task_falls_where_the_forecast_reaches_it(): + frame = UsageForecast.calendar("2027-01-01", "2028-01-01") + shifts = DutyPlan(Shifts("Mon-Fri", "06:00", "22:00")).forecast( + "2027-01-01", "2028-01-01" + ) + context = CalendarContext(frame, {"a": shifts}) + spec = { + "reliability": surv.Weibull.from_params([3000.0, 2.0]), + "repairability": "instant", + "preventive": {"interval": 4000.0, "basis": "operating"}, + } + rbd = context.diagram(RepairableRBD(ONE, {"a": spec})) + due = rbd._preventive["a"].due(0.0) + expected = context.model_time([shifts.moment(4000.0)])[0] + assert math.isclose(due, expected, rel_tol=0.0, abs_tol=1e-9) + assert shifts.moment(4000.0).isoformat().startswith("2027-12-16T22:00") + + +def test_a_task_on_a_rule_is_replaced_at_its_dates(): + frame = UsageForecast.calendar("2027-01-01", "2028-01-01") + context = CalendarContext(frame) + rule = Recurrence.monthly( + weekday="Monday", nth=1, every=3, anchor="2027-01-01" + ) + spec = { + "reliability": W, + "repairability": "instant", + "preventive": {"replace_at": context.rule_times(rule, at="06:00")}, + } + rbd = context.diagram(RepairableRBD(ONE, {"a": spec})) + # 4 January, 5 April, 5 July and 4 October, at 06:00. + days = np.array([3, 94, 185, 276]) * 24.0 + 6.0 + np.testing.assert_allclose(rbd._preventive["a"].times, days) + + +def test_events_by_period_on_a_plan_that_changes(): + frame = UsageForecast.calendar("2027-01-01", "2027-04-01") + shifts = DutyPlan(Shifts("Mon-Fri", "06:00", "22:00")).forecast( + "2027-01-01", "2027-04-01" + ) + spec = { + "reliability": surv.Weibull.from_params([300.0, 2.0]), + "repairability": surv.Exponential.from_params([0.125]), + "repair_cost": 100.0, + } + rbd = RepairableRBD(ONE, {"a": spec}) + months = events_by_period( + rbd, + CalendarContext(frame, {"a": shifts}), + cost=True, + discount=0.07, + mc_samples=300, + seed=2, + ) + assert "simulations' histories" in months.notes[0] + failures = months.events.node_failures["a"] + np.testing.assert_allclose(months.cost.simulated_mean, failures * 100.0) + assert np.all(months.expected_npv < months.cost.mean) + + +# -- saving and what is refused --------------------------------------------- + + +def test_saving_keeps_the_plan(): + rbd = planned() + again = rbd_from_json(rbd_to_json(rbd)) + assert again._init_args["components"]["a"]["duty"] == PLAN + a = rbd.availability(3000.0, mc_samples=100, seed=1).availability + b = again.availability(3000.0, mc_samples=100, seed=1).availability + np.testing.assert_array_equal(a, b) + + +def test_the_compiled_engine_hands_it_to_python(): + rbd = planned() + plan = _event_loop._stream_plan(rbd, 1.0, 0, False)[0] + reason = _compiled.unsupported(rbd, plan, None, numba=True) + assert reason == "the duty plan that changes over time of node 'a'" + + +@pytest.mark.parametrize( + "more, words", + [ + ({"repair": {"model": "kijima1", "q": 0.5}}, "virtual age"), + ( + { + "preventive": { + "policy": "condition", + "interval": 50.0, + "threshold": 0.1, + } + }, + "on condition", + ), + ( + {"inspection": {"interval": 100.0, "basis": "operating"}}, + "tests counted in operating time", + ), + ], +) +def test_what_a_plan_that_changes_refuses(more, words): + with pytest.raises(NotImplementedError, match=words): + planned(**more) + + +def test_the_exact_methods_refuse_and_a_state_must_be_new(): + rbd = planned() + with pytest.raises(NotImplementedError, match="changes over time"): + rbd.expected_events_by_window(np.array([1000.0])) + with pytest.raises(NotImplementedError, match="other than new"): + rbd.availability( + 1000.0, mc_samples=10, seed=1, state={"a": NodeState(age=10.0)} + ) + + +def test_a_plan_is_checked(): + with pytest.raises(ValueError, match="must start at 0"): + RepairableRBD( + ONE, + { + "a": { + "reliability": W, + "duty": DutySchedule("hours", (5.0, 9.0), (1.0, 0.5)), + } + }, + ) + with pytest.raises(ValueError, match=r"in \[0, 1\]"): + RepairableRBD( + ONE, + { + "a": { + "reliability": W, + "duty": DutySchedule("hours", (0.0, 9.0), (1.0, 1.5)), + } + }, + ) diff --git a/repyability/tests/test_duty_tasks.py b/repyability/tests/test_duty_tasks.py index 3e83c2a5..4ac83246 100644 --- a/repyability/tests/test_duty_tasks.py +++ b/repyability/tests/test_duty_tasks.py @@ -385,11 +385,16 @@ def test_saving_keeps_the_running_hours_and_the_basis(): # -- what is refused --------------------------------------------------------- -def test_a_task_in_running_hours_needs_a_duty(): +def test_a_task_in_running_hours_with_no_duty_runs_on_the_clock(): + # The duty plan belongs to the analysis (schedule.CalendarContext): + # with none, the diagram's clock is the block's operating time. spec = pump(interval=EVERY) del spec["duty"] - with pytest.raises(ValueError, match="give the block's duty, the share"): - RepairableRBD(ONE, {"p": spec}) + alone = RepairableRBD(ONE, {"p": spec}) + full = RepairableRBD(ONE, {"p": {**spec, "duty": 1.0}}) + assert alone._preventive["p"] == full._preventive["p"] + assert alone._preventive["p"].interval == EVERY + assert alone.mean_availability() == full.mean_availability() def test_a_calendar_policy_is_not_counted_in_running_hours(): diff --git a/repyability/tests/test_exact_or_horizon.py b/repyability/tests/test_exact_or_horizon.py new file mode 100644 index 00000000..9da2861f --- /dev/null +++ b/repyability/tests/test_exact_or_horizon.py @@ -0,0 +1,519 @@ +"""Exact by default; refuse what can't be done exactly; ``horizon=`` +never refuses (UC-44, the maintainer's decision of 16 Nov 2026). + +Checked against independent workings: the horizon's equivalent annual +cost against the exact discounted long run as the horizon lengthens; +each refusal's ready horizon run as given, and again doubled; a fixed +rule's discounted price against a plain backward sweep over many cycles +and a seeded simulation of its discounted costs; and the next +replacement's discounted choices against present values worked out by +quadrature from the density. +""" + +import math +import re +import warnings +from datetime import date + +import numpy as np +import pytest +import surpyval as surv +from scipy.integrate import quad + +from repyability import NonRepairable, Opportunities, Opportunity +from repyability._version import __version__ +from repyability.maintenance import _replacement as R +from repyability.schedule import DutyPlan, Recurrence, Shifts +from repyability.utils.deprecation import NEXT_REMOVAL + +NOW = "2026-11-16" +A_DAY = math.log(1.07) / 365.25 +LIFE = surv.Weibull.from_params([1000.0, 2.5]) + +# The 28-day stop: replace at a stop for 3, a failure 20, 7% a year. +PART = NonRepairable(LIFE, unplanned_cost=20.0, opportunity_cost=3.0) +STOPS = Opportunities([Opportunity("stop", period=28.0)], any_day=False) +STOPS_ON_DATES = Opportunities( + [Opportunity("stop", Recurrence.every(4, "weeks", "2026-11-21"))], + any_day=False, +) + +# (a): the 7, 93 and 401-day shuts, any other day 4, failure 40. +WORN = NonRepairable( + surv.Weibull.from_params([1000.0, 5.0]), + planned_cost=4.0, + unplanned_cost=40.0, + opportunity_costs={"a": 3.0, "b": 2.0, "c": 1.0}, +) +COPRIME = Opportunities( + [ + Opportunity("a", period=7.0), + Opportunity("b", period=93.0), + Opportunity("c", period=401.0), + ] +) +# (b), (c), (e): a part replaced at a shut for 1, any day 4, failure 20. +SHUT_PART = NonRepairable( + LIFE, planned_cost=4.0, unplanned_cost=20.0, opportunity_cost=1.0 +) +GIVEN = Opportunities([Opportunity("turnaround", dates=[100.0, 400.0])]) +ANNUAL = Opportunities( + [ + Opportunity( + "annual shut", + Recurrence.yearly(month="November", weekday="Tuesday", nth=1), + ) + ], + any_day=False, +) +# (d): weekday shifts, the bearing's life in hours. +SHIFTS = DutyPlan(Shifts("Mon-Fri", "06:00", "22:00")) +HOURS_PART = NonRepairable( + surv.Weibull.from_params([20_000.0, 2.5]), + planned_cost=4.0, + unplanned_cost=40.0, + opportunity_cost=1.0, +) + + +def model_horizon(message: str) -> float: + found = re.search(r"horizon=(\d+(?:\.\d+)?)", message) + assert found, message + return float(found.group(1)) + + +def site_horizon(message: str) -> str: + found = re.search(r"horizon='(\d{4}-\d{2}-\d{2})'", message) + assert found, message + return found.group(1) + + +def doubled(day: str) -> str: + now = date.fromisoformat(NOW) + return (now + 2 * (date.fromisoformat(day) - now)).isoformat() + + +@pytest.fixture(scope="module") +def exact_28(): + return PART.optimal_opportunity_policy(STOPS, discount_rate=A_DAY) + + +# ------------------------------------------------ horizon against exact + + +def test_the_horizon_s_eac_comes_to_the_exact_one(exact_28): + # The exact discounted long run: 4.216 a year, from 419.1 days. + assert exact_28.eac * 365.25 == pytest.approx(4.21646, abs=1e-5) + assert exact_28._threshold(0.0) == pytest.approx(419.125) + gaps = [] + for years in (10, 50, 100, 307): + policy = PART.optimal_opportunity_policy( + STOPS, discount_rate=A_DAY, horizon=years * 365.25 + ) + assert policy.basis == "horizon" + gaps.append(abs(policy.eac - exact_28.eac) / exact_28.eac) + if years < 50: + continue # a part's life from the end: early decisions move + # Its first decisions are the exact thresholds, within a step. + for t in (0.0, 28.0, 420.0, 840.0): + assert abs(policy._threshold(t) - exact_28._threshold(t)) <= ( + policy.step + 1e-9 + ) + assert policy.next_replacement(0.0) == exact_28.next_replacement(0.0) + assert gaps == sorted(gaps, reverse=True) + assert gaps[-1] < 1e-8 + # Its present value comes to the long run's too. + assert policy.npv == pytest.approx(exact_28.npv, rel=1e-8) + + +def test_on_real_dates_the_horizon_comes_to_the_exact_one(): + exact = PART.optimal_opportunity_policy( + STOPS_ON_DATES, unit="days", now=NOW, discount=0.07 + ) + assert exact.eac == exact.cost + horizon = PART.optimal_opportunity_policy( + STOPS_ON_DATES, + unit="days", + now=NOW, + discount=0.07, + horizon="2333-11-16", + ) + # The horizon's grid is sized from the life alone (the stops laid at + # its nearest steps), the exact route's put on the stops: the two + # grids differ by about 1.5e-5. + assert horizon.eac == pytest.approx(exact.cost, rel=5e-5) + assert horizon.cost == pytest.approx(exact.npv, rel=5e-5) + assert "equivalent annual cost" in horizon.route_text + assert horizon.next_replacement == exact.next_replacement + + +def test_an_undiscounted_horizon_is_the_total_to_it(): + policy = PART.optimal_opportunity_policy(STOPS, horizon=36525.0) + assert policy.discount_rate == 0.0 + # The total cost to the horizon, the expected costs of every step. + # (The horizon rounded up to a whole step of the grid.) + length = policy.settings["horizon"] + assert 36525.0 <= length < 36525.0 + policy.step + assert policy.npv == pytest.approx(policy.cost_rate * length, rel=1e-5) + assert policy.eac == pytest.approx(policy.npv / length) + plain = PART.optimal_opportunity_policy(STOPS) + # Near the long-run rate, a little under it: the part in service at + # the horizon is not paid for (about one cycle's cost over 100 years). + assert plain.cost_rate * 0.99 < policy.eac < plain.cost_rate + + +def test_a_horizon_in_model_time_is_a_number(): + with pytest.raises(ValueError, match="in their own time"): + PART.optimal_opportunity_policy(STOPS, horizon="2036-11-16") + with pytest.raises(ValueError, match="its own route"): + PART.optimal_opportunity_policy( + STOPS, horizon=3650.0, method="sampling" + ) + + +# ------------------------------------------- the cases once refused + + +def test_a_periods_that_repeat_too_late_to_discount(): + with pytest.raises(NotImplementedError) as refused: + WORN.optimal_opportunity_policy(COPRIME, discount_rate=A_DAY) + message = str(refused.value) + assert "too long to discount" in message + assert "one part in a billion" in message + horizon = model_horizon(message) + assert horizon == 112_000.0 + policy = WORN.optimal_opportunity_policy( + COPRIME, discount_rate=A_DAY, horizon=horizon + ) + longer = WORN.optimal_opportunity_policy( + COPRIME, discount_rate=A_DAY, horizon=2 * horizon + ) + assert longer.npv == pytest.approx(policy.npv, rel=1e-8) + assert longer.eac == pytest.approx(policy.eac, rel=1e-8) + assert longer.next_replacement(0.0) == policy.next_replacement(0.0) + + +def test_b_given_dates_in_model_time_with_a_discount(): + with pytest.raises(NotImplementedError) as refused: + SHUT_PART.optimal_opportunity_policy(GIVEN, discount_rate=A_DAY) + message = str(refused.value) + assert "given dates" in message and "nothing assumed" in message + horizon = model_horizon(message) + policy = SHUT_PART.optimal_opportunity_policy( + GIVEN, discount_rate=A_DAY, horizon=horizon + ) + longer = SHUT_PART.optimal_opportunity_policy( + GIVEN, discount_rate=A_DAY, horizon=2 * horizon + ) + assert longer.npv == pytest.approx(policy.npv, rel=1e-8) + assert longer.schedule(until=500.0) == policy.schedule(until=500.0) + + +def test_c_a_shut_that_drifts_on_real_dates(): + with pytest.raises(ValueError) as refused: + SHUT_PART.optimal_opportunity_policy( + ANNUAL, unit="days", now=NOW, discount=0.07 + ) + message = str(refused.value) + assert "364 or 371 days apart" in message + horizon = site_horizon(message) + assert horizon == "2333-11-16" + assert "discount=0.07" in message and "one part in a billion" in message + policy = SHUT_PART.optimal_opportunity_policy( + ANNUAL, unit="days", now=NOW, discount=0.07, horizon=horizon + ) + longer = SHUT_PART.optimal_opportunity_policy( + ANNUAL, unit="days", now=NOW, discount=0.07, horizon=doubled(horizon) + ) + assert policy.route == "horizon" + assert longer.cost == pytest.approx(policy.cost, rel=1e-8) + assert longer.eac == pytest.approx(policy.eac, rel=1e-8) + assert longer.next_replacement == policy.next_replacement + + +def test_d_a_duty_plan_with_a_discount(): + with pytest.raises(ValueError) as refused: + HOURS_PART.optimal_opportunity_policy( + STOPS_ON_DATES, plan=SHIFTS, unit="hours", now=NOW, discount=0.07 + ) + message = str(refused.value) + assert "steady pace" in message + horizon = site_horizon(message) + policy = HOURS_PART.optimal_opportunity_policy( + STOPS_ON_DATES, + plan=SHIFTS, + unit="hours", + now=NOW, + discount=0.07, + horizon=horizon, + ) + longer = HOURS_PART.optimal_opportunity_policy( + STOPS_ON_DATES, + plan=SHIFTS, + unit="hours", + now=NOW, + discount=0.07, + horizon=doubled(horizon), + ) + assert longer.cost == pytest.approx(policy.cost, rel=1e-8) + assert longer.next_replacement == policy.next_replacement + + +def test_e_a_given_rule_at_a_discount_where_nothing_repeats(): + rule = {"annual shut": 400.0} + with pytest.raises(ValueError) as refused: + SHUT_PART.opportunity_policy_cost( + ANNUAL, rule, unit="days", now=NOW, discount=0.07 + ) + horizon = site_horizon(str(refused.value)) + priced = SHUT_PART.opportunity_policy_cost( + ANNUAL, rule, unit="days", now=NOW, discount=0.07, horizon=horizon + ) + longer = SHUT_PART.opportunity_policy_cost( + ANNUAL, + rule, + unit="days", + now=NOW, + discount=0.07, + horizon=doubled(horizon), + ) + assert priced.measure == "net present cost" + assert longer.cost == pytest.approx(priced.cost, rel=1e-8) + assert priced.eac == pytest.approx(priced.npv * 0.0676586, rel=1e-4) + # And in model time: given dates refuse, the horizon prices them. + with pytest.raises(NotImplementedError) as refused: + SHUT_PART.opportunity_policy_cost( + GIVEN, {"turnaround": 50.0}, discount_rate=A_DAY + ) + horizon_t = model_horizon(str(refused.value)) + once = SHUT_PART.opportunity_policy_cost( + GIVEN, {"turnaround": 50.0}, discount_rate=A_DAY, horizon=horizon_t + ) + twice = SHUT_PART.opportunity_policy_cost( + GIVEN, + {"turnaround": 50.0}, + discount_rate=A_DAY, + horizon=2 * horizon_t, + ) + assert twice == pytest.approx(once, rel=1e-8) + + +# ------------------------------------------------ a fixed rule, priced + + +def test_the_optimiser_s_rule_prices_at_its_own_eac(exact_28): + rule = {"stop": exact_28._threshold(0.0)} + eac = PART.opportunity_policy_cost(STOPS, rule, discount_rate=A_DAY) + assert eac == pytest.approx(exact_28.eac, rel=1e-9) + on_dates = PART.optimal_opportunity_policy( + STOPS_ON_DATES, unit="days", now=NOW, discount=0.07 + ) + priced = PART.opportunity_policy_cost( + STOPS_ON_DATES, + {"stop": on_dates.rule.thresholds["stop"][0]}, + unit="days", + now=NOW, + discount=0.07, + ) + assert priced.measure == "equivalent annual cost" + assert priced.cost == pytest.approx(on_dates.cost, rel=1e-9) + assert priced.npv == pytest.approx(on_dates.npv, rel=1e-9) + + +def test_a_fixed_rule_s_eac_against_a_plain_backward_sweep(): + rule = {"stop": 300.0} + eac = PART.opportunity_policy_cost(STOPS, rule, discount_rate=A_DAY) + # A plain backward sweep with the decisions fixed, from nothing, + # over enough cycles that what lies past them is discounted away. + calendar, _ = __import__( + "repyability.maintenance._opportunities", fromlist=["resolve"] + ).resolve(PART, STOPS) + step = R._resolve_step(None, calendar, PART) + ages = R._Ages(PART, step, None) + grid = R._Grid(calendar, None, step) + n = int(math.ceil(150_000.0 / step)) + costs, first = R._rule_prices(grid, rule, 0, n) + v, _, _ = R._sweep( + np.zeros(ages.size + 1), + costs, + ages.p, + 20.0, + math.exp(-A_DAY * step), + fixed=first, + ) + assert eac == pytest.approx(A_DAY * v[0], rel=1e-8) + + +def test_a_fixed_rule_s_present_value_against_a_simulation(): + # Replace at the first stop at which the part is 300 days old or + # more, at 3; a failure renews it at once, at 20; every cost + # discounted to now at 7% a year. + rule = {"stop": 300.0} + eac = PART.opportunity_policy_cost(STOPS, rule, discount_rate=A_DAY) + rng = np.random.default_rng(20261116) + paths = 20_000 + t = np.zeros(paths) + total = np.zeros(paths) + while True: + alive = np.exp(-A_DAY * t) > 1e-10 + if not alive.any(): + break + life = 1000.0 * rng.weibull(2.5, paths) + due = np.ceil((t + 300.0) / 28.0 - 1e-12) * 28.0 + fails = t + life < due + when = np.where(fails, t + life, due) + price = np.where(fails, 20.0, 3.0) + total += np.where(alive, price * np.exp(-A_DAY * when), 0.0) + t = when + npv = total.mean() + se = total.std(ddof=1) / math.sqrt(paths) + assert abs(eac / A_DAY - npv) < 4 * se + + +def test_a_fixed_rule_by_quadrature_discounted(): + policy = PART.optimal_opportunity_policy( + STOPS_ON_DATES, + unit="days", + now=NOW, + discount=0.07, + failure_timing="exact", + ) + priced = PART.opportunity_policy_cost( + STOPS_ON_DATES, + {"stop": policy.rule.thresholds["stop"][0]}, + unit="days", + now=NOW, + discount=0.07, + failure_timing="exact", + ) + assert priced.cost == pytest.approx(policy.cost, rel=1e-6) + + +def test_a_rule_whose_long_run_cannot_be_discounted_is_refused(): + with pytest.raises(NotImplementedError, match="horizon=") as refused: + WORN.opportunity_policy_cost(COPRIME, {"c": 0.0}, discount_rate=A_DAY) + assert "one part in a billion" in str(refused.value) + + +def test_rate_zero_prices_as_before(): + rule = {"stop": 300.0} + assert PART.opportunity_policy_cost( + STOPS, rule, discount_rate=0.0 + ) == PART.opportunity_policy_cost(STOPS, rule) + + +# ----------------------------------------- the next replacement + + +def brute_force(part, age, policy, u, price): + """A choice's present value from the density, with every later + replacement valued at the policy's present value ``V``, less ``V``: + failures before ``u`` at the failure price, else ``price`` at ``u``, + each discounted to when it falls.""" + r, value = policy.discount_rate, policy.npv + life = part.reliability + held = float(life.sf(age)) + + def failing(t): + return math.exp(-r * t) * float(life.df(age + t)) / held + + failed = quad(failing, 0.0, u, limit=400)[0] + kept = ( + 0.0 + if math.isinf(u) + else math.exp(-r * u) * float(life.sf(age + u)) / held + ) + return (part.cu + value) * failed + (price + value) * kept - value + + +def test_the_next_replacement_s_choices_are_discounted(exact_28): + part = NonRepairable( + LIFE, planned_cost=4.0, unplanned_cost=20.0, opportunity_cost=3.0 + ) + found = part.optimal_next_replacement( + 300.0, + now_cost=20.0, + scheduled_outages=[(20.0, 3.0), (48.0, 3.0), (300.0, 3.0)], + policy=exact_28, + ) + assert found.discount_rate == exact_28.discount_rate + assert found.cost_rate == exact_28.eac + for choice in found.choices[1:]: + if choice.kind == "planned": + continue + assert choice.cost == pytest.approx( + brute_force(part, 300.0, exact_28, choice.time, choice.price), + rel=1e-6, + abs=1e-9, + ) + + +def test_a_discounted_age_policy_s_planned_choice_against_brute_force(): + part = NonRepairable(LIFE, planned_cost=1.0, unplanned_cost=5.0) + policy = part.optimal_replacement_policy(discount_rate=A_DAY) + found = part.optimal_next_replacement(200.0, policy=policy) + planned = next(c for c in found.choices if c.kind == "planned") + assert planned.cost == pytest.approx( + brute_force(part, 200.0, policy, planned.time, 1.0), rel=1e-6 + ) + # The best time is the discounted one: no time nearby is cheaper. + for du in (-5.0, 5.0): + assert ( + planned.cost + <= brute_force(part, 200.0, policy, planned.time + du, 1.0) + 1e-12 + ) + # From the policy's own age replacing now is the best (Fox's + # optimum, to the search's tolerance). + assert found.replace_from_age == pytest.approx(policy.interval, rel=2e-3) + + +def test_the_next_replacement_at_rate_zero_is_unchanged(): + part = NonRepairable( + surv.Weibull.from_params([365.0, 2.0]), + planned_cost=150.0, + unplanned_cost=400.0, + ) + found = part.optimal_next_replacement( + 200.0, scheduled_outages=[(150.0, 100.0), (330.0, 100.0)] + ) + assert found.discount_rate == 0.0 + assert round(found.replace_from_age, 1) == 297.6 + + +def test_on_real_dates_the_choices_are_discounted_at_the_policy_s_rate(): + policy = PART.optimal_opportunity_policy( + STOPS_ON_DATES, unit="days", now=NOW, discount=0.07 + ) + found = PART.optimal_next_replacement( + 300.0, site=STOPS_ON_DATES, unit="days", now=NOW, policy=policy + ) + assert found.discount_rate == pytest.approx(A_DAY) + assert "discounted at 7% a year" in found.valued_by + + +# ------------------------------------------ method="auto" sampling + + +def test_auto_sampling_warns_it_will_refuse_with_a_ready_horizon(): + with pytest.warns(FutureWarning, match=f"From {NEXT_REMOVAL}") as w: + sampled = WORN.optimal_opportunity_policy( + COPRIME, mc_samples=2, seed=1 + ) + assert sampled.method == "sampling" + message = str(w[0].message) + assert "method='sampling'" in message + # The full cycle (261,051 days) and three life spans. + assert model_horizon(message) == 266_000.0 + with warnings.catch_warnings(): + warnings.simplefilter("error") + WORN.optimal_opportunity_policy( + COPRIME, method="sampling", mc_samples=2, seed=1 + ) + + +def test_auto_sampling_refuses_in_0_21(): + # method="auto" sampling a long cycle warns (a FutureWarning) for + # 0.20 and refuses from 0.21. This fails as a reminder once the + # version reaches it: make "auto" refuse with its ready horizon. + version = tuple(map(int, __version__.split(".")))[:2] + assert version < tuple(map(int, NEXT_REMOVAL.split("."))) diff --git a/repyability/tests/test_failure_finding_window.py b/repyability/tests/test_failure_finding_window.py new file mode 100644 index 00000000..7f1cc3bf --- /dev/null +++ b/repyability/tests/test_failure_finding_window.py @@ -0,0 +1,351 @@ +"""A hidden failure tested at given times over a window: +``failure_finding_window`` (UC-53 of ``repyability/maintenance/README.md``). + +Checked against an exponential device's closed forms (a two-state chain +where demands reveal), ``failure_finding``'s long run, and a simulation +of the plan written out plainly here. +""" + +import json +import math + +import numpy as np +import pytest +import surpyval as surv + +from repyability import ( + FailureFindingWindow, + NonRepairable, + failure_finding, + failure_finding_window, +) + + +def exponential(rate): + return NonRepairable(surv.Exponential.from_params([rate])) + + +def closed_form(rate, tests, window, reveal=0.0, discount=0.0): + """An exponential device tested at ``tests``: what each test finds, + the failed time, and the failed time discounted. From a test (or the + start) the chance of being failed after ``s`` is ``rate / k (1 - + exp(-k s))``, ``k = rate + reveal``.""" + k = rate + reveal + edges = [0.0, *[t for t in tests if 0.0 < t < window], window] + found, failed, discounted = [], 0.0, 0.0 + for start, end in zip(edges[:-1], edges[1:]): + length = end - start + found.append(rate / k * -math.expm1(-k * length)) + failed += rate / k * (length + math.expm1(-k * length) / k) + if discount > 0.0: + discounted += ( + rate + / k + * math.exp(-discount * start) + * ( + -math.expm1(-discount * length) / discount + + math.expm1(-(discount + k) * length) / (discount + k) + ) + ) + if discount == 0.0: + discounted = failed + if not (tests and tests[-1] == window): + found = found[:-1] + return np.array(found), failed, discounted + + +def test_uc53_trip_tested_at_uneven_times(): + """The worked example: 0.1 a year, tests at 6 and 12 months and 2 + years, over 3 years; a demand every 2 years.""" + trip = exponential(0.1) + prices = dict( + demand_rate=0.5, + test_cost=200.0, + repair_cost=1500.0, + consequence_cost=50_000.0, + ) + tested = failure_finding_window(trip, [0.5, 1.0, 2.0], 3.0, **prices) + assert isinstance(tested, FailureFindingWindow) + np.testing.assert_allclose( + tested.found_at_tests, [0.04320, 0.04320, 0.07520], atol=5e-6 + ) + assert tested.failures_found == pytest.approx(0.16159, abs=5e-6) + assert tested.failed_time == pytest.approx(0.10535, abs=5e-6) + assert tested.mean_unavailability == pytest.approx(0.03512, abs=5e-6) + assert tested.demands_on_failed == pytest.approx(0.05267, abs=5e-6) + assert tested.tests_cost == 600.0 + assert tested.repairs_cost == pytest.approx(321.40, abs=0.01) + assert tested.consequence_cost == pytest.approx(2633.75, abs=0.01) + assert tested.cost == pytest.approx(3555.15, abs=0.01) + assert tested.present_value == tested.cost + never = failure_finding_window( + trip, [], 3.0, **{**prices, "test_cost": 0.0} + ) + assert never.failed_time == pytest.approx(0.26814, abs=5e-6) + assert never.cost == pytest.approx(6904.57, abs=0.01) + assert never.failures_found == 0.0 and never.tests_cost == 0.0 + json.dumps(tested.to_dict()) + assert "FailureFindingWindow(3 tests over 3" in repr(tested) + + +@pytest.mark.parametrize("reveal", [True, False]) +@pytest.mark.parametrize("discount", [0.0, 0.08]) +def test_exponential_closed_form(reveal, discount): + rate, demand = 0.3, 0.7 + tests = [0.4, 1.0, 1.1, 2.5, 4.0] + window = 4.0 + found = failure_finding_window( + exponential(rate), + tests, + window, + demand_rate=demand, + test_cost=10.0, + repair_cost=40.0, + consequence_cost=900.0, + discount_rate=discount, + demands_reveal=reveal, + ) + q, failed, discounted = closed_form( + rate, tests, window, demand if reveal else 0.0, discount + ) + np.testing.assert_allclose(found.found_at_tests, q, rtol=1e-9) + assert found.failed_time == pytest.approx(failed, rel=1e-9) + assert found.demands_on_failed == pytest.approx(demand * failed, rel=1e-9) + each = 900.0 + (40.0 if reveal else 0.0) + cost = 10.0 * 5 + 40.0 * q.sum() + each * demand * failed + factors = np.exp(-discount * np.array(tests)) + present = ( + 10.0 * factors.sum() + 40.0 * factors @ q + each * demand * discounted + ) + assert abs(found.cost - cost) <= found.precision + assert abs(found.present_value - present) <= found.precision + assert found.precision <= 2e-6 * cost + assert found.present_value == pytest.approx(present, rel=1e-9) + if discount == 0.0: + assert found.present_value == found.cost + # The curve: just before a test at its time, 0 just after. + at = np.array([0.0, 0.2, 0.4, 0.7, 4.0]) + k = rate + (demand if reveal else 0.0) + since = np.array([0.0, 0.2, 0.4, 0.3, 1.5]) + curve = failure_finding_window( + exponential(rate), + tests, + window, + demand_rate=demand, + times=at, + demands_reveal=reveal, + ) + np.testing.assert_allclose( + curve.unavailability, rate / k * -np.expm1(-k * since), atol=2e-4 + ) + + +def test_even_tests_reproduce_the_long_run(): + """Even tests with no discount, only tests finding a failure: a + constant rate has ``failure_finding``'s numbers on any whole number + of intervals, and a Weibull life tends to them over a long window.""" + prices = dict( + test_cost=5.0, + repair_cost=30.0, + demand_rate=0.2, + consequence_cost=700.0, + ) + valve = exponential(0.05) + long_run = failure_finding(valve, 2.0, **prices) + window = failure_finding_window( + valve, + np.arange(1, 26) * 2.0, + 50.0, + demands_reveal=False, + **prices, + ) + assert window.mean_unavailability == pytest.approx( + long_run.mean_unavailability, rel=1e-9 + ) + assert window.cost / 50.0 == pytest.approx(long_run.cost_rate, rel=1e-9) + assert window.failures_found / 50.0 == pytest.approx( + long_run.failures_found_rate, rel=1e-9 + ) + # A Weibull life (mean 8.86) from new, over 400 mean lives: the start + # is worth about a cycle in 400, so within 1% of the long run. + wearing = NonRepairable(surv.Weibull.from_params([10.0, 2.0])) + long_run = failure_finding(wearing, 2.5, **prices) + span = 3500.0 + window = failure_finding_window( + wearing, + np.arange(1, 1401) * 2.5, + span, + demands_reveal=False, + **prices, + ) + assert window.mean_unavailability == pytest.approx( + long_run.mean_unavailability, rel=0.01 + ) + assert window.cost / span == pytest.approx(long_run.cost_rate, rel=0.01) + assert window.failures_found / span == pytest.approx( + long_run.failures_found_rate, rel=0.01 + ) + + +def _simulated(tests, window, age, demand, reveal, discount, rng, runs): + """The plan itself, one device at a time: a Weibull(10, 2.2) life from + ``age``; a failure stays until the next test or, where demands + reveal, the next demand (an exponential wait: demands are a Poisson + process), and is then repaired as new. Each run's tests that found a + failure, demands that met the device failed, and both discounted.""" + scale, shape = 10.0, 2.2 + found = np.zeros(runs) + met = np.zeros(runs) + found_pv = np.zeros(runs) + met_pv = np.zeros(runs) + tests = np.asarray(tests, float) + for run in range(runs): + t, unit_age = 0.0, age + while True: + hazard = (unit_age / scale) ** shape + rng.exponential() + fails = t + scale * hazard ** (1.0 / shape) - unit_age + if fails >= window: + break + later = tests[tests >= fails] + test = later[0] if later.size else math.inf + if reveal: + shown = fails + rng.exponential(1.0 / demand) + if min(shown, test) > window: + break + if shown < test: + met[run] += 1 + met_pv[run] += math.exp(-discount * shown) + t = shown + else: + found[run] += 1 + found_pv[run] += math.exp(-discount * test) + t = test + else: + end = min(test, window) + # Undiscounted only: the demands in the failed time. + met[run] += rng.poisson(demand * (end - fails)) + if test > window: + break + found[run] += 1 + found_pv[run] += math.exp(-discount * test) + t = test + unit_age = 0.0 + return found, met, found_pv, met_pv + + +@pytest.mark.parametrize("tests", [(3.0, 5.0, 6.0, 9.0, 11.0), ()]) +@pytest.mark.parametrize("reveal", [True, False]) +def test_weibull_against_a_simulation(tests, reveal): + """A wearing device, 4 old, tested at uneven times (and never): + within four standard errors of a seeded simulation of the plan.""" + device = NonRepairable(surv.Weibull.from_params([10.0, 2.2])) + window, age, demand = 12.0, 4.0, 0.6 + discount = 0.05 if reveal else 0.0 + worked = failure_finding_window( + device, + tests, + window, + age=age, + test_cost=0.0, + repair_cost=1.0, + demand_rate=demand, + consequence_cost=1.0, + discount_rate=discount, + demands_reveal=reveal, + ) + rng = np.random.default_rng(20261120) + runs = 40_000 + found, met, found_pv, met_pv = _simulated( + tests, window, age, demand, reveal, discount, rng, runs + ) + repairs = found_pv + (met_pv if reveal else 0.0) + for value, draws in ( + (worked.failures_found, found), + (worked.demands_on_failed, met), + ) + ( + ((worked.present_value, repairs + met_pv),) + if reveal + else ((worked.cost, found + met),) + ): + se = draws.std(ddof=1) / math.sqrt(runs) + assert abs(draws.mean() - value) < 4.0 * se + worked.precision + + +def test_never_tested_without_reveal_is_the_life_itself(): + device = NonRepairable(surv.Weibull.from_params([10.0, 0.8])) + at = np.linspace(0.0, 15.0, 7) + found = failure_finding_window( + device, [], 15.0, age=2.0, demands_reveal=False, times=at + ) + life = device.reliability + np.testing.assert_allclose( + found.unavailability, + 1.0 - life.sf(2.0 + at) / life.sf(2.0), + atol=1e-12, + ) + assert found.demands_on_failed is None and found.cost == 0.0 + + +def test_a_test_at_the_start_finds_nothing(): + """The device is working at the start, so a test then only costs.""" + device = NonRepairable(surv.Weibull.from_params([10.0, 1.5])) + prices = dict(test_cost=7.0, demand_rate=0.3, consequence_cost=50.0) + with_first = failure_finding_window(device, [0.0, 4.0], 9.0, **prices) + without = failure_finding_window(device, [4.0], 9.0, **prices) + assert with_first.found_at_tests[0] == 0.0 + assert with_first.found_at_tests[1] == without.found_at_tests[0] + assert with_first.cost == pytest.approx(without.cost + 7.0, rel=1e-12) + + +def test_the_unit_of_time_does_not_matter(): + """Times a thousand, rates a thousandth: the same chances and costs.""" + prices = dict(test_cost=3.0, repair_cost=20.0, consequence_cost=400.0) + tests = np.array([2.0, 5.0, 6.0]) + one = failure_finding_window( + NonRepairable(surv.Weibull.from_params([10.0, 1.7])), + tests, + 9.0, + age=1.0, + demand_rate=0.4, + discount_rate=0.06, + **prices, + ) + other = failure_finding_window( + NonRepairable(surv.Weibull.from_params([10.0e3, 1.7])), + tests * 1e3, + 9.0e3, + age=1.0e3, + demand_rate=0.4e-3, + discount_rate=0.06e-3, + **prices, + ) + np.testing.assert_allclose( + other.found_at_tests, one.found_at_tests, rtol=1e-9 + ) + assert other.present_value == pytest.approx(one.present_value, rel=1e-9) + assert other.mean_unavailability == pytest.approx( + one.mean_unavailability, rel=1e-9 + ) + + +def test_refusals(): + valve = exponential(0.1) + with pytest.raises(ValueError, match="increasing"): + failure_finding_window(valve, [2.0, 1.0], 3.0) + with pytest.raises(ValueError, match="leave out the tests after it"): + failure_finding_window(valve, [1.0, 4.0], 3.0) + with pytest.raises(ValueError, match="window must be a number"): + failure_finding_window(valve, [1.0], 0.0) + with pytest.raises(ValueError, match="needs the demand_rate"): + failure_finding_window(valve, [1.0], 3.0, consequence_cost=5.0) + with pytest.raises(ValueError, match="demands_reveal"): + failure_finding_window(valve, [1.0], 3.0, demands_reveal="yes") + with pytest.raises(ValueError, match="tolerance"): + failure_finding_window(valve, [1.0], 3.0, tolerance=0.0) + with pytest.raises(ValueError, match="times must be from 0"): + failure_finding_window(valve, [1.0], 3.0, times=[4.0]) + with pytest.raises(NotImplementedError, match="use failure_finding"): + failure_finding_window(valve, np.arange(1, 2002) * 1e-3, 3.0) + bounded = NonRepairable(surv.Uniform.from_params([0.0, 5.0])) + with pytest.raises(ValueError, match="age of a working device"): + failure_finding_window(bounded, [1.0], 3.0, age=6.0) diff --git a/repyability/tests/test_first_build.py b/repyability/tests/test_first_build.py new file mode 100644 index 00000000..ce909ee9 --- /dev/null +++ b/repyability/tests/test_first_build.py @@ -0,0 +1,40 @@ +"""A session's first diagram does not import surpyval's joint or +degradation models to check whether its nodes are one: no model can be +one before its module is imported, and importing them (with surpyval's +regression code and pandas) took about 2 s of the first build.""" + +import subprocess +import sys +import textwrap + + +def test_a_first_diagram_imports_no_joint_or_degradation_models(): + code = textwrap.dedent(""" + import sys + import surpyval as surv + import repyability as r + + w = surv.Weibull.from_params([7500, 2.0]) + e = surv.Exponential.from_params([1e-4]) + edges = [("input", "p1"), ("input", "p2"), ("p1", "v"), + ("p2", "v"), ("v", "output")] + rbd = r.NonRepairableRBD(edges, {"p1": w, "p2": w, "v": e}) + rbd.sf(1000.0) + rbd.mean() + r.RepairableRBD( + edges, + {n: {"reliability": w, "repairability": e} for n in ("p1", "p2")} + | {"v": {"reliability": e, "repairability": e}}, + ).mean_availability() + loaded = [m for m in ("surpyval.degradation", + "surpyval.univariate.joint") if m in sys.modules] + print(loaded) + """) + out = subprocess.run( + [sys.executable, "-c", code], + capture_output=True, + text=True, + check=True, + env=None, + ) + assert out.stdout.strip().splitlines()[-1] == "[]", out.stderr diff --git a/repyability/tests/test_fitted_processes.py b/repyability/tests/test_fitted_processes.py index feed5171..5d924447 100644 --- a/repyability/tests/test_fitted_processes.py +++ b/repyability/tests/test_fitted_processes.py @@ -86,8 +86,8 @@ def failures_by(process, horizon, n=N_RUNS, seed=1, **more): @pytest.mark.parametrize( "process", [ - surv.ARA.fit_from_parameters([100.0, 2.5], 0.0), - surv.ARI.fit_from_parameters([100.0, 2.5], 0.0), + surv.ARA.from_params([100.0, 2.5], 0.0), + surv.ARI.from_params([100.0, 2.5], 0.0), ], ids=["ARA", "ARI"], ) @@ -102,7 +102,7 @@ def test_no_reduction_is_minimal_repair(process): def test_g1_with_no_stretch_is_a_renewal_process(): # G1 with q = 0 draws every gap from the life itself: a renewal # process, and with an exponential life a Poisson one, lambda * T. - process = surv.GeneralizedOneRenewal.fit_from_parameters( + process = surv.GeneralizedOneRenewal.from_params( [0.05], 0.0, dist=surv.Exponential ) assert failures_by(process, 200.0) == pytest.approx(10.0, abs=0.2) @@ -111,10 +111,10 @@ def test_g1_with_no_stretch_is_a_renewal_process(): @pytest.mark.parametrize( "process", [ - surv.GeneralizedOneRenewal.fit_from_parameters([100.0, 2.0], 0.3), - surv.ARA.fit_from_parameters([100.0, 2.5], 0.6), - surv.ARA.fit_from_parameters([100.0, 2.5], 0.4, m=2), - surv.ARI.fit_from_parameters([100.0, 2.5], 0.5), + surv.GeneralizedOneRenewal.from_params([100.0, 2.0], 0.3), + surv.ARA.from_params([100.0, 2.5], 0.6), + surv.ARA.from_params([100.0, 2.5], 0.4, m=2), + surv.ARI.from_params([100.0, 2.5], 0.5), ], ids=["G1", "ARA1", "ARA2", "ARI1"], ) @@ -153,7 +153,7 @@ def test_a_stepped_unit_leaves_other_units_draws_as_they_were(): { "a": plain, "b": { - "reliability": surv.ARA.fit_from_parameters([100.0, 2.5], 0.5), + "reliability": surv.ARA.from_params([100.0, 2.5], 0.5), "repairability": "instant", }, }, @@ -168,7 +168,7 @@ def test_a_stepped_unit_leaves_other_units_draws_as_they_were(): def test_a_stepped_unit_is_saved_as_its_fitted_model(): - process = surv.ARA.fit_from_parameters([100.0, 2.5], 0.6) + process = surv.ARA.from_params([100.0, 2.5], 0.6) rbd = one(process) saved = rbd.to_dict() back = RepairableRBD.from_dict(saved) @@ -185,7 +185,7 @@ def test_a_stepped_unit_is_saved_as_its_fitted_model(): def test_a_stepped_unit_starts_from_its_age(): # Run 80 since new without a failure: under ARA its next failure is # the life's from age 80, as for any unit; then the fitted repairs. - process = surv.ARA.fit_from_parameters([100.0, 2.5], 0.0) + process = surv.ARA.from_params([100.0, 2.5], 0.0) run = one(process).availability( t_simulation=100.0, mc_samples=N_RUNS, @@ -198,7 +198,7 @@ def test_a_stepped_unit_starts_from_its_age(): def test_what_a_stepped_unit_refuses(): - process = surv.ARA.fit_from_parameters([100.0, 2.5], 0.5) + process = surv.ARA.from_params([100.0, 2.5], 0.5) with pytest.raises(NotImplementedError, match="not a Kijima virtual age"): one(process).availability( t_simulation=10.0, diff --git a/repyability/tests/test_imperfect_repair.py b/repyability/tests/test_imperfect_repair.py index 32d9ac2d..e5ccc502 100644 --- a/repyability/tests/test_imperfect_repair.py +++ b/repyability/tests/test_imperfect_repair.py @@ -24,7 +24,7 @@ def _gr(q, alpha=100.0, beta=2.0, kijima="ii"): """A generalized-renewal model, Weibull baseline, restoration factor q.""" - return GeneralizedRenewal.fit_from_parameters( + return GeneralizedRenewal.from_params( [alpha, beta], q, kijima=kijima, dist=surv.Weibull ) @@ -324,7 +324,7 @@ def count_terminated_simulation( self, events, items=1000, random_state=None ): self.seen.append(("count", random_state)) - return GeneralizedRenewal.fit_from_parameters( + return GeneralizedRenewal.from_params( [100.0, 2.0], 0.5, kijima="ii", dist=surv.Weibull ).count_terminated_simulation(events, items=items) diff --git a/repyability/tests/test_inspection.py b/repyability/tests/test_inspection.py index 70dab9a4..a75970a6 100644 --- a/repyability/tests/test_inspection.py +++ b/repyability/tests/test_inspection.py @@ -74,6 +74,8 @@ def test_a_hidden_failure_is_down_until_the_next_inspection(): "system_downtime": 0.0, "setup": 0.0, "shutdown": 0.0, + "crews": 0.0, + "capital": 0.0, } @@ -483,7 +485,7 @@ def test_the_simulation_matches_the_exact_values(): ({"interval": -5}, "positive, finite"), ({"interval": float("inf")}, "positive, finite"), ({"interval": "yearly"}, "positive, finite"), - ({"interval": 50, "duration": 3.0}, "time-to-test model"), + ({"interval": 50, "duration": -3.0}, "time-to-test model"), ({"interval": 50, "cost": -1.0}, "non-negative"), ], ) diff --git a/repyability/tests/test_joint_importance.py b/repyability/tests/test_joint_importance.py index 1739a239..46116287 100644 --- a/repyability/tests/test_joint_importance.py +++ b/repyability/tests/test_joint_importance.py @@ -343,16 +343,22 @@ def test_a_repairable_diagram_with_groups(): assert held[("a", "c")] == 0.0 and held[("a", "b")] == pytest.approx(-1.0) with pytest.raises(NotImplementedError, match="common-cause group"): shared.joint_importance(broken_nodes=["a"]) - # With limited repair crews too, the groups refuse as the other - # measures do. + # With limited repair crews too, their chain takes the group in + # (#251): each pair's is Birnbaum's measure of one with the other + # held either way, a member held being struck no more. crews = RepairableRBD( PAIR_THEN_C, units, ccf_groups=[CCFGroup(["a", "b"], BetaFactor(0.1))], repair_crews=1, ) - with pytest.raises(NotImplementedError, match="repair crews"): - crews.joint_importance() + pairs = crews.joint_importance() + assert pairs[("a", "c")] == pytest.approx( + crews.birnbaum_importance(working_nodes=["c"])["a"] + - crews.birnbaum_importance(broken_nodes=["c"])["a"], + rel=1e-12, + ) + assert pairs[("a", "b")] < 0 < pairs[("a", "c")] def test_a_fault_tree_s_is_its_diagram_s(): diff --git a/repyability/tests/test_kept_at_given_times.py b/repyability/tests/test_kept_at_given_times.py new file mode 100644 index 00000000..a69faf26 --- /dev/null +++ b/repyability/tests/test_kept_at_given_times.py @@ -0,0 +1,155 @@ +"""A block inspected at a shutdown's given times and kept unless it is due +(``"older_than"``, or on condition with a threshold), valued stretch by +stretch over a horizon (``_condition_replacement. +condition_plan_availability``): against the same block at a shutdown on a +period when the times are equally spaced, against renewing it at every +outage (a threshold of 0) and against no task (an age past the horizon), +and against the simulation, from new and from a state.""" + +import numpy as np +import pytest +import surpyval as surv + +from repyability import NodeState, RepairableRBD +from repyability.rbd import routes + +E = surv.Exponential.from_params +W = surv.Weibull.from_params +LIFE = W([200.0, 2.0]) +TIMES = [30.0, 90.0, 210.0, 240.0] +Z = 4.0 + + +def unit(preventive=None, calendar=None, duration=10.0): + """A wearing unit, repaired at rate 0.5, held by shutdown "line".""" + spec = { + "reliability": LIFE, + "repairability": E([0.5]), + "repair_cost": 4.0, + } + if preventive is not None: + spec["preventive"] = {"shutdown": "line", "cost": 3.0, **preventive} + shut = {"duration": duration, **(calendar or {"times": TIMES})} + return RepairableRBD( + [("s", "a"), ("a", "t")], {"a": spec}, shutdowns={"line": shut} + ) + + +def plain(**more): + return dict(control_variate=False, conditional=False, **more) + + +def test_equally_spaced_times_are_the_shutdown_on_that_period(): + T = 300.0 + given = unit({"older_than": 100.0}, {"times": [20.0, 120.0, 220.0]}) + period = unit({"older_than": 100.0}, {"period": 100.0, "offset": 20.0}) + t = np.linspace(0.0, T, 61) + np.testing.assert_allclose( + given.point_availability(t), period.point_availability(t), atol=1e-7 + ) + assert given.expected_cost(T).mean == pytest.approx( + period.expected_cost(T).mean, rel=1e-7 + ) + a, b = given.expected_events(T), period.expected_events(T) + assert a.node_preventive["a"] == pytest.approx( + b.node_preventive["a"], rel=1e-7 + ) + + +def test_a_threshold_of_0_renews_at_every_outage(): + T = 300.0 + kept = unit({"policy": "condition", "threshold": 0.0}) + renewed = unit({}) + t = np.linspace(0.0, T, 61) + np.testing.assert_allclose( + kept.point_availability(t), renewed.point_availability(t), atol=1e-7 + ) + assert kept.expected_events(T).node_failures["a"] == pytest.approx( + renewed.expected_events(T).node_failures["a"], rel=1e-7 + ) + + +def test_an_age_past_the_horizon_renews_nothing(monkeypatch): + """An age the unit never reaches: the same as no task, to the + recursion's own discretisation error, which is first order in the + grid step and is bounded from it. + + Each stretch is worked out on a grid of ``N`` steps (here every + stretch is short beside the life's spread, so ``N`` is + ``_block_replacement._MIN_STEPS``, 2,000, and the step ``h`` of each + stretch is its length over ``N``). The kept side follows the units it + keeps through the condition recursion, which carries their failures + and the starts after them in cells of one step, a first-order rule; + so the two sides differ by ``C / N + O(1 / N**2)``. + + The order and the constant were measured before this bound was set, + as the largest difference over the times checked: 2.17e-7 at + ``N`` = 2,000, 1.09e-7 at 4,000 and 5.5e-8 at 8,000. It halves each + time ``N`` doubles (ratios 1.99 and 1.98), so it is first order, and + ``N`` times it, the constant ``C``, is 4.35e-4, 4.36e-4 and 4.41e-4. + (The same holds on a period: an age past the horizon against no task + with a shut every 120 differs by 2.7e-7, 1.4e-7 and 7.0e-8 at the + same ``N``.) The bound is ``C / N`` with ``C`` rounded up to its next + power of ten, 1e-3: 5e-7 at ``N`` = 2,000. + + The test checks the order too, from the values at ``N`` and ``2 N``: + the difference shrinks by a factor between sqrt(2) and 2 sqrt(2) (an + order between 1/2 and 3/2), so it is the grid's error, which vanishes + as the grid is refined, not a fixed one.""" + from repyability.rbd import _block_replacement + + T, C = 300.0, 1e-3 + t = np.linspace(0.0, T, 61) + + def difference(): + kept = unit({"older_than": 1e6}).point_availability(t) + return float(np.max(np.abs(kept - unit().point_availability(t)))) + + N = _block_replacement._MIN_STEPS + coarse = difference() + assert coarse <= C / N + assert unit({"older_than": 1e6}).expected_events(T).node_preventive[ + "a" + ] == pytest.approx(0.0, abs=1e-9) + monkeypatch.setattr(_block_replacement, "_MIN_STEPS", 2 * N) + fine = difference() + assert np.sqrt(2.0) * fine <= coarse <= 2.0 * np.sqrt(2.0) * fine + + +@pytest.mark.parametrize( + "preventive", + [{"older_than": 70.0}, {"policy": "condition", "threshold": 0.2}], +) +@pytest.mark.parametrize( + "state", [None, {"a": NodeState(age=120.0)}, {"a": NodeState(alive=False)}] +) +def test_the_simulation_agrees(preventive, state): + T, rbd = 300.0, unit(preventive) + route = rbd.analysis_routes()["mission_availability"].route + assert route in (routes.EXACT, routes.NUMERICAL) + run = rbd.availability( + T, mc_samples=20_000, seed=3, state=state, **plain() + ) + interval = run.mean_availability_interval() + exact = rbd.mission_availability(T, state=state) + assert abs(interval.estimate - exact) <= Z * interval.standard_error + cost = rbd.expected_cost(T, state=state).mean + assert abs(run.cost.sample_mean - cost) <= Z * run.cost.sample_se + + +def test_a_test_at_given_times_is_still_simulated(): + rbd = unit() + tested = RepairableRBD( + rbd._init_args["edges"], + { + "a": { + **rbd._init_args["components"]["a"], + "inspection": {"shutdown": "line"}, + } + }, + shutdowns=rbd._init_args["shutdowns"], + ) + assert tested.analysis_routes()["expected_npv"].route == routes.REFUSED + assert unit({"older_than": 70.0}).analysis_routes()[ + "expected_npv" + ].route in (routes.EXACT, routes.NUMERICAL) diff --git a/repyability/tests/test_maintenance_calendar.py b/repyability/tests/test_maintenance_calendar.py index 1c4116a0..f6cf2860 100644 --- a/repyability/tests/test_maintenance_calendar.py +++ b/repyability/tests/test_maintenance_calendar.py @@ -15,6 +15,13 @@ from repyability.maintenance import _replacement from repyability.maintenance._calendar import _Grid +# The 0.14 and 0.19 forms (Calendar, Shutdown, Shutdowns, prices on the +# opportunities, optimal_calendar_policy) still work, deprecated: these +# tests keep them unchanged, and test_opportunities.py the new forms. +pytestmark = pytest.mark.filterwarnings( + "ignore:.*(is deprecated|puts a price on the opportunities):FutureWarning" +) + def solve(part, calendar, **options): """The calendar policy, on a grid of a given step where a check needs @@ -210,6 +217,8 @@ def shut_every_180(offset): def test_an_offset_off_the_grid_keeps_the_period(): with warnings.catch_warnings(): warnings.simplefilter("error") + # The 0.14 and 0.19 forms warn that they are deprecated. + warnings.simplefilter("ignore", FutureWarning) aligned = SHUT.optimal_calendar_policy(shut_every_180(0.0)) with pytest.warns(UserWarning, match="nearest"): moved = SHUT.optimal_calendar_policy(shut_every_180(0.1234)) @@ -242,6 +251,8 @@ def test_an_offset_of_whole_steps_shifts_the_policy(): offset = 10 * aligned.step with warnings.catch_warnings(): warnings.simplefilter("error") + # The 0.14 and 0.19 forms warn that they are deprecated. + warnings.simplefilter("ignore", FutureWarning) shifted = SHUT.optimal_calendar_policy(shut_every_180(offset)) assert shifted.step == aligned.step and shifted.period == 180.0 assert shifted.cost_rate == pytest.approx(aligned.cost_rate, rel=1e-9) diff --git a/repyability/tests/test_maintenance_calendar_methods.py b/repyability/tests/test_maintenance_calendar_methods.py index 9d23da27..31e3c846 100644 --- a/repyability/tests/test_maintenance_calendar_methods.py +++ b/repyability/tests/test_maintenance_calendar_methods.py @@ -13,6 +13,13 @@ from repyability import Calendar, NonRepairable, Opportunity from repyability.maintenance import _replacement +# The 0.14 and 0.19 forms (Calendar, Shutdown, Shutdowns, prices on the +# opportunities, optimal_calendar_policy) still work, deprecated: these +# tests keep them unchanged, and test_opportunities.py the new forms. +pytestmark = pytest.mark.filterwarnings( + "ignore:.*(is deprecated|puts a price on the opportunities):FutureWarning" +) + def solve(part, calendar, **options): """The calendar policy, on a grid of a given step where a check needs @@ -207,12 +214,15 @@ def test_the_sampled_policy_is_deterministic(): def test_auto_chooses_the_method(nested_exact): assert nested_exact.method == "dp" and nested_exact.basis == "exact" - # Falling to sampling is said: the cycle is too long, and mc_samples - # sets the cost. - with pytest.warns(UserWarning, match="mc_samples") as record: + # Falling to sampling is said, as a deprecation (0.21 refuses it): + # the cycle is too long, mc_samples sets the cost, and the ready + # horizon and method='sampling' are named. + with pytest.warns(FutureWarning, match="mc_samples") as record: sampled = solve(BEARING, COPRIME, step=1.0, mc_samples=2, seed=0) assert sampled.method == "sampling" - assert f"more than {_replacement.MAX_CYCLE:,}" in str(record[0].message) + message = str(record[0].message) + assert f"more than {_replacement.MAX_CYCLE:,}" in message + assert "horizon=" in message and "method='sampling'" in message with warnings.catch_warnings(): warnings.simplefilter("error") asked = solve( diff --git a/repyability/tests/test_maintenance_calendar_rbd.py b/repyability/tests/test_maintenance_calendar_rbd.py index 6db77747..e86c8885 100644 --- a/repyability/tests/test_maintenance_calendar_rbd.py +++ b/repyability/tests/test_maintenance_calendar_rbd.py @@ -20,6 +20,13 @@ ) from repyability.maintenance import _replacement +# The 0.14 and 0.19 forms (Calendar, Shutdown, Shutdowns, prices on the +# opportunities, optimal_calendar_policy) still work, deprecated: these +# tests keep them unchanged, and test_opportunities.py the new forms. +pytestmark = pytest.mark.filterwarnings( + "ignore:.*(is deprecated|puts a price on the opportunities):FutureWarning" +) + def solve(part, calendar, **options): """The calendar policy, on a grid of a given step where a check needs @@ -330,6 +337,8 @@ def test_a_calendar_replacement_is_a_stop_of_its_group(shuts): "system_downtime": 0.0, "setup": 2 * 500.0, "shutdown": 0.0, + "crews": 0.0, + "capital": 0.0, } diff --git a/repyability/tests/test_maintenance_calendar_spread.py b/repyability/tests/test_maintenance_calendar_spread.py index 0515e057..4821f0e3 100644 --- a/repyability/tests/test_maintenance_calendar_spread.py +++ b/repyability/tests/test_maintenance_calendar_spread.py @@ -20,6 +20,13 @@ ) from repyability.maintenance import _replacement +# The 0.14 and 0.19 forms (Calendar, Shutdown, Shutdowns, prices on the +# opportunities, optimal_calendar_policy) still work, deprecated: these +# tests keep them unchanged, and test_opportunities.py the new forms. +pytestmark = pytest.mark.filterwarnings( + "ignore:.*(is deprecated|puts a price on the opportunities):FutureWarning" +) + LIFE = surv.Weibull.from_params([365.0, 2.0]) # UC-7's plant: a shut every 180 days (the next in 21) at $100, no # planned replacement between shuts, $400 at a failure. diff --git a/repyability/tests/test_maintenance_next.py b/repyability/tests/test_maintenance_next.py index b21ff747..5e722fa9 100644 --- a/repyability/tests/test_maintenance_next.py +++ b/repyability/tests/test_maintenance_next.py @@ -17,6 +17,13 @@ Opportunity, ) +# The 0.14 and 0.19 forms (Calendar, Shutdown, Shutdowns, prices on the +# opportunities, optimal_calendar_policy) still work, deprecated: these +# tests keep them unchanged, and test_opportunities.py the new forms. +pytestmark = pytest.mark.filterwarnings( + "ignore:.*(is deprecated|puts a price on the opportunities):FutureWarning" +) + LIFE = surv.Weibull.from_params([365.0, 2.0]) BEARING = NonRepairable(LIFE, planned_cost=150.0, unplanned_cost=400.0) OUTAGES = [(150.0, 100.0), (330.0, 100.0)] diff --git a/repyability/tests/test_maintenance_options.py b/repyability/tests/test_maintenance_options.py index 1413b277..d436fdc4 100644 --- a/repyability/tests/test_maintenance_options.py +++ b/repyability/tests/test_maintenance_options.py @@ -16,6 +16,13 @@ from repyability import NonRepairable, Opportunity +# The 0.14 and 0.19 forms (Calendar, Shutdown, Shutdowns, prices on the +# opportunities, optimal_calendar_policy) still work, deprecated: these +# tests keep them unchanged, and test_opportunities.py the new forms. +pytestmark = pytest.mark.filterwarnings( + "ignore:.*(is deprecated|puts a price on the opportunities):FutureWarning" +) + SCALE, SHAPE = 365.0, 2.0 CP, CU = 150.0, 400.0 DAY = math.log(1.08) / 365.25 diff --git a/repyability/tests/test_maintenance_shutdowns.py b/repyability/tests/test_maintenance_shutdowns.py index 498924b6..28ec6ad3 100644 --- a/repyability/tests/test_maintenance_shutdowns.py +++ b/repyability/tests/test_maintenance_shutdowns.py @@ -23,6 +23,13 @@ from repyability.maintenance._site_policy import _Averaged from repyability.schedule import DutyPlan, Rate, Recurrence, Shifts, Usage +# The 0.14 and 0.19 forms (Calendar, Shutdown, Shutdowns, prices on the +# opportunities, optimal_calendar_policy) still work, deprecated: these +# tests keep them unchanged, and test_opportunities.py the new forms. +pytestmark = pytest.mark.filterwarnings( + "ignore:.*(is deprecated|puts a price on the opportunities):FutureWarning" +) + LIFE = surv.Weibull.from_params([1000.0, 2.5]) NOW = "2026-11-16" @@ -585,7 +592,7 @@ def test_results_go_through_json(): ({"method": "exact"}, "no repeating cycle to be exact over"), ({"method": "sampling"}, "no repeating cycle to sample"), ({"horizon": "2036-11-16"}, "needs discount= too"), - ({"discount": 0.07}, "goes with horizon="), + ({"discount": 0.07}, "discounted long run needs shuts that repeat"), ( {"horizon": "2036-11-16", "discount": 0.07, "method": "averaged"}, "its own route", @@ -692,6 +699,8 @@ def test_the_model_time_calendar_is_unchanged(): part = textbook() with warnings.catch_warnings(): warnings.simplefilter("error") + # The 0.14 and 0.19 forms warn that they are deprecated. + warnings.simplefilter("ignore", FutureWarning) policy = part.optimal_calendar_policy(Calendar()) assert policy.cost_rate == pytest.approx(0.003462, abs=5e-7) with pytest.raises(ValueError, match="for a site"): diff --git a/repyability/tests/test_maintenance_shutdowns_dated.py b/repyability/tests/test_maintenance_shutdowns_dated.py index ec49cd46..de5433c9 100644 --- a/repyability/tests/test_maintenance_shutdowns_dated.py +++ b/repyability/tests/test_maintenance_shutdowns_dated.py @@ -20,6 +20,13 @@ ) from repyability.schedule import DutyPlan, Recurrence, Shifts +# The 0.14 and 0.19 forms (Calendar, Shutdown, Shutdowns, prices on the +# opportunities, optimal_calendar_policy) still work, deprecated: these +# tests keep them unchanged, and test_opportunities.py the new forms. +pytestmark = pytest.mark.filterwarnings( + "ignore:.*(is deprecated|puts a price on the opportunities):FutureWarning" +) + LIFE = surv.Weibull.from_params([1000.0, 2.5]) NOW = "2026-11-16" TURNAROUNDS = ["2027-03-03", "2028-09-09"] diff --git a/repyability/tests/test_npv_allocation.py b/repyability/tests/test_npv_allocation.py new file mode 100644 index 00000000..56e5595b --- /dev/null +++ b/repyability/tests/test_npv_allocation.py @@ -0,0 +1,253 @@ +"""``allocate_redundancy`` by net present value or equivalent annual cost +(``objective=``, ``value_rate=``): the total cost's design with no value, +every design of a small diagram drawn out and valued, and a design that +changes with the discount rate.""" + +import itertools +import json +import math + +import numpy as np +import pytest +import surpyval as surv + +from repyability import RepairableRBD + +HORIZON = 87600.0 +PARTS = { + "a": dict(life=1e-3, repair=0.1, fix=500.0, buy=20000.0), + "b": dict(life=4e-4, repair=0.05, fix=900.0, buy=35000.0), + "c": dict(life=2e-3, repair=0.5, fix=100.0, buy=6000.0), +} +DOWNTIME = 40.0 + + +def part(name): + p = PARTS[name] + return { + "reliability": surv.Exponential.from_params([p["life"]]), + "repairability": surv.Exponential.from_params([p["repair"]]), + "repair_cost": p["fix"], + "acquisition_cost": p["buy"], + } + + +def drawn(units): + """The line with each part's copies drawn in parallel: every copy of + one part feeds every copy of the next.""" + stages = [ + [(name, i) for i in range(units[name])] for name in ("a", "b", "c") + ] + edges = [("s", node) for node in stages[0]] + for before, after in zip(stages, stages[1:]): + edges += list(itertools.product(before, after)) + edges += [(node, "t") for node in stages[-1]] + return RepairableRBD( + edges, + {node: part(node[0]) for stage in stages for node in stage}, + downtime_cost_rate=DOWNTIME, + ) + + +def line(): + return RepairableRBD( + [("s", "a"), ("a", "b"), ("b", "c"), ("c", "t")], + {name: part(name) for name in PARTS}, + downtime_cost_rate=DOWNTIME, + ) + + +def present(rate, horizon=HORIZON): + return -math.expm1(-rate * horizon) / rate if rate else horizon + + +def valued(units, rate, value_rate): + """A design's net present value, from the diagram drawn out: what it + earns at its long-run availability, less its total cost.""" + design = drawn(units) + value = value_rate * present(rate) * design.mean_availability() + return value - design.total_cost(HORIZON, discount_rate=rate) + + +@pytest.mark.parametrize("rate", [0.0, 2e-5]) +@pytest.mark.parametrize("method", ["exact", "greedy"]) +def test_with_no_value_it_is_the_total_costs_design(rate, method): + kwargs = dict(discount_rate=rate, method=method) + by_cost = line().allocate_redundancy(HORIZON, **kwargs) + for objective in ("npv", "eac"): + best = line().allocate_redundancy( + HORIZON, objective=objective, **kwargs + ) + assert best.units == by_cost.units + assert best.total_cost == by_cost.total_cost + assert best.acquisition_cost == by_cost.acquisition_cost + assert best.cost_rate == by_cost.cost_rate + assert best.availability == by_cost.availability + assert best.npv == -by_cost.total_cost and best.value == 0.0 + assert best.eac == pytest.approx( + by_cost.total_cost / present(rate), rel=1e-12 + ) + assert by_cost.objective == "cost" and by_cost.npv is None + + +@pytest.mark.parametrize("rate", [0.0, 1e-5, 1e-4]) +@pytest.mark.parametrize("value_rate", [0.0, 150.0]) +def test_against_every_design_drawn_out(rate, value_rate): + counts = range(1, 5) + values = { + n: valued(dict(zip("abc", n)), rate, value_rate) + for n in itertools.product(counts, repeat=3) + } + best_units = max(values, key=values.get) + assert max(best_units) < 4 # the best is inside what was tried + best = line().allocate_redundancy( + HORIZON, objective="npv", discount_rate=rate, value_rate=value_rate + ) + assert tuple(best.units[name] for name in "abc") == best_units + assert best.npv == pytest.approx(values[best_units], rel=1e-9) + assert best.npv == pytest.approx( + best.value - best.acquisition_cost - best.running_cost, rel=1e-12 + ) + assert best.eac == pytest.approx(-best.npv / present(rate), rel=1e-12) + by_eac = line().allocate_redundancy( + HORIZON, objective="eac", discount_rate=rate, value_rate=value_rate + ) + assert by_eac.units == best.units and by_eac.npv == best.npv + assert "long-run" in best.basis and "expected_npv" in best.basis + + +@pytest.mark.parametrize("seed", range(8)) +def test_the_searchs_bounds_hold_on_random_small_cases(seed): + # The exact search stops at its bounds (a copy that cannot pay for + # itself, the copies a design no worse can afford): with a value and + # a discount rate it must still find the best of every design. + rng = np.random.default_rng(seed) + parts = { + name: { + "reliability": surv.Exponential.from_params( + [float(10 ** rng.uniform(-3.5, -2.5))] + ), + "repairability": surv.Exponential.from_params( + [float(10 ** rng.uniform(-1.5, -0.5))] + ), + "repair_cost": float(rng.uniform(100.0, 2000.0)), + "acquisition_cost": float(rng.uniform(5000.0, 50000.0)), + } + for name in ("a", "b") + } + downtime = float(rng.uniform(0.0, 100.0)) + value_rate = float(rng.uniform(0.0, 400.0)) + rate = float(10 ** rng.uniform(-6.0, -4.0)) + + def design(units): + stages = [[(n, i) for i in range(units[n])] for n in ("a", "b")] + edges = [("s", node) for node in stages[0]] + edges += list(itertools.product(*stages)) + edges += [(node, "t") for node in stages[1]] + return RepairableRBD( + edges, + {node: parts[node[0]] for stage in stages for node in stage}, + downtime_cost_rate=downtime, + ) + + values = {} + for n in itertools.product(range(1, 7), repeat=2): + drawn_out = design(dict(zip("ab", n))) + values[n] = value_rate * present( + rate + ) * drawn_out.mean_availability() - drawn_out.total_cost( + HORIZON, discount_rate=rate + ) + best_units = max(values, key=values.get) + assert max(best_units) < 6 + best = design({"a": 1, "b": 1}).allocate_redundancy( + HORIZON, objective="npv", discount_rate=rate, value_rate=value_rate + ) + found = (best.units[("a", 0)], best.units[("b", 0)]) + assert found == best_units + assert best.npv == pytest.approx(values[best_units], rel=1e-9) + + +def test_the_best_design_changes_with_the_discount_rate(): + # Discounted hard, the downtime a copy saves in later years is worth + # little now, and the copy is bought at the start. + kwargs = dict(objective="npv", value_rate=150.0) + plain = line().allocate_redundancy(HORIZON, **kwargs) + hard = line().allocate_redundancy(HORIZON, discount_rate=1e-4, **kwargs) + assert plain.units != hard.units + assert all(hard.units[n] <= plain.units[n] for n in PARTS) + assert sum(hard.units.values()) < sum(plain.units.values()) + + +def test_a_value_buys_more_copies_than_the_cost_alone(): + by_cost = line().allocate_redundancy(HORIZON) + worth = line().allocate_redundancy( + HORIZON, objective="npv", value_rate=2000.0 + ) + assert sum(worth.units.values()) > sum(by_cost.units.values()) + assert worth.availability > by_cost.availability + assert worth.value == pytest.approx( + 2000.0 * HORIZON * worth.availability, rel=1e-12 + ) + + +def test_the_constraints_are_kept(): + kwargs = dict(objective="npv", discount_rate=1e-5, value_rate=150.0) + free = line().allocate_redundancy(HORIZON, **kwargs) + floor = 1.0 - 0.1 * (1.0 - free.availability) + held = line().allocate_redundancy( + HORIZON, min_availability=floor, **kwargs + ) + assert held.availability >= floor and held.npv < free.npv + capped = line().allocate_redundancy(HORIZON, max_units=1, **kwargs) + assert set(capped.units.values()) == {1} + assert capped.npv <= free.npv + + +def test_for_ever_at_a_discount_rate(): + rate = 1e-5 + best = line().allocate_redundancy( + math.inf, objective="eac", discount_rate=rate, value_rate=150.0 + ) + assert best.eac == pytest.approx(-best.npv * rate, rel=1e-12) + + +def test_the_arguments_are_checked(): + allocate = line().allocate_redundancy + with pytest.raises(ValueError, match="objective must be"): + allocate(HORIZON, objective="profit") + with pytest.raises(ValueError, match="value_rate needs an objective"): + allocate(HORIZON, value_rate=10.0) + with pytest.raises(ValueError, match="value_rate must be"): + allocate(HORIZON, objective="npv", value_rate=-1.0) + + +def test_a_crew_for_every_job_is_the_allocation_without_crews(): + """Crews are allocated (test_crew_allocation.py); with a crew for + every component no job waits, so the NPV search is the one with no + crews at all.""" + edges = [("s", "a"), ("a", "b"), ("b", "t")] + plain = RepairableRBD( + edges, + {"a": part("a"), "b": part("b")}, + downtime_cost_rate=DOWNTIME, + ) + crewed = RepairableRBD( + edges, + {"a": part("a"), "b": part("b")}, + downtime_cost_rate=DOWNTIME, + repair_crews=2, + ) + free = plain.allocate_redundancy(HORIZON, objective="npv", value_rate=5.0) + held = crewed.allocate_redundancy(HORIZON, objective="npv", value_rate=5.0) + assert held.units == free.units + assert held.npv == pytest.approx(free.npv, rel=1e-9) + + +def test_the_result_goes_through_json(): + best = line().allocate_redundancy( + HORIZON, objective="npv", discount_rate=1e-5, value_rate=150.0 + ) + again = json.loads(json.dumps(best.to_dict())) + assert again["objective"] == "npv" and again["npv"] == best.npv + assert again["value_rate"] == 150.0 and again["basis"] == best.basis diff --git a/repyability/tests/test_npv_contracts.py b/repyability/tests/test_npv_contracts.py new file mode 100644 index 00000000..ae4440f7 --- /dev/null +++ b/repyability/tests/test_npv_contracts.py @@ -0,0 +1,223 @@ +"""Contract payoffs in the simulated NPV (``npv_distribution(contract=)``) +and two plans compared on the same random numbers (``compare_npv``): +the payoff by hand, a system that never fails in closed form, identical +plans differing by exactly 0, and the variance the common numbers +remove.""" + +import json +import math + +import numpy as np +import pytest +import surpyval as surv + +from repyability import AvailabilityContract, NPVComparison, RepairableRBD +from repyability.tests.catalogue import systems_of_every_kind + +E = surv.Exponential.from_params +W = surv.Weibull.from_params +LINE = [("s", "p"), ("p", "t")] + + +def pump(mttr=10.0, life=E([1e-3])): + return RepairableRBD( + LINE, + { + "p": { + "reliability": life, + "repairability": E([1 / mttr]), + "repair_cost": 500.0, + "acquisition_cost": 2000.0, + } + }, + ) + + +def terms(**kwargs): + given = dict(target=0.99, penalty_per_point=1000.0) + given.update(kwargs) + return AvailabilityContract(730.0, **given) + + +def test_a_payoff_by_points(): + contract = AvailabilityContract( + 10.0, target=0.9, penalty_per_point=50.0, bonus_per_point=20.0, cap=300 + ) + paid = contract.payoff([0.9, 0.95, 0.85, 0.0, 1.0]) + assert paid.tolist() == pytest.approx([0.0, 100.0, -250.0, -300.0, 200.0]) + + +def test_a_target_of_0_pays_nothing(): + rbd = pump() + kwargs = dict(discount_rate=1e-5, value_rate=10.0, mc_samples=300, seed=4) + plain = rbd.npv_distribution(8760.0, **kwargs) + runs = rbd.npv_distribution(8760.0, contract=terms(target=0.0), **kwargs) + assert np.all(runs.contract_samples == 0.0) + assert runs.contract_payoff == 0.0 + assert np.array_equal(runs.samples, plain.samples) + assert plain.contract is None and plain.contract_samples is None + + +def test_a_system_that_never_fails_is_paid_in_closed_form(): + # A life of mean 1e15 hours: no run fails within the horizon. + rbd = pump(life=E([1e-15])) + rate, horizon = 1e-4, 8760.0 + contract = AvailabilityContract( + 730.0, + target=0.95, + penalty_per_point=1000.0, + bonus_per_point=400.0, + cap=1500.0, + ) + runs = rbd.npv_distribution( + horizon, discount_rate=rate, mc_samples=200, seed=1, contract=contract + ) + ends = 730.0 * np.arange(1, 13) + assert runs.period_ends == pytest.approx(ends.tolist()) + assert np.all(runs.period_availability == 1.0) + # 5 points over at 400 a point is 2,000, capped at 1,500 a month. + each = 1500.0 * np.exp(-rate * ends).sum() + assert runs.contract_samples == pytest.approx(np.full(200, each)) + assert runs.undiscounted_contract_payoff == pytest.approx(1500.0 * 12) + assert runs.mean == pytest.approx(each - 2000.0) + + +def test_each_run_is_paid_on_its_own_availability(): + rbd = pump(mttr=50.0) + rate, horizon, n = 2e-5, 8760.0, 300 + contract = terms(bonus_per_point=100.0) + runs = rbd.npv_distribution( + horizon, discount_rate=rate, mc_samples=n, seed=7, contract=contract + ) + ends = np.array(runs.period_ends) + paid = contract.payoff(runs.period_availability) + assert runs.contract_samples == pytest.approx( + paid @ np.exp(-rate * ends), rel=1e-12 + ) + assert np.allclose( + runs.samples, + runs.value_samples - runs.cost_samples + runs.contract_samples, + rtol=1e-12, + ) + # The periods cover the year: their uptime is each run's. + up = rbd.simulate_timelines(horizon, mc_samples=n, seed=7).system.uptime + assert runs.period_availability @ np.diff(np.r_[0.0, ends]) == ( + pytest.approx(up, rel=1e-10) + ) + assert np.any(runs.contract_samples < 0.0) + + +def test_a_contract_alone_is_priced(): + rbd = RepairableRBD( + LINE, {"p": {"reliability": E([1e-3]), "repairability": E([0.1])}} + ) + runs = rbd.npv_distribution( + 8760.0, mc_samples=50, seed=1, contract=terms() + ) + assert runs.mean == pytest.approx(runs.contract_payoff) + assert runs.mean < 0.0 + + +@pytest.mark.parametrize("contract", [None, terms(bonus_per_point=50.0)]) +def test_identical_plans_differ_by_exactly_0(contract): + gain = pump().compare_npv( + pump(), + 8760.0, + discount_rate=1e-5, + value_rate=10.0, + contract=contract, + mc_samples=300, + seed=2, + ) + assert isinstance(gain, NPVComparison) + assert np.all(gain.differences == 0.0) + assert gain.mean == 0.0 and gain.interval.standard_error == 0.0 + assert gain.probability_other_better == 0.0 + + +def test_the_common_numbers_shrink_the_difference_variance(): + kwargs = dict( + discount_rate=1e-5, + value_rate=10.0, + mc_samples=1000, + seed=11, + contract=terms(bonus_per_point=50.0), + ) + gain = pump(5.0).compare_npv(pump(10.0), 8760.0, **kwargs) + this = pump(5.0).npv_distribution(8760.0, **kwargs) + other = pump(10.0).npv_distribution(8760.0, **kwargs) + # Each plan's runs are npv_distribution's, by seed. + assert np.array_equal(gain.this.samples, this.samples) + assert np.array_equal(gain.other.samples, other.samples) + assert np.var(gain.differences) < np.var(this.samples) + np.var( + other.samples + ) + # About half here: the contract's thresholds pay on small + # differences in a period's uptime, which the plans do not share. + assert gain.interval.standard_error < 0.5 * gain.independent_standard_error + # A faster repair is worth more, in nearly every run. + assert gain.interval.lower > 0.0 + assert gain.probability_other_better < 0.1 + json.dumps(gain.to_dict()) + + +def test_draws_that_cannot_be_matched_are_refused_by_name(): + unstreamed = systems_of_every_kind()["unstreamable"] + with pytest.raises(NotImplementedError, match="'b'") as caught: + unstreamed.compare_npv( + unstreamed, 100.0, value_rate=1.0, mc_samples=10, seed=1 + ) + assert "independently" in str(caught.value) + + +def test_terms_go_through_plain_data(): + contract = AvailabilityContract( + [100.0, 250.0], target=0.9, penalty_per_point=5.0, cap=20.0 + ) + data = json.loads(json.dumps(contract.to_dict())) + assert AvailabilityContract.from_dict(data) == contract + runs = pump().npv_distribution( + 300.0, value_rate=1.0, mc_samples=20, seed=1, contract=data + ) + assert runs.period_ends == [100.0, 250.0] + assert runs.contract == contract.to_dict() + json.dumps(runs.to_dict()) + + +@pytest.mark.parametrize( + "args, match", + [ + ((0.0, 0.9, 1.0), "length"), + (([10.0, 5.0], 0.9, 1.0), "increasing"), + ((10.0, 1.5, 1.0), "target"), + ((10.0, 0.9, -1.0), "penalty_per_point"), + ((10.0, 0.9, 1.0, math.nan), "bonus_per_point"), + ((10.0, 0.9, 1.0, 0.0, 0.0), "cap"), + ], +) +def test_terms_are_checked(args, match): + with pytest.raises(ValueError, match=match): + AvailabilityContract(*args) + + +def test_periods_must_fit_the_horizon(): + with pytest.raises(ValueError, match="after the horizon"): + pump().npv_distribution( + 100.0, + value_rate=1.0, + mc_samples=10, + seed=1, + contract=AvailabilityContract([50.0, 150.0], 0.9, 1.0), + ) + with pytest.raises(ValueError, match="No whole period"): + pump().npv_distribution( + 100.0, + value_rate=1.0, + mc_samples=10, + seed=1, + contract=AvailabilityContract(200.0, 0.9, 1.0), + ) + with pytest.raises(TypeError, match="contract"): + pump().npv_distribution(100.0, value_rate=1.0, contract=0.9) + with pytest.raises(TypeError, match="other"): + pump().compare_npv("pump", 100.0, value_rate=1.0) diff --git a/repyability/tests/test_npv_distribution.py b/repyability/tests/test_npv_distribution.py new file mode 100644 index 00000000..abce419c --- /dev/null +++ b/repyability/tests/test_npv_distribution.py @@ -0,0 +1,282 @@ +"""The net present value of each simulated run of a ``RepairableRBD`` +(``npv_distribution``): its mean against the exact ``expected_npv``, +each run at no discounting against the simulation's own cost and uptime, +the engines run for run, and the summaries against a hand calculation.""" + +import json +import math + +import numpy as np +import pytest +import surpyval as surv + +from repyability import NPVDistribution, RepairableRBD +from repyability.rbd import _npv_runs, routes + +E = surv.Exponential.from_params +W = surv.Weibull.from_params +LINE = [("s", "p"), ("p", "t")] +PAIR = [("s", "a"), ("s", "b"), ("a", "t"), ("b", "t")] + + +def pump(): + return RepairableRBD( + LINE, + { + "p": { + "reliability": E([1e-3]), + "repairability": E([0.1]), + "repair_cost": 500.0, + "acquisition_cost": 2000.0, + } + }, + ) + + +def age_replaced(): + return RepairableRBD( + LINE, + { + "p": { + "reliability": W([100.0, 2.5]), + "repairability": W([6.0, 1.5]), + "repair_cost": 30.0, + "replace_cost": 5.0, + "downtime_cost": 1.0, + "preventive": { + "interval": 60.0, + "policy": "age", + "duration": W([2.0, 2.0]), + "cost": 10.0, + }, + } + }, + downtime_cost_rate=4.0, + ) + + +def crews(life=None): + spec = { + "reliability": life or E([1e-2]), + "repairability": E([0.05]), + "repair_cost": 10.0, + "downtime_cost": 0.5, + } + return RepairableRBD( + PAIR, + {"a": dict(spec), "b": dict(spec)}, + repair_crews=1, + downtime_cost_rate=100.0, + ) + + +@pytest.mark.parametrize("make", [pump, age_replaced, crews]) +def test_the_mean_is_the_expected_npv(make): + rbd = make() + horizon, rate, value = 400.0, 2e-3, 3.0 + runs = rbd.npv_distribution( + horizon, discount_rate=rate, value_rate=value, mc_samples=4000, seed=3 + ) + exact = rbd.expected_npv(horizon, discount_rate=rate, value_rate=value) + interval = runs.mean_interval(0.9999) + assert interval.lower < exact.npv < interval.upper + assert runs.mean == pytest.approx(runs.value - runs.cost, rel=1e-12) + assert np.allclose( + runs.samples, runs.value_samples - runs.cost_samples, rtol=1e-12 + ) + # The same split of value and cost, each within its own error. + assert set(runs.cost_by_category) == set(exact.cost_by_category) + for category, amount in exact.cost_by_category.items(): + assert runs.cost_by_category[category] == pytest.approx( + amount, rel=0.1, abs=1e-9 + ), category + assert set(runs.cost_by_component) == set(exact.cost_by_component) + + +@pytest.mark.parametrize( + "make", [pump, age_replaced, crews, lambda: crews(W([100.0, 2.0]))] +) +def test_undiscounted_each_run_is_its_value_less_its_simulated_cost(make): + rbd = make() + horizon, value, n = 300.0, 2.0, 200 + runs = rbd.npv_distribution( + horizon, value_rate=value, mc_samples=n, seed=5 + ) + cost = rbd.cost(horizon, mc_samples=n, seed=5, control_variate=False) + uptime = rbd.simulate_timelines(horizon, mc_samples=n, seed=5).system + expected = value * uptime.uptime - cost.samples - cost.acquisition_cost + assert np.allclose(runs.samples, expected, rtol=1e-10, atol=1e-8) + assert runs.undiscounted_npv == pytest.approx(runs.mean, rel=1e-12) + + +def test_crews_with_other_lives_are_simulated(): + rbd = crews(W([100.0, 2.0])) + assert rbd.analysis_routes()["expected_npv"].route == routes.REFUSED + route = rbd.analysis_routes()["npv_distribution"] + assert route.route == routes.SIMULATED + runs = rbd.npv_distribution( + 200.0, discount_rate=1e-3, mc_samples=50, seed=1 + ) + assert runs.samples.shape == (50,) + + +def test_the_engines_agree_run_for_run(): + pytest.importorskip("numba") + rbd = age_replaced() + kwargs = dict(discount_rate=1e-3, value_rate=2.0, mc_samples=300, seed=9) + python = rbd.npv_distribution(250.0, engine="python", **kwargs) + numba = rbd.npv_distribution(250.0, engine="numba", **kwargs) + assert np.array_equal(python.samples, numba.samples) + + +def test_seeded_runs_repeat_and_are_made_in_parts(monkeypatch): + rbd = age_replaced() + whole = rbd.npv_distribution( + 200.0, discount_rate=1e-3, mc_samples=50, seed=2 + ) + again = rbd.npv_distribution( + 200.0, discount_rate=1e-3, mc_samples=50, seed=2 + ) + assert np.array_equal(whole.samples, again.samples) + monkeypatch.setattr(_npv_runs, "_CHUNK", 7) + parts = rbd.npv_distribution( + 200.0, discount_rate=1e-3, mc_samples=50, seed=2 + ) + assert np.allclose(parts.samples, whole.samples, rtol=1e-13, atol=1e-12) + + +def test_an_unseeded_run_keeps_the_seed_it_drew(): + rbd = pump() + first = rbd.npv_distribution(500.0, value_rate=1.0, mc_samples=20) + again = rbd.npv_distribution( + 500.0, value_rate=1.0, mc_samples=20, seed=first.seed + ) + assert np.array_equal(first.samples, again.samples) + + +def test_the_summaries_by_hand(): + rbd = age_replaced() + runs = rbd.npv_distribution( + 200.0, + discount_rate=1e-3, + value_rate=1.0, + mc_samples=10, + seed=4, + tail=0.3, + hurdle=0.0, + ) + x = sorted(runs.samples.tolist()) + # The ceil(p n)-th lowest: 1st, 5th and 9th of ten. + assert (runs.p10, runs.p50, runs.p90) == (x[0], x[4], x[8]) + assert runs.percentile(25) == x[2] + assert runs.percentile(100) == x[9] + assert runs.cvar == pytest.approx(sum(x[:3]) / 3, rel=1e-15) + assert runs.probability_below_hurdle == sum(v < 0.0 for v in x) / 10 + assert runs.probability_below(x[5]) == 0.5 + se = float(np.std(x, ddof=1)) / math.sqrt(10) + assert runs.mean_interval().standard_error == pytest.approx(se) + + +def test_a_percentile_interval_is_binomial(): + # For the median of 100 runs at 95%, the 40th and 61st lowest: the + # binomial(100, 0.5) count below the median is in [40, 60] with + # probability 0.965. + samples = np.arange(100.0)[::-1] + result = NPVDistribution( + **{ + **dict.fromkeys(NPVDistribution.__dataclass_fields__, 0.0), + "samples": samples, + } + ) + assert result.percentile_interval(50) == (39.0, 60.0) + lower, upper = result.percentile_interval(1) + # The 1st percentile: no run low enough for a lower bound; the 4th + # lowest above. + assert lower == -math.inf and upper == 3.0 + with pytest.raises(ValueError, match="percentile"): + result.percentile(0) + + +def test_it_goes_through_json(): + runs = pump().npv_distribution( + 500.0, value_rate=1.0, mc_samples=5, seed=1, hurdle=10.0 + ) + data = json.loads(json.dumps(runs.to_dict())) + assert len(data["samples"]) == 5 + assert data["probability_below_hurdle"] == runs.probability_below_hurdle + assert "NPVDistribution(mean=" in repr(runs) + + +def test_a_cost_the_histories_do_not_record_is_refused(): + rbd = RepairableRBD( + LINE, + { + "p": { + "reliability": W([100.0, 2.5]), + "repairability": E([0.2]), + "repair_cost": 30.0, + "preventive": {"interval": 60.0, "cost": 10.0}, + } + }, + ) + route = rbd.analysis_routes()["npv_distribution"] + assert route.route == routes.REFUSED + with pytest.raises(NotImplementedError, match="duration") as caught: + rbd.npv_distribution(100.0, mc_samples=10, seed=1) + assert "'p'" in str(caught.value) + standby = RepairableRBD( + LINE, + { + "p": { + "reliability": E([1e-2]), + "repairability": E([0.2]), + "repair_cost": 1.0, + "standby": {"units": 2, "k": 1}, + } + }, + ) + with pytest.raises(NotImplementedError, match="standby"): + standby.npv_distribution(100.0, mc_samples=10, seed=1) + + +def test_a_cost_given_as_a_distribution_is_charged_its_mean(): + rbd = RepairableRBD( + LINE, + { + "p": { + "reliability": E([1e-2]), + "repairability": E([0.2]), + "repair_cost": surv.Normal.from_params([50.0, 5.0]), + } + }, + ) + runs = rbd.npv_distribution(300.0, mc_samples=20, seed=1) + failures = rbd.simulate_timelines(300.0, mc_samples=20, seed=1) + count = failures.components["p"].failures + assert runs.priced_at_mean == ["p"] + assert np.allclose(runs.cost_samples, 50.0 * count) + + +@pytest.mark.parametrize( + "kwargs, match", + [ + ({"tail": 0.0}, "tail"), + ({"tail": 1.5}, "tail"), + ({"hurdle": math.inf}, "hurdle"), + ({"mc_samples": 0}, "mc_samples"), + ({"engine": "fast"}, "engine"), + ], +) +def test_inputs_are_checked(kwargs, match): + with pytest.raises(ValueError, match=match): + pump().npv_distribution(100.0, **{"seed": 1, **kwargs}) + + +def test_nothing_priced_and_no_value_is_refused(): + rbd = RepairableRBD( + LINE, {"p": {"reliability": E([1e-2]), "repairability": E([0.2])}} + ) + with pytest.raises(routes.Refused): + rbd.npv_distribution(100.0, mc_samples=5, seed=1) + runs = rbd.npv_distribution(100.0, value_rate=1.0, mc_samples=5, seed=1) + assert runs.cost == 0.0 and runs.cost_by_category == {} diff --git a/repyability/tests/test_npv_escalation.py b/repyability/tests/test_npv_escalation.py new file mode 100644 index 00000000..e8574b5c --- /dev/null +++ b/repyability/tests/test_npv_escalation.py @@ -0,0 +1,292 @@ +"""Value and prices over time in a net present value (UC-57 of the +maintenance README): a value earned in steps (``ValueSchedule``), costs +and value that escalate, and rates that are real or nominal; and the +same escalation on dates, in ``repyability.schedule``.""" + +import json +import math +from datetime import date + +import numpy as np +import pytest +import surpyval as surv + +from repyability import RepairableRBD, ValueSchedule +from repyability.schedule import ( + Recurrence, + Task, + UsageForecast, + events_by_period, + work_by_period, +) + +E = surv.Exponential.from_params +LAMBDA, MU, PRICE = 1e-3, 0.1, 500.0 +T = 5 * 8760.0 +R = math.log(1.08) / 8760 +G = math.log(1.05) / 8760 + + +def pump(**more): + return RepairableRBD( + [("s", "p"), ("p", "t")], + { + "p": { + "reliability": E([LAMBDA]), + "repairability": E([MU]), + "repair_cost": PRICE, + "acquisition_cost": 20000.0, + **more, + } + }, + ) + + +def up_time(rate, start=0.0, end=T): + """The integral of exp(-rate t) A(t) from ``start`` to ``end``, in + closed form (A = MU/S + LAMBDA/S exp(-S t), S = LAMBDA + MU).""" + s = LAMBDA + MU + + def steady(d, t): + return t if d == 0.0 else -math.expm1(-d * t) / d + + def to(t): + return MU / s * steady(rate, t) + LAMBDA / s * steady(rate + s, t) + + return to(end) - to(start) + + +def test_a_growing_value_is_the_closed_form_s(): + # The value's part, apart from the costs, which do not change. + rbd = pump() + plain = rbd.expected_npv(T, discount_rate=R, value_rate=10.0) + grown = rbd.expected_npv( + T, discount_rate=R, value_rate=10.0, escalation={"value": G} + ) + assert grown.value == pytest.approx(10.0 * up_time(R - G), rel=1e-7) + assert grown.cost == plain.cost + assert grown.undiscounted_value == pytest.approx( + 10.0 * up_time(-G), rel=1e-7 + ) + + +@pytest.mark.parametrize("g", [G, 2.5 * R, -G]) +def test_an_escalated_cost_is_the_cost_discounted_at_the_rate_less_it(g): + # Also a growth above the rate: a rate below 0, over a horizon. + rbd = pump() + grown = rbd.expected_npv( + T, discount_rate=R, value_rate=10.0, escalation={"repair": g} + ) + exact = PRICE * LAMBDA * up_time(R - g) + assert grown.cost_by_category["repair"] == pytest.approx(exact, rel=1e-7) + assert grown.cost_by_category["acquisition"] == 20000.0 + + +def test_a_component_s_growth_comes_before_its_category_s(): + rbd = pump() + a = rbd.expected_npv(T, discount_rate=R, escalation={"p": G}) + b = rbd.expected_npv( + T, discount_rate=R, escalation={"p": G, "repair": 3 * G} + ) + c = rbd.expected_npv(T, discount_rate=R, escalation={"repair": G}) + assert a.npv == b.npv == c.npv + + +def test_steps_of_value_are_the_sum_of_the_steps_valued_apart(): + rbd = pump() + schedule = ValueSchedule([0.0, 8760.0], [10.0, 12.0]) + stepped = rbd.expected_npv( + T, discount_rate=R, value_rate=schedule, periods=5 + ) + exact = 10.0 * up_time(R, 0.0, 8760.0) + 12.0 * up_time(R, 8760.0, T) + assert stepped.value == pytest.approx(exact, rel=1e-7) + first = rbd.expected_npv(8760.0, discount_rate=R, value_rate=10.0) + whole = rbd.expected_npv(T, discount_rate=R, value_rate=12.0) + early = rbd.expected_npv(8760.0, discount_rate=R, value_rate=12.0) + assert stepped.value == pytest.approx( + first.value + whole.value - early.value, rel=1e-9 + ) + values = [r for r in stepped.cash_flows if r["category"] == "value"] + assert len(values) == 5 + assert sum(r["present_value"] for r in values) == pytest.approx( + stepped.value, rel=1e-12 + ) + assert math.isnan(stepped.value_rate) + assert stepped.value_schedule == schedule + out = json.loads(json.dumps(stepped.to_dict())) + assert out["value_schedule"] == { + "times": [0.0, 8760.0], + "rates": [10.0, 12.0], + } + + +def test_inflation_on_every_stream_leaves_the_npv_as_it_is(): + rbd = pump(replace_cost=100.0) + i = math.log(1.03) / 8760 + kwargs = dict(value_rate=10.0, salvage=1000.0, periods=5) + real = rbd.expected_npv( + T, + discount_rate=R, + escalation={"repair": G}, + rates="real", + inflation=i, + **kwargs, + ) + nominal = rbd.expected_npv( + T, + discount_rate=R + i, + escalation={ + "repair": G + i, + "replace": i, + "value": i, + "salvage": i, + }, + **kwargs, + ) + in_real_terms = rbd.expected_npv( + T, discount_rate=R, escalation={"repair": G}, **kwargs + ) + for result in (nominal, in_real_terms): + assert real.npv == pytest.approx(result.npv, rel=1e-12) + # Its undiscounted amounts are nominal, and its rate the real one. + assert real.undiscounted_npv == pytest.approx( + nominal.undiscounted_npv, rel=1e-12 + ) + assert real.discount_rate == R + assert (real.rate_basis, real.inflation) == ("real", i) + assert real.eac == pytest.approx(in_real_terms.eac, rel=1e-12) + + +def test_no_growth_and_one_rate_change_nothing(): + rbd = pump(replace_cost=100.0) + kwargs = dict(discount_rate=R, value_rate=10.0, periods=5, salvage=50.0) + before = rbd.expected_npv(T, **kwargs).to_dict() + after = rbd.expected_npv(T, escalation={}, **kwargs).to_dict() + assert after == before + assert before["escalation"] == {} and before["rate_basis"] == "nominal" + + +def test_a_salvage_grows_at_its_own_rate(): + rbd = pump() + plain = rbd.expected_npv(T, discount_rate=R, salvage=1000.0) + grown = rbd.expected_npv( + T, discount_rate=R, salvage=1000.0, escalation={"salvage": G} + ) + assert grown.salvage == pytest.approx( + plain.salvage * math.exp(G * T), rel=1e-12 + ) + assert grown.undiscounted_salvage == pytest.approx( + 1000.0 * math.exp(G * T), rel=1e-12 + ) + + +@pytest.mark.parametrize( + "kwargs, error, match", + [ + ({"escalation": {"x": 0.1}}, ValueError, "no component"), + ({"escalation": {"repair": "fast"}}, ValueError, "finite growth"), + ({"escalation": 0.1}, ValueError, "must be a dict"), + ({"rates": "both"}, ValueError, "rates"), + ({"inflation": 0.01}, ValueError, 'rates="real"'), + ({"value_rate": lambda t: 1.0}, ValueError, "ValueSchedule"), + ], +) +def test_what_is_refused(kwargs, error, match): + with pytest.raises(error, match=match): + pump().expected_npv(T, **{"value_rate": 1.0, **kwargs}) + + +def test_a_schedule_is_steps_of_plain_numbers(): + with pytest.raises(TypeError, match="plain numbers"): + ValueSchedule(lambda t: t, [1.0]) + with pytest.raises(ValueError, match="the first 0"): + ValueSchedule([1.0, 2.0], [1.0, 1.0]) + with pytest.raises(ValueError, match="one for each|for each of"): + ValueSchedule([0.0, 2.0], [1.0]) + + +# -- on dates ----------------------------------------------------------------- + + +def test_a_task_s_present_value_takes_its_cost_grown(): + task = Task( + "grease", + every=Recurrence.every(30, "days", "2026-11-20"), + cost=250.0, + ) + due = task.due("2026-11-20", "2028-11-19", discount=0.07, escalation=0.03) + start = date(2026, 11, 20) + by_hand = sum( + 250.0 * (1.03 / 1.07) ** ((day - start).days / 365.25) + for day in due.done + ) + assert due.npv == pytest.approx(by_hand, rel=1e-12) + assert due.discount == 0.07 + assert "escalate at 3% a year" in " ".join(due.notes) + plain = task.due("2026-11-20", "2028-11-19", discount=0.07) + assert due.npv > plain.npv + assert due.cost == plain.cost # at today's prices + work = work_by_period( + [task], + "year", + "2026-11-20", + "2028-11-19", + discount=0.07, + escalation=0.03, + ) + assert work.total_npv == pytest.approx(by_hand, rel=1e-12) + + +def test_for_ever_needs_the_escalation_below_the_discount(): + task = Task( + "grease", + every=Recurrence.every(30, "days", "2026-11-20"), + cost=250.0, + ) + grown = task.long_run_value("2026-11-20", 0.07, escalation=0.03) + net = 1.07 / 1.03 - 1.0 + assert grown.npv == pytest.approx( + task.long_run_value("2026-11-20", net).npv, rel=1e-12 + ) + with pytest.raises(ValueError, match="without end"): + task.long_run_value("2026-11-20", 0.03, escalation=0.03) + with pytest.raises(ValueError, match="give a discount"): + task.due("2026-11-20", "2027-11-19", escalation=0.03) + + +@pytest.mark.parametrize("escalation", [0.03, 0.12]) +def test_a_system_s_costs_on_dates_are_expected_npv_s(escalation): + # The diagram's clock is calendar time in hours: the yearly rates are + # continuous ones per hour, and a growth above the discount (12% + # against 7%) is a rate below 0 over the window. + rbd = RepairableRBD( + [("s", "p"), ("p", "t")], + { + "p": { + "reliability": E([1e-3]), + "repairability": E([0.1]), + "repair_cost": 500.0, + } + }, + ) + usage = UsageForecast.calendar("2027-01-01", "2029-01-01") + found = events_by_period( + rbd, + usage, + "year", + unit="hours", + cost=True, + mc_samples=50, + seed=1, + discount=0.07, + escalation=escalation, + ) + hours = 24.0 * 365.25 + rate = math.log(1.07) / hours + growth = math.log(1.0 + escalation) / hours + end = float(found.model_ends[-1]) + npv = rbd.expected_npv( + end, discount_rate=rate, escalation={"repair": growth} + ) + assert found.npv == pytest.approx(npv.cost, rel=1e-6) + assert np.all(np.diff(found.expected_npv) != 0.0) diff --git a/repyability/tests/test_npv_inspection.py b/repyability/tests/test_npv_inspection.py new file mode 100644 index 00000000..b1de7293 --- /dev/null +++ b/repyability/tests/test_npv_inspection.py @@ -0,0 +1,268 @@ +"""The test intervals chosen for an equivalent annual cost or a net +present value (``optimal_inspection_intervals(objective=...)``): a tested +unit's discounted cycle against its closed form and against +``expected_cost``, the cost rate at a rate of 0, and a PFDavg limit that +binds under each objective.""" + +import math +import warnings + +import numpy as np +import pytest +import surpyval as surv + +from repyability import RepairableRBD +from repyability.rbd import _discounted_long_run + +RATE, TEST, FOUND, DOWN = 2e-5, 500.0, 2000.0, 3.0 + + +def valve(life=None, interval=8760.0, offset=0.0, **inspection): + return { + "reliability": life or surv.Exponential.from_params([RATE]), + "repairability": "instant", + "replace_cost": FOUND, + "downtime_cost": DOWN, + "inspection": { + "interval": interval, + "cost": TEST, + "offset": offset, + **inspection, + }, + } + + +def one(downtime_cost_rate=20.0, **kwargs): + return RepairableRBD( + [("s", "v"), ("v", "t")], + {"v": valve(**kwargs)}, + downtime_cost_rate=downtime_cost_rate, + ) + + +def closed_form(interval, rate): + """An exponential unit's equivalent annual cost, its hidden failures + found at tests every ``interval`` and repaired at once: with ``q`` + the chance of surviving an interval and ``e`` an interval's + discount, a cycle ends at test ``k`` with chance ``q^(k-1) (1 - q)``, + so its discount is ``phi = e (1 - q) / (1 - e q)``; its tests cost + ``TEST e / (1 - e q)``, the failure ``FOUND phi`` when found, and + the unit's downtime, from the failure (discounted, ``lam / (lam + + r)``) to the test, ``DOWN (lam / (lam + r) - phi) / r``.""" + q = math.exp(-RATE * interval) + e = math.exp(-rate * interval) + phi = e * (1.0 - q) / (1.0 - e * q) + cycle = ( + TEST * e / (1.0 - e * q) + + FOUND * phi + + DOWN * (RATE / (RATE + rate) - phi) / rate + ) + return rate * cycle / (1.0 - phi) + + +@pytest.mark.parametrize("rate", [1e-6, 1e-5, 1e-4, 1e-3]) +@pytest.mark.parametrize("interval", [100.0, 1500.0, 8760.0, 90000.0]) +def test_an_exponential_units_cycle_is_its_closed_form(rate, interval): + system = one(interval=interval) + assert _discounted_long_run.node_eac(system, "v", rate) == pytest.approx( + closed_form(interval, rate), rel=1e-10 + ) + + +def test_the_closed_form_tends_to_the_cost_rate(): + system = one(interval=1500.0, downtime_cost_rate=0.0) + assert closed_form(1500.0, 1e-10) == pytest.approx( + system.expected_cost_rate(), rel=1e-6 + ) + + +@pytest.mark.parametrize("offset", [0.0, 100.0]) +@pytest.mark.parametrize("weibull", [False, True]) +def test_a_tested_units_cost_is_its_discounted_costs_for_ever(offset, weibull): + # r times the present value of every cost from new, over a horizon + # so long that what is left is discounted to exp(-40). + rate = 1e-3 + life = surv.Weibull.from_params([1500, 2.0]) if weibull else None + system = one( + life=life, interval=300.0, offset=offset, downtime_cost_rate=0.0 + ) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + present = system.expected_cost(40.0 / rate, discount_rate=rate).mean + eac = _discounted_long_run.node_eac(system, "v", rate) + assert eac == pytest.approx(rate * float(present), rel=1e-6) + + +@pytest.mark.parametrize( + "kwargs", + [ + {}, + {"min_availability": 0.99}, + {"allowed": [730.0, 2190.0, 4380.0, 8760.0]}, + {"allowed": [730.0, 2190.0, 4380.0], "offset_shares": "stagger"}, + ], +) +def test_at_rate_0_the_plan_is_the_cost_rates(kwargs): + system = pair() if "allowed" in kwargs else one() + by_cost = system.optimal_inspection_intervals(**kwargs) + by_eac = system.optimal_inspection_intervals(objective="eac", **kwargs) + assert by_eac.intervals == by_cost.intervals + assert by_eac.offsets == by_cost.offsets + assert by_eac.cost_rate == by_cost.cost_rate + assert by_eac.availability == by_cost.availability + assert by_eac.objective_value == by_cost.cost_rate + + +def pair(**kwargs): + return RepairableRBD( + [("s", "v1"), ("s", "v2"), ("v1", "t"), ("v2", "t")], + {"v1": valve(), "v2": valve()}, + downtime_cost_rate=2000.0, + **kwargs, + ) + + +def test_one_units_interval_is_the_closed_forms_best(): + rate = 1e-4 + system = one(downtime_cost_rate=0.0) + plan = system.optimal_inspection_intervals( + objective="eac", discount_rate=rate + ) + grid = np.geomspace(300.0, 20000.0, 400) + costs = [closed_form(t, rate) for t in grid] + best = int(np.argmin(costs)) + step = grid[1] / grid[0] + assert grid[best] / step < plan.intervals["v"] < grid[best] * step + assert plan.objective_value <= costs[best] * (1 + 1e-12) + assert plan.objective_value == pytest.approx( + closed_form(plan.intervals["v"], rate), rel=1e-10 + ) + # Discounted, the tests are a little further apart here (observed + # on this case). + plain = system.optimal_inspection_intervals() + assert plan.intervals["v"] > plain.intervals["v"] + + +@pytest.mark.parametrize( + "objective, extra", + [("eac", {}), ("npv", {"horizon": 20000.0})], +) +def test_a_pfd_limit_binds_under_each_objective(objective, extra): + system = one() + kwargs = dict(objective=objective, discount_rate=1e-4, **extra) + free = system.optimal_inspection_intervals(**kwargs) + limit = 0.5 * (1.0 - free.availability) # half its PFDavg + held = system.optimal_inspection_intervals( + min_availability=1.0 - limit, **kwargs + ) + assert 1.0 - held.availability == pytest.approx(limit, rel=1e-4) + assert 1.0 - held.availability <= limit * (1 + 1e-9) + assert held.intervals["v"] < free.intervals["v"] + worse = held.objective_value - free.objective_value + assert worse > 0 if objective == "eac" else worse < 0 + assert held.objective == objective + + +def test_npv_from_allowed_intervals_is_the_best_expected_npv(): + system = pair() + calendar = [2190.0, 4380.0] + kwargs = dict(discount_rate=1e-4, value_rate=10.0) + plan = system.optimal_inspection_intervals( + objective="npv", horizon=20000.0, allowed=calendar, **kwargs + ) + values = {} + for a in calendar: + for b in calendar: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + values[(a, b)] = ( + system.with_intervals({"v1": a, "v2": b}) + .expected_npv(20000.0, **kwargs) + .npv + ) + best = max(values, key=values.get) + assert (plan.intervals["v1"], plan.intervals["v2"]) == best + assert plan.objective_value == pytest.approx(values[best], rel=1e-9) + assert plan.offsets == {"v1": 0.0, "v2": 0.0} + + +def test_offsets_are_chosen_with_the_objective(): + system = pair() + plan = system.optimal_inspection_intervals( + objective="eac", + discount_rate=1e-4, + allowed=[730.0, 2190.0, 4380.0], + offset_shares="stagger", + ) + assert plan.objective == "eac" + again = system.with_intervals(plan) + rate = 1e-4 + own = sum( + _discounted_long_run.node_eac(again, node, rate) + for node in ("v1", "v2") + ) + assert plan.objective_value == pytest.approx( + own + 2000.0 * (1.0 - again.mean_availability()), rel=1e-10 + ) + + +@pytest.mark.parametrize( + "inspection, repair", + [ + ({"coverage": 0.9, "full_test": 8760.0 * 4}, "instant"), + ({}, surv.Exponential.from_params([0.1])), + ({"duration": surv.Exponential.from_params([1.0])}, "instant"), + ], +) +def test_eac_refuses_tests_with_no_cycle_worked_out(inspection, repair): + spec = valve(**inspection) + spec["repairability"] = repair + system = RepairableRBD([("s", "v"), ("v", "t")], {"v": spec}) + with pytest.raises(NotImplementedError, match="tested") as refused: + system.optimal_inspection_intervals( + objective="eac", discount_rate=1e-4 + ) + assert 'objective="npv"' in str(refused.value) + plain = system.optimal_inspection_intervals() + by_eac = system.optimal_inspection_intervals(objective="eac") + assert by_eac.intervals == plain.intervals + + +def test_the_arguments_are_checked(): + choose = one().optimal_inspection_intervals + with pytest.raises(ValueError, match="objective must be"): + choose(objective="profit") + with pytest.raises(ValueError, match="discount_rate needs an objective"): + choose(discount_rate=1e-4) + with pytest.raises(ValueError, match="give horizon"): + choose(objective="npv") + with pytest.raises(ValueError, match="no horizon"): + choose(objective="eac", horizon=1000.0) + + +def test_crews_salaries_are_in_the_value(): + rate = 1e-4 + crewed = RepairableRBD( + [("s", "v"), ("v", "p"), ("p", "t")], + { + "v": valve(), + "p": { + "reliability": surv.Exponential.from_params([1e-3]), + "repairability": surv.Exponential.from_params([0.1]), + }, + }, + repair_crews=1, + crew_cost_rate=7.0, + ) + free = RepairableRBD( + **{**crewed._init_args, "repair_crews": None, "crew_cost_rate": 0.0} + ) + kwargs = dict(objective="eac", discount_rate=rate) + plan = crewed.optimal_inspection_intervals( + assume_unlimited_crews=True, **kwargs + ) + base = free.optimal_inspection_intervals(**kwargs) + assert plan.intervals == base.intervals + assert plan.objective_value == pytest.approx( + base.objective_value + 7.0, rel=1e-12 + ) diff --git a/repyability/tests/test_npv_intervals.py b/repyability/tests/test_npv_intervals.py new file mode 100644 index 00000000..99401514 --- /dev/null +++ b/repyability/tests/test_npv_intervals.py @@ -0,0 +1,402 @@ +"""The replacement intervals chosen for an equivalent annual cost or a net +present value (``optimal_replacement_intervals(objective=...)``): against +one unit's discounted policy, the cost rate at a rate of 0, the textbook +discounted renewal cycle on a grid, and ``expected_npv`` itself.""" + +import json +import math +import warnings + +import numpy as np +import pytest +import surpyval as surv +from scipy.integrate import quad + +from repyability import NonRepairable, RepairableRBD +from repyability.rbd import _discounted_long_run + +A_YEAR = math.log(1.10) / 8760 + + +def pump(interval=600.0, duration=True): + spec = { + "reliability": surv.Weibull.from_params([1000, 2.5]), + "repairability": surv.LogNormal.from_params([3.0, 0.5]), + "replace_cost": 5000.0, + "downtime_cost": 30.0, + "preventive": {"interval": interval, "cost": 1000.0}, + } + if duration: + spec["preventive"]["duration"] = surv.Weibull.from_params([8, 3]) + return spec + + +def plant(**kwargs): + return RepairableRBD( + [("s", "a"), ("a", "b1"), ("a", "b2"), ("b1", "t"), ("b2", "t")], + {"a": pump(), "b1": pump(), "b2": pump()}, + downtime_cost_rate=500.0, + **kwargs, + ) + + +def one_unit(life, cp=1.0, cu=5.0, interval=500.0): + return RepairableRBD( + [("s", "unit"), ("unit", "t")], + { + "unit": { + "reliability": life, + "repairability": "instant", + "replace_cost": cu, + "preventive": {"interval": interval, "cost": cp}, + } + }, + ) + + +@pytest.mark.parametrize("rate", [A_YEAR, 1e-4, 1e-3]) +def test_one_unit_is_the_units_own_discounted_policy(rate): + life = surv.Weibull.from_params([1000, 2.5]) + unit = NonRepairable(life) + unit.set_costs_planned_and_unplanned(cp=1, cu=5) + policy = unit.optimal_replacement_policy(discount_rate=rate) + plan = one_unit(life).optimal_replacement_intervals( + objective="eac", discount_rate=rate + ) + assert plan.intervals["unit"] == pytest.approx(policy.interval, rel=1e-5) + assert plan.objective_value == pytest.approx(policy.eac, rel=1e-10) + assert plan.objective == "eac" and plan.discount_rate == rate + assert "Fox" in plan.basis and "Approximate" not in plan.basis + + +@pytest.mark.parametrize( + "targets", + [ + {}, + {"min_availability": 0.98032}, + {"allowed": [400.0, 500.0, 600.0, math.inf]}, + ], +) +def test_at_rate_0_the_plan_is_the_cost_rates(targets): + system = plant() + by_cost = system.optimal_replacement_intervals(**targets) + by_eac = system.optimal_replacement_intervals(objective="eac", **targets) + assert by_eac.intervals == by_cost.intervals + assert by_eac.cost_rate == by_cost.cost_rate + assert by_eac.availability == by_cost.availability + assert by_eac.objective_value == by_cost.cost_rate + assert by_cost.objective == "cost" and by_cost.objective_value is None + + +@pytest.mark.parametrize("duration", [True, False]) +def test_a_components_cost_is_its_discounted_costs_for_ever(duration): + # r times the present value of every cost from new, the horizon so + # long that what is left is discounted to exp(-40). + rate = 1e-3 + system = RepairableRBD( + [("s", "a"), ("a", "t")], {"a": pump(duration=duration)} + ) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + present = system.expected_cost(40.0 / rate, discount_rate=rate).mean + eac = _discounted_long_run.node_eac(system, "a", rate) + assert eac == pytest.approx(rate * float(present), rel=1e-6) + assert _discounted_long_run.node_eac(system, "a", 0.0) == pytest.approx( + system.expected_cost_rate(), rel=1e-9 + ) + + +SERIES = { + "a": dict(alpha=1000.0, beta=2.5, mu=0.05, cu=5000.0, cp=1000.0), + "b": dict(alpha=700.0, beta=3.5, mu=0.1, cu=3000.0, cp=400.0), +} +DOWN, VALUE = 800.0, 200.0 + + +def series(interval=500.0): + return RepairableRBD( + [("s", "a"), ("a", "b"), ("b", "t")], + { + node: { + "reliability": surv.Weibull.from_params( + [c["alpha"], c["beta"]] + ), + "repairability": surv.Exponential.from_params([c["mu"]]), + "replace_cost": c["cu"], + "preventive": {"interval": interval, "cost": c["cp"]}, + } + for node, c in SERIES.items() + }, + downtime_cost_rate=DOWN, + ) + + +def textbook(node, age, rate): + """A component's equivalent annual cost and long-run availability at + a replacement ``age``, written out: the failure density and the + survival function integrated by scipy, an exponential repair's + discounted mean time ``1 / (mu + r)``.""" + c = SERIES[node] + + def sf(x): + return math.exp(-((x / c["alpha"]) ** c["beta"])) + + def pdf(x): + return c["beta"] / x * (x / c["alpha"]) ** c["beta"] * sf(x) + + up = quad(lambda x: math.exp(-rate * x) * sf(x), 0, age)[0] + failed = quad(lambda x: math.exp(-rate * x) * pdf(x), 0, age)[0] + kept = math.exp(-rate * age) * sf(age) + repair = 1.0 / (c["mu"] + rate) + eac = (c["cu"] * failed + c["cp"] * kept) / (up + failed * repair) + mean_up = quad(sf, 0, age)[0] + availability = mean_up / (mean_up + (1.0 - sf(age)) / c["mu"]) + return eac, availability + + +def test_a_series_system_against_every_plan_of_a_grid(): + rate = 5e-4 + ages = np.geomspace(150.0, 1500.0, 47) + own = {node: [textbook(node, t, rate) for t in ages] for node in SERIES} + # The equivalent annual cost of every pair of ages, written out. + grid = np.array( + [ + [ + ea + eb + DOWN * (1.0 - aa * ab) - VALUE * aa * ab + for eb, ab in own["b"] + ] + for ea, aa in own["a"] + ] + ) + i, j = np.unravel_index(int(np.argmin(grid)), grid.shape) + system = series() + kwargs = dict(objective="eac", discount_rate=rate, value_rate=VALUE) + # From the grid's ages, every combination valued: the grid's best. + allowed = system.optimal_replacement_intervals( + allowed=[float(t) for t in ages[::2]], **kwargs + ) + coarse = grid[::2, ::2] + ci, cj = np.unravel_index(int(np.argmin(coarse)), coarse.shape) + assert allowed.intervals == { + "a": float(ages[::2][ci]), + "b": float(ages[::2][cj]), + } + assert allowed.objective_value == pytest.approx(coarse[ci, cj], rel=1e-8) + # Searched: no plan of the grid is better, and it is by the grid's. + plan = system.optimal_replacement_intervals(**kwargs) + assert plan.objective_value <= grid.min() + 1e-9 * abs(grid.min()) + step = ages[1] / ages[0] + assert ages[i] / step < plan.intervals["a"] < ages[i] * step + assert ages[j] / step < plan.intervals["b"] < ages[j] * step + assert "Approximate" in plan.basis + assert "downtime" in plan.basis and "value" in plan.basis + + +def test_a_higher_rate_does_not_shorten_these_intervals(): + # As observed on these cases; not a theorem, and asserted on them + # only. + life = surv.Weibull.from_params([1000, 2.5]) + unit = one_unit(life) + system = series() + rates = [0.0, A_YEAR, 1e-4, 5e-4, 1e-3] + lone, both = [], [] + for rate in rates: + kwargs = dict(objective="eac", discount_rate=rate) + lone.append(unit.optimal_replacement_intervals(**kwargs).intervals) + both.append(system.optimal_replacement_intervals(**kwargs).intervals) + for before, after in zip(lone, lone[1:]): + assert after["unit"] >= before["unit"] * (1 - 1e-6) + for before, after in zip(both, both[1:]): + for node in SERIES: + assert after[node] >= before[node] * (1 - 1e-6) + assert lone[-1]["unit"] > 1.05 * lone[0]["unit"] + + +def test_the_targets_are_kept(): + system = series() + kwargs = dict(objective="eac", discount_rate=5e-4) + free = system.optimal_replacement_intervals(**kwargs) + floor = free.availability + 0.0005 + held = system.optimal_replacement_intervals( + min_availability=floor, **kwargs + ) + assert held.availability >= floor - 1e-9 + assert held.objective_value > free.objective_value + # A cap on the long-run cost rate that the free plan does not meet: + # worth 5000 a unit time up, the best plan is the most available. + options = [150.0, 200.0, 300.0, 400.0, 500.0, 600.0] + kwargs["value_rate"] = 5000.0 + loose = system.optimal_replacement_intervals(allowed=options, **kwargs) + cheapest = system.optimal_replacement_intervals(allowed=options) + assert loose.cost_rate > cheapest.cost_rate + cap = 0.5 * (loose.cost_rate + cheapest.cost_rate) + capped = system.optimal_replacement_intervals( + max_cost_rate=cap, allowed=options, **kwargs + ) + assert capped.cost_rate <= cap < loose.cost_rate + assert capped.objective_value > loose.objective_value + assert capped.objective == "eac" + + +def npv_of(system, intervals, horizon, **kwargs): + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + return ( + system.with_intervals(intervals) + .expected_npv(horizon, **kwargs) + .npv + ) + + +def test_npv_from_allowed_intervals_is_the_best_expected_npv(): + life = surv.Weibull.from_params([1000, 2.5]) + unit = one_unit(life) + options = [350.0, 450.0, 525.0, 600.0, 800.0, math.inf] + kwargs = dict(discount_rate=1e-3) + values = [npv_of(unit, {"unit": t}, 3000.0, **kwargs) for t in options] + plan = unit.optimal_replacement_intervals( + objective="npv", horizon=3000.0, allowed=options, **kwargs + ) + best = int(np.argmax(values)) + assert plan.intervals == {"unit": options[best]} + assert plan.objective_value == pytest.approx(values[best], rel=1e-9) + assert plan.objective == "npv" and plan.horizon == 3000.0 + assert "expected_npv" in plan.basis + + +def test_npv_is_searched_from_the_long_runs_plan(): + life = surv.Weibull.from_params([1000, 2.5]) + unit = one_unit(life) + kwargs = dict(discount_rate=1e-3, value_rate=0.01) + long_run = unit.optimal_replacement_intervals(objective="eac", **kwargs) + plan = unit.optimal_replacement_intervals( + objective="npv", horizon=3000.0, **kwargs + ) + achieved = npv_of(unit, plan.intervals, 3000.0, **kwargs) + assert plan.objective_value == pytest.approx(achieved, rel=1e-9) + start = npv_of(unit, long_run.intervals, 3000.0, **kwargs) + assert plan.objective_value >= start - 1e-9 * abs(start) + assert plan.value_rate == 0.01 + + +def test_like_units_can_be_worth_replacing_at_different_ages_from_new(): + # From new, a pair replaced at one age are down together; the long + # run does not see it, the net present value does. + pair = RepairableRBD( + [("s", "b1"), ("s", "b2"), ("b1", "t"), ("b2", "t")], + {"b1": pump(), "b2": pump()}, + downtime_cost_rate=5000.0, + ) + options = [400.0, 600.0] + kwargs = dict(discount_rate=1e-4) + plan = pair.optimal_replacement_intervals( + objective="npv", horizon=3000.0, allowed=options, **kwargs + ) + values = { + (a, b): npv_of(pair, {"b1": a, "b2": b}, 3000.0, **kwargs) + for a in options + for b in options + } + best = max(values, key=values.get) + assert (plan.intervals["b1"], plan.intervals["b2"]) == best + assert plan.objective_value == pytest.approx(values[best], rel=1e-9) + + +def test_crews_salaries_are_in_the_value(): + crewed = plant(repair_crews=1, crew_cost_rate=7.0) + free = plant() + rate = 1e-4 + for objective, extra, paid in ( + ("eac", {}, 7.0), + ("npv", {"horizon": 2000.0}, 7.0 * -math.expm1(-rate * 2000) / rate), + ): + kwargs = dict( + objective=objective, + discount_rate=rate, + allowed={"a": [600.0], "b1": [500.0], "b2": [500.0]}, + **extra, + ) + with pytest.raises(NotImplementedError, match="crew"): + crewed.optimal_replacement_intervals(**kwargs) + plan = crewed.optimal_replacement_intervals( + assume_unlimited_crews=True, **kwargs + ) + base = free.optimal_replacement_intervals(**kwargs) + sign = -1.0 if objective == "npv" else 1.0 + assert plan.objective_value == pytest.approx( + base.objective_value + sign * paid, rel=1e-12 + ) + assert plan.cost_rate == pytest.approx(base.cost_rate + 7.0) + + +def with_valve(**schedule): + return RepairableRBD( + [("s", "a"), ("a", "v"), ("v", "t")], + { + "a": pump(), + "v": { + "reliability": surv.Exponential.from_params([1e-4]), + "repairability": surv.Exponential.from_params([0.1]), + "replace_cost": 100.0, + **schedule, + }, + }, + ) + + +@pytest.mark.parametrize( + "schedule, what", + [ + ({"inspection": {"interval": 500.0, "cost": 10.0}}, "tested"), + ( + { + "preventive": { + "interval": 2000.0, + "cost": 10.0, + "policy": "block", + } + }, + "block", + ), + ], +) +def test_eac_refuses_what_has_no_cycle_of_its_own(schedule, what): + system = with_valve(**schedule) + with pytest.raises(NotImplementedError, match=what) as refused: + system.optimal_replacement_intervals( + ["a"], objective="eac", discount_rate=1e-4 + ) + assert 'objective="npv"' in str(refused.value) + # Undiscounted, it is the cost rate, which has it. + plain = system.optimal_replacement_intervals(["a"]) + by_eac = system.optimal_replacement_intervals(["a"], objective="eac") + assert by_eac.intervals == plain.intervals + + +def test_the_arguments_are_checked(): + system = plant() + choose = system.optimal_replacement_intervals + with pytest.raises(ValueError, match="objective must be"): + choose(objective="profit") + with pytest.raises(ValueError, match="discount_rate needs an objective"): + choose(discount_rate=1e-4) + with pytest.raises(ValueError, match="value_rate and horizon need"): + choose(value_rate=3.0, horizon=100.0) + with pytest.raises(ValueError, match="give horizon"): + choose(objective="npv", discount_rate=1e-4) + with pytest.raises(ValueError, match="no horizon"): + choose(objective="eac", horizon=1000.0) + with pytest.raises(ValueError, match="value_rate must be"): + choose(objective="eac", value_rate=-1.0) + with pytest.raises(ValueError, match="discount_rate must be"): + choose(objective="eac", discount_rate=-0.1) + + +def test_the_plan_goes_through_json(): + plan = plant().optimal_replacement_intervals( + objective="eac", discount_rate=1e-4, value_rate=100.0 + ) + again = json.loads(json.dumps(plan.to_dict())) + assert again["objective"] == "eac" + assert again["objective_value"] == plan.objective_value + assert again["basis"] == plan.basis diff --git a/repyability/tests/test_npv_runs_own_end.py b/repyability/tests/test_npv_runs_own_end.py new file mode 100644 index 00000000..7550a478 --- /dev/null +++ b/repyability/tests/test_npv_runs_own_end.py @@ -0,0 +1,231 @@ +"""The valuations of simulated runs (``npv_distribution``, +``compare_npv``) take a unit's own retirement and salvage: the runs end +at the retirement, and each is credited the salvage at the end, against +the same runs valued by hand from a plan without them.""" + +import math + +import numpy as np +import pytest +import surpyval as surv + +from repyability import AgePolicy, Prices, RepairableRBD, UnitPlan +from repyability.rbd import routes + +W = surv.Weibull.from_params([400.0, 2.0]) +REPAIR = surv.LogNormal.from_params([1.0, 0.5]) +HORIZON = 300.0 +RATE = 1e-3 +RUNS = dict(discount_rate=RATE, value_rate=1.0, mc_samples=200, seed=5) + +PLAIN = UnitPlan( + W, + REPAIR, + tasks=(AgePolicy(interval=250.0, cost=2.0, duration=REPAIR),), + prices=Prices(repair=5.0, downtime=1.0, acquisition=20.0), +) + + +def with_money(**money) -> UnitPlan: + from dataclasses import replace + + return replace(PLAIN, **money) + + +def test_a_salvage_is_credited_to_every_run_at_the_end(): + plan = with_money(salvage=70.0) + runs = plan.npv_distribution(HORIZON, **RUNS) + plain = PLAIN.npv_distribution(HORIZON, **RUNS) + worth = 70.0 * math.exp(-RATE * HORIZON) + assert runs.salvage == pytest.approx(worth, rel=1e-15) + assert runs.undiscounted_salvage == 70.0 + assert runs.retire_at is None + np.testing.assert_allclose( + runs.samples, plain.samples + worth, rtol=0, atol=1e-9 + ) + assert runs.undiscounted_npv == pytest.approx( + plain.undiscounted_npv + 70.0, rel=1e-13 + ) + # The same credit expected_npv gives. + exact = plan.expected_npv(HORIZON, discount_rate=RATE, value_rate=1.0) + assert runs.salvage == pytest.approx(exact.salvage, rel=1e-12) + + +def test_a_retirement_ends_the_runs_there(): + plan = with_money(retire_at=240.0, salvage=30.0, escalation=2e-4) + runs = plan.npv_distribution(HORIZON, **RUNS) + to_then = PLAIN.npv_distribution( + 240.0, escalation={UnitPlan.NODE: 2e-4}, **RUNS + ) + # The salvage grows with the "salvage" stream alone, as expected_npv + # credits it (the unit's own escalation is its costs'). + worth = 30.0 * math.exp(-RATE * 240.0) + assert runs.retire_at == 240.0 and runs.horizon == 240.0 + assert runs.salvage == pytest.approx(worth, rel=1e-15) + exact = plan.expected_npv(HORIZON, discount_rate=RATE, value_rate=1.0) + assert runs.salvage == pytest.approx(exact.salvage, rel=1e-12) + np.testing.assert_allclose( + runs.samples, to_then.samples + worth, rtol=0, atol=1e-9 + ) + + +def test_compare_npv_credits_each_plan_its_own(): + salvaged = with_money(salvage=70.0) + rbd = salvaged.diagram() + other = PLAIN.diagram() + compared = rbd.compare_npv(other, HORIZON, **RUNS) + worth = 70.0 * math.exp(-RATE * HORIZON) + # The runs are matched, so each run differs by the salvage alone. + np.testing.assert_allclose(compared.differences, worth, atol=1e-9) + assert compared.this.salvage == pytest.approx(worth, rel=1e-15) + assert compared.other.salvage == 0.0 + + +def test_what_runs_still_refuse_says_what_to_give(): + by_age = with_money(salvage=lambda age: 100.0 - age / 10.0) + with pytest.raises(NotImplementedError, match="salvage by age"): + by_age.diagram().npv_distribution(HORIZON, **RUNS) + route = by_age.diagram().analysis_routes()["npv_distribution"] + assert route.route == routes.REFUSED + assert "salvage by age" in route.reason + # One unit of several retiring is not built (expected_npv's refusal). + other = {"reliability": W, "repairability": REPAIR, "repair_cost": 3.0} + several = RepairableRBD( + [("s", "a"), ("a", "b"), ("b", "t")], + {"a": with_money(retire_at=100.0), "b": other}, + ) + with pytest.raises(NotImplementedError, match="retiring one unit"): + several.npv_distribution(HORIZON, **RUNS) + 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_npv_shutdowns.py b/repyability/tests/test_npv_shutdowns.py new file mode 100644 index 00000000..cd313822 --- /dev/null +++ b/repyability/tests/test_npv_shutdowns.py @@ -0,0 +1,240 @@ +"""The net present value of each simulated run of a diagram with +shutdowns (``npv_distribution``, ``compare_npv``): each shut's cost at +its starts, a hold not charged as a task, and what a hold hides (a +failure in the shut, a renewal made in it) charged all the same. Each run +at no discounting against the simulation's own cost and uptime, the mean +against the exact ``expected_npv``, and the shuts' costs against their +calendar.""" + +import math + +import numpy as np +import pytest +import surpyval as surv + +from repyability import RepairableRBD +from repyability.rbd import _timeline_runs, routes +from repyability.tests.test_outage_opportunistic import line +from repyability.tests.test_shutdowns import one, outages, shut + +E = surv.Exponential.from_params +W = surv.Weibull.from_params + + +def opportunistic(): + """Outages that hold a and b for 150 and cost 40, renewing a if it is + 500 old: failures in the shuts and renewals made in them, hidden.""" + return line({"a": 500.0}, duration=150.0, cost=40.0) + + +def moment(): + """A shut in no time that costs 5 at each start, every 100.""" + return one( + {"repair_cost": 2.0}, + shutdown={"period": 100.0, "duration": 0.0, "cost": 5.0}, + ) + + +def held_unworked(): + """A pump under its own age replacement, held by shuts that do no + work on it: its holds are no tasks.""" + return one( + { + "reliability": W([150.0, 2.0]), + "repair_cost": 20.0, + "preventive": { + "policy": "age", + "interval": 80.0, + "duration": W([2.0, 2.0]), + "cost": 7.0, + }, + }, + shutdown=shut(cost=3.0), + ) + + +CASES = { + "outages at given times": (outages, 800.0), + "opportunistic renewals in long shuts": (opportunistic, 3000.0), + "a shut in no time": (moment, 1000.0), + "holds of a part with its own tasks": (held_unworked, 1000.0), +} + + +@pytest.mark.parametrize("case", CASES) +def test_undiscounted_each_run_is_its_value_less_its_simulated_cost(case): + make, horizon = CASES[case] + rbd, value, n = make(), 2.0, 300 + runs = rbd.npv_distribution( + horizon, value_rate=value, mc_samples=n, seed=5 + ) + cost = rbd.cost(horizon, mc_samples=n, seed=5, control_variate=False) + uptime = rbd.simulate_timelines(horizon, mc_samples=n, seed=5).system + expected = value * uptime.uptime - cost.samples - cost.acquisition_cost + assert np.allclose(runs.samples, expected, rtol=1e-10, atol=1e-8) + for category, amount in cost.by_category.items(): + assert runs.cost_by_category.get(category, 0.0) == pytest.approx( + amount, rel=1e-10, abs=1e-9 + ), category + + +@pytest.mark.parametrize( + "case", + [ + "outages at given times", + "opportunistic renewals in long shuts", + "holds of a part with its own tasks", + ], +) +def test_the_histories_mark_holds_and_what_they_hid(case): + # The cases above are not priced right by the recorded changes alone. + make, horizon = CASES[case] + rbd = make() + _, hidden = _timeline_runs.simulate( + rbd, + horizon, + 300, + 5, + None, + None, + False, + "auto", + None, + 0, + None, + hidden=True, + ) + assert sum(int(h.held.sum()) for h in hidden.values()) > 0 + if case != "holds of a part with its own tasks": + assert sum(h.times.size for h in hidden.values()) > 0 + + +def test_a_shut_in_no_time_is_charged_at_each_start(): + rbd, horizon = moment(), 1000.0 + cost = rbd.cost(horizon, mc_samples=20, seed=1, control_variate=False) + assert cost.by_category["shutdown"] == 45.0 + assert rbd.expected_cost(horizon).by_category["shutdown"] == 45.0 + + +@pytest.mark.parametrize( + "make, horizon", + [ + (outages, 800.0), + ( + lambda: one( + { + "repair_cost": 2.0, + "preventive": {"shutdown": "line", "cost": 4.0}, + }, + shutdown=shut(cost=5.0), + ), + 1000.0, + ), + ], +) +def test_the_mean_is_the_expected_npv(make, horizon): + rbd, rate, value = make(), 1e-3, 3.0 + runs = rbd.npv_distribution( + horizon, discount_rate=rate, value_rate=value, mc_samples=4000, seed=3 + ) + exact = rbd.expected_npv(horizon, discount_rate=rate, value_rate=value) + interval = runs.mean_interval(0.9999) + assert interval.lower < exact.npv < interval.upper + # Each shut's cost, the same in every run, discounted at its starts. + starts = [ + start + for spec in rbd._shutdowns.values() + for start in spec.starts(horizon) + for _ in range(1 if spec.cost else 0) + ] + costs = [ + spec.cost + for spec in rbd._shutdowns.values() + for _ in spec.starts(horizon) + if spec.cost + ] + shut_cost = sum(c * math.exp(-rate * t) for c, t in zip(costs, starts)) + assert runs.cost_by_category["shutdown"] == pytest.approx( + shut_cost, rel=1e-12 + ) + assert exact.cost_by_category["shutdown"] == pytest.approx( + shut_cost, rel=1e-6 + ) + for category, amount in exact.cost_by_category.items(): + assert runs.cost_by_category.get(category, 0.0) == pytest.approx( + amount, rel=0.1, abs=1e-9 + ), category + + +def test_two_plans_with_shutdowns_are_compared_run_for_run(): + rbd = opportunistic() + assert rbd.analysis_routes()["npv_distribution"].route == ( + routes.SIMULATED + ) + assert rbd.analysis_routes()["compare_npv"].route == routes.SIMULATED + same = rbd.compare_npv( + opportunistic(), 3000.0, discount_rate=1e-3, mc_samples=100, seed=2 + ) + assert np.array_equal(same.differences, np.zeros(100)) + # Renewing at an outage only if older than never happens: the plan + # without the rule, which saves less than the rule's plan. + never = line({"a": math.inf}, duration=150.0, cost=40.0) + gain = rbd.compare_npv( + never, 3000.0, discount_rate=1e-3, mc_samples=400, seed=2 + ) + assert gain.interval.standard_error < gain.independent_standard_error + assert gain.this.cost_by_category["shutdown"] == pytest.approx( + gain.other.cost_by_category["shutdown"], rel=1e-15 + ) + + +def test_a_paused_part_held_in_a_shut_is_priced(): + # outages() stands c still in its own shut: its runs priced as above + # and its own task's cost charged once per shut. + rbd = outages() + runs = rbd.npv_distribution(800.0, mc_samples=200, seed=9) + assert runs.cost_by_component["c"] > 0.0 + cost = rbd.cost(800.0, mc_samples=200, seed=9, control_variate=False) + assert runs.cost_by_component["c"] == pytest.approx( + cost.by_component["c"], rel=1e-10 + ) + + +def test_shuts_are_simulated_in_python(): + # The compiled engine does not simulate shutdowns: asked for, it + # refuses, naming the engines that do, and "auto" runs the Python + # loop. (Shuts that take no time, priced at each shut; an instant + # renewal at them leaves no outage in the histories, so it is not + # priced.) + pytest.importorskip("numba") + rbd = one( + {"repair_cost": 2.0, "preventive": {"shutdown": "line"}}, + shutdown={ + "period": 100.0, + "offset": 20.0, + "duration": 0.0, + "cost": 4.0, + }, + ) + python = rbd.npv_distribution( + 1000.0, mc_samples=50, seed=1, engine="python" + ) + auto = rbd.npv_distribution(1000.0, mc_samples=50, seed=1, engine="auto") + assert auto.engine == "python" + assert np.array_equal(python.samples, auto.samples) + with pytest.raises( + NotImplementedError, match="does not simulate shutdowns" + ): + rbd.npv_distribution(1000.0, mc_samples=50, seed=1, engine="numba") + + +def test_a_diagram_whose_only_costs_are_its_shuts(): + # A diagram with shutdowns and no costs at all but its shuts' is + # priced: the shuts alone. + rbd = RepairableRBD( + [("s", "a"), ("a", "t")], + {"a": {"reliability": E([1e-3]), "repairability": E([0.5])}}, + shutdowns={"x": {"times": [10.0, 20.0], "duration": 1.0, "cost": 4.0}}, + ) + runs = rbd.npv_distribution(100.0, mc_samples=5, seed=1) + assert np.array_equal(runs.samples, np.full(5, -8.0)) diff --git a/repyability/tests/test_npv_uncertainty.py b/repyability/tests/test_npv_uncertainty.py new file mode 100644 index 00000000..057d66d0 --- /dev/null +++ b/repyability/tests/test_npv_uncertainty.py @@ -0,0 +1,334 @@ +"""How sure an NPV is: its derivative in the discount rate +(``expected_npv(rate_sensitivity=True)``), its spread over plausible +models of the components (``expected_npv_uncertainty``), and how robust a +choice of replacement intervals is to them +(``optimal_replacement_intervals(robust=...)``).""" + +import json +import math + +import numpy as np +import pytest +import surpyval as surv +from scipy import integrate + +from repyability import NPVUncertainty, PlanRobustness, RepairableRBD +from repyability.rbd import _repairable_uncertainty + +E, W = surv.Exponential.from_params, surv.Weibull.from_params + +LAMBDA, MU, PRICE, VALUE = 1e-3, 0.1, 500.0, 10.0 +HORIZON = 5 * 8760.0 +RATE = math.log(1.08) / 8760 + + +def pump(life=None): + return RepairableRBD( + [("s", "p"), ("p", "t")], + { + "p": { + "reliability": E([LAMBDA]) if life is None else life, + "repairability": E([MU]), + "repair_cost": PRICE, + "acquisition_cost": 20000.0, + } + }, + ) + + +def availability(t, lam=LAMBDA): + """An exponential unit's point availability, from new.""" + return MU / (lam + MU) + lam / (lam + MU) * math.exp(-(lam + MU) * t) + + +def closed_npv(rate, lam=LAMBDA, horizon=HORIZON): + """The pump's NPV: value while up, less a repair at each failure (at + the rate ``lam A(t)``), less the price paid at 0.""" + net = VALUE - PRICE * lam + return ( + integrate.quad( + lambda t: math.exp(-rate * t) * availability(t, lam) * net, + 0.0, + horizon, + limit=200, + epsabs=1e-9, + epsrel=1e-12, + )[0] + - 20000.0 + ) + + +def closed_slope(rate): + """``d npv / d r`` of ``closed_npv``: each amount at ``t`` weighed + by ``-t``.""" + net = VALUE - PRICE * LAMBDA + return integrate.quad( + lambda t: -t * math.exp(-rate * t) * availability(t) * net, + 0.0, + HORIZON, + limit=200, + epsabs=1e-6, + epsrel=1e-12, + )[0] + + +@pytest.mark.parametrize("rate", [RATE, 0.0, 1e-9]) +def test_the_rate_sensitivity_is_the_closed_form_s(rate): + # At 0 and just above it the differences are one-sided. + result = pump().expected_npv( + HORIZON, discount_rate=rate, value_rate=VALUE, rate_sensitivity=True + ) + exact = closed_slope(rate) + assert result.rate_sensitivity == pytest.approx(exact, rel=1e-6) + # The error it states bounds the one it makes. + assert ( + abs(result.rate_sensitivity - exact) <= result.rate_sensitivity_error + ) + assert result.rate_sensitivity_error < 1e-4 * abs(exact) + + +def test_the_rate_sensitivity_predicts_a_change_of_rate(): + rbd = pump() + base = rbd.expected_npv( + HORIZON, discount_rate=RATE, value_rate=VALUE, rate_sensitivity=True + ) + step = 1e-4 / HORIZON + moved = rbd.expected_npv( + HORIZON, discount_rate=RATE + step, value_rate=VALUE + ) + assert moved.npv - base.npv == pytest.approx( + base.rate_sensitivity * step, rel=1e-3 + ) + + +def test_the_rate_sensitivity_covers_a_retirement_and_a_salvage(): + # The salvage is discounted from the retirement: its part of the + # derivative is -stop * exp(-r stop) * salvage. + rbd = pump() + kwargs = dict(discount_rate=RATE, value_rate=VALUE, retire_at=20000.0) + plain = rbd.expected_npv(HORIZON, rate_sensitivity=True, **kwargs) + sold = rbd.expected_npv( + HORIZON, salvage=8000.0, rate_sensitivity=True, **kwargs + ) + assert sold.rate_sensitivity - plain.rate_sensitivity == pytest.approx( + -20000.0 * math.exp(-RATE * 20000.0) * 8000.0, rel=1e-5 + ) + + +def test_without_asking_there_is_no_rate_sensitivity(): + result = pump().expected_npv(HORIZON, discount_rate=RATE, value_rate=1.0) + assert result.rate_sensitivity is None + assert result.rate_sensitivity_error is None + with pytest.raises(TypeError, match="rate_sensitivity"): + pump().expected_npv(HORIZON, value_rate=1.0, rate_sensitivity="yes") + + +# An exponential life fitted to 40 failures: its rate's variance is +# lambda^2 / 40. +FAILURES = np.random.default_rng(0).exponential(1.0 / LAMBDA, 40) + + +@pytest.fixture(scope="module") +def fitted(): + return pump(surv.Exponential.fit(FAILURES)) + + +@pytest.fixture(scope="module") +def spread(fitted): + return fitted.expected_npv_uncertainty( + HORIZON, + discount_rate=RATE, + value_rate=VALUE, + n_draws=400, + seed=3, + ) + + +def test_the_delta_method_is_the_closed_form_s(fitted, spread): + lam = float(fitted.components["p"].reliability.params[0]) + variance = lam**2 / len(FAILURES) + h = 1e-3 * lam + slope = (closed_npv(RATE, lam + h) - closed_npv(RATE, lam - h)) / (2 * h) + covariance = np.asarray(fitted.components["p"].reliability.hess_inv, float) + assert covariance[0, 0] == pytest.approx(variance, rel=1e-3) + assert spread.delta_variance == pytest.approx( + slope**2 * covariance[0, 0], rel=1e-3 + ) + assert spread.variance_shares == {"p": pytest.approx(1.0)} + + +def test_the_spread_of_the_draws_is_the_delta_method_s(spread): + # The NPV is nearly linear in the rate over its spread (a few per cent + # of it): the draws' variance is the delta method's, to the error of a + # variance from 400 draws (about 7%). + assert spread.std**2 == pytest.approx(spread.delta_variance, rel=0.25) + lower, upper = spread.interval(0.9) + half = 1.6449 * math.sqrt(spread.delta_variance) + assert lower == pytest.approx(spread.nominal - half, abs=0.3 * half) + assert upper == pytest.approx(spread.nominal + half, abs=0.3 * half) + + +def test_each_draw_is_the_npv_of_its_models(fitted, spread): + inputs, groups = _repairable_uncertainty.sources(fitted, None) + models, group_models = _repairable_uncertainty.draws( + fitted, inputs, groups, 400, 3 + ) + for i in (0, 199, 399): + lam = float(models[0]["reliability"][i].params[0]) + assert spread.samples[i] == pytest.approx( + closed_npv(RATE, lam), rel=1e-7 + ) + + +def test_the_spread_says_what_it_held_and_goes_through_json(spread): + assert isinstance(spread, NPVUncertainty) + assert spread.band == "confidence" + assert spread.held_fixed == [{"node": "p", "role": "repairability"}] + out = json.loads(json.dumps(spread.to_dict())) + assert len(out["samples"]) == 400 + assert out["held_fixed"] == [{"node": "p", "role": "repairability"}] + assert out["variance_shares"] == {"p": pytest.approx(1.0)} + assert out["horizon"] == HORIZON + assert "NPVUncertainty(nominal=" in repr(spread) + + +def test_a_seed_gives_the_same_draws(fitted): + def run(): + return fitted.expected_npv_uncertainty( + HORIZON, value_rate=VALUE, n_draws=5, seed=11, shares=False + ) + + first, second = run(), run() + np.testing.assert_array_equal(first.samples, second.samples) + assert first.variance_shares == {} + assert first.delta_variance is None + + +def test_two_inputs_share_the_variance(): + life = surv.Exponential.fit(FAILURES) + repairs = np.random.default_rng(1).exponential(1.0 / MU, 15) + rbd = pump(life) + rbd = RepairableRBD( + [("s", "p"), ("p", "t")], + { + "p": { + "reliability": life, + "repairability": surv.Exponential.fit(repairs), + "repair_cost": PRICE, + } + }, + ) + result = rbd.expected_npv_uncertainty( + HORIZON, + {"p": "fit"}, + discount_rate=RATE, + value_rate=VALUE, + n_draws=3, + seed=0, + ) + assert sum(result.variance_shares.values()) == pytest.approx(1.0) + assert result.held_fixed == [] + + +# A unit replaced at an age: 1000 costs it nothing extra under the model +# as given, but under a shorter-lived model, 750 is better. +ALLOWED = [500.0, 750.0, 1000.0, 1500.0] +LONG, SHORT = W([1500.0, 3.0]), W([900.0, 3.0]) + + +def replaced(life): + return RepairableRBD( + [("s", "u"), ("u", "t")], + { + "u": { + "reliability": life, + "repairability": E([0.1]), + "replace_cost": 5000.0, + "preventive": { + "interval": 1000.0, + "duration": E([0.5]), + "cost": 1000.0, + }, + } + }, + downtime_cost_rate=50.0, + ) + + +def test_the_choice_flips_in_the_draws_whose_model_says_so(): + rbd = replaced(LONG) + own = rbd.optimal_replacement_intervals(allowed=ALLOWED) + short = replaced(SHORT).optimal_replacement_intervals(allowed=ALLOWED) + # The two models choose differently, one step apart. + i = ALLOWED.index(own.intervals["u"]) + assert abs(ALLOWED.index(short.intervals["u"]) - i) == 1 + uncertainty = {"u": {"reliability": [LONG, SHORT]}} + plan = rbd.optimal_replacement_intervals( + allowed=ALLOWED, + robust=True, + uncertainty=uncertainty, + n_draws=60, + seed=5, + ) + robustness = plan.robustness + assert isinstance(robustness, PlanRobustness) + assert plan.intervals == own.intervals + inputs, groups = _repairable_uncertainty.sources(rbd, uncertainty) + models, _ = _repairable_uncertainty.draws(rbd, inputs, groups, 60, 5) + drew_short = np.array([m is SHORT for m in models[0]["reliability"]]) + assert 0 < drew_short.sum() < 60 + # The choice is the best exactly where the long life was drawn. + assert robustness.share_best == pytest.approx(1.0 - drew_short.mean()) + # And loses, where it was not, what the short life's own choice + # saves on its cost rate. + flipped = replaced(SHORT) + loss = flipped.with_intervals(own).expected_cost_rate() - ( + flipped.with_intervals(short).expected_cost_rate() + ) + assert loss > 0.0 + np.testing.assert_allclose(robustness.regret[~drew_short], 0.0, atol=0) + np.testing.assert_allclose(robustness.regret[drew_short], loss, rtol=1e-9) + assert robustness.expected_regret == pytest.approx( + loss * drew_short.mean(), rel=1e-9 + ) + assert robustness.held_fixed == [ + {"node": "u", "role": "repairability"}, + {"node": "u", "role": "preventive.duration"}, + ] + # Each draw's own choice, chosen again, agrees. + again = rbd.optimal_replacement_intervals( + allowed=ALLOWED, + robust="reoptimise", + uncertainty=uncertainty, + n_draws=60, + seed=5, + ).robustness + assert again.share_best == robustness.share_best + np.testing.assert_allclose(again.regret, robustness.regret, rtol=1e-12) + out = json.loads(json.dumps(plan.to_dict())) + assert out["robustness"]["share_best"] == robustness.share_best + assert len(out["robustness"]["candidates"]) == 3 + + +def test_a_continuous_choice_is_compared_with_its_neighbours(): + rbd = replaced(LONG) + plan = rbd.optimal_replacement_intervals( + robust=True, + uncertainty={"u": {"reliability": [LONG]}}, + n_draws=4, + seed=0, + ) + robustness = plan.robustness + best = plan.intervals["u"] + assert [c["u"] for c in robustness.candidates] == pytest.approx( + [best, best / 1.25, best * 1.25] + ) + # Every draw is the fitted model: the choice is the best in each. + assert robustness.share_best == 1.0 + assert robustness.share_best_by_candidate == [1.0, 0.0, 0.0] + assert robustness.expected_regret == 0.0 + + +def test_robust_is_checked(): + with pytest.raises(ValueError, match="robust must be"): + replaced(LONG).optimal_replacement_intervals(robust="yes") diff --git a/repyability/tests/test_npv_value_runs.py b/repyability/tests/test_npv_value_runs.py new file mode 100644 index 00000000..5be83586 --- /dev/null +++ b/repyability/tests/test_npv_value_runs.py @@ -0,0 +1,298 @@ +"""A value schedule and escalation in the simulated NPV +(``npv_distribution``, ``compare_npv``, ``best_switch_time``) and in +``plan_vs_actual``: each run priced against a reference written here from +its history, the runs' mean against ``expected_npv`` with the same +arguments, the real/nominal identity, and a plan against what happened +adding up (and averaging to the plan, the tower property).""" + +import json +import math +import warnings + +import numpy as np +import pytest +import surpyval as surv + +from repyability import RepairableRBD, Timeline, ValueSchedule, value_plan +from repyability.tests.test_npv_distribution import age_replaced, pump + +E = surv.Exponential.from_params +W = surv.Weibull.from_params +LINE = [("s", "p"), ("p", "t")] +H, R = 400.0, 2e-3 +SCHEDULE = ValueSchedule([0.0, 150.0], [3.0, 5.0]) +GROWTH = {"value": 1e-3, "repair": 3e-3, "system_downtime": -1e-3} + + +def span(a, b, r): + """The integral of exp(-r t) from a to b.""" + if r == 0.0: + return b - a + return (math.exp(-r * a) - math.exp(-r * b)) / r + + +def by_hand(timeline, steps, rate, growth): + """A history's value earned, written out: each up span, cut at each + step, at the step's rate grown at ``growth`` and discounted.""" + times = [0.0] + list(timeline.changes) + [timeline.end] + up = timeline.up + total = 0.0 + for a, b in zip(times[:-1], times[1:]): + if up: + for lo, hi, worth in steps: + x, y = max(a, lo), min(b, hi) + if y > x: + total += worth * span(x, y, rate - growth) + up = not up + return total + + +def test_each_run_is_priced_as_written_out(): + rbd = pump() + n = 40 + runs = rbd.npv_distribution( + H, + discount_rate=R, + value_rate=SCHEDULE, + escalation=GROWTH, + mc_samples=n, + seed=2, + ) + sim = rbd.simulate_timelines(H, mc_samples=n, seed=2) + steps = [(0.0, 150.0, 3.0), (150.0, H, 5.0)] + for i in range(n): + value = by_hand(sim.system[i], steps, R, GROWTH["value"]) + pump_log = sim.components["p"][i] + failures = pump_log.changes[0::2] # it starts up + cost = 2000.0 + sum( + 500.0 * math.exp(-(R - GROWTH["repair"]) * t) for t in failures + ) + assert runs.value_samples[i] == pytest.approx(value, rel=1e-12) + assert runs.cost_samples[i] == pytest.approx(cost, rel=1e-12) + assert math.isnan(runs.value_rate) + assert runs.value_schedule == SCHEDULE + assert runs.escalation == GROWTH and runs.rate_basis == "nominal" + + +@pytest.mark.parametrize("make", [pump, age_replaced]) +def test_the_mean_is_the_expected_npv_with_the_same_arguments(make): + rbd = make() + kwargs = dict(discount_rate=R, value_rate=SCHEDULE, escalation=GROWTH) + runs = rbd.npv_distribution(H, mc_samples=4000, seed=3, **kwargs) + exact = rbd.expected_npv(H, **kwargs) + interval = runs.mean_interval(0.9999) + assert interval.lower < exact.npv < interval.upper + for category, amount in exact.cost_by_category.items(): + assert runs.cost_by_category.get(category, 0.0) == pytest.approx( + amount, rel=0.1, abs=1e-9 + ), category + + +def test_one_step_and_no_growth_are_the_rate_alone(): + rbd = age_replaced() + plain = rbd.npv_distribution( + H, discount_rate=R, value_rate=3.0, mc_samples=50, seed=1 + ) + stepped = rbd.npv_distribution( + H, + discount_rate=R, + value_rate=ValueSchedule([0.0], [3.0]), + escalation={}, + mc_samples=50, + seed=1, + ) + np.testing.assert_array_equal(plain.samples, stepped.samples) + + +def test_inflation_leaves_the_present_values_and_lifts_the_rest(): + rbd = age_replaced() + kwargs = dict( + discount_rate=R, + value_rate=SCHEDULE, + escalation=GROWTH, + rates="real", + mc_samples=50, + seed=1, + ) + real = rbd.npv_distribution(H, **kwargs) + lifted = rbd.npv_distribution(H, inflation=1e-3, **kwargs) + np.testing.assert_allclose(lifted.samples, real.samples, rtol=1e-12) + assert lifted.undiscounted_cost > real.undiscounted_cost + assert lifted.inflation == 1e-3 and lifted.rate_basis == "real" + # No discounting and no growth: the undiscounted value is the + # present one. + flat = rbd.npv_distribution(H, value_rate=SCHEDULE, mc_samples=50, seed=1) + assert flat.undiscounted_npv == pytest.approx(flat.mean, rel=1e-12) + + +def test_two_plans_take_one_escalation(): + # The escalation names a component only the other plan has. + one = pump() + two = RepairableRBD( + [("s", "p"), ("p", "q"), ("q", "t")], + { + "p": dict(one._init_args["components"]["p"]), + "q": { + "reliability": E([1e-4]), + "repairability": E([0.1]), + "repair_cost": 50.0, + }, + }, + ) + kwargs = dict( + discount_rate=R, + value_rate=SCHEDULE, + escalation={"q": 1e-3, "value": 1e-3}, + mc_samples=200, + seed=4, + ) + gain = one.compare_npv(two, H, **kwargs) + assert gain.this.escalation == {"value": 1e-3} + assert gain.other.escalation == {"q": 1e-3, "value": 1e-3} + # One that names a component of neither plan is refused. + with pytest.raises(ValueError, match="'q', which is no component"): + one.compare_npv(pump(), H, **kwargs) + same = one.compare_npv( + pump(), H, **{**kwargs, "escalation": {"value": 1e-3}} + ) + np.testing.assert_array_equal(same.differences, np.zeros(200)) + + +def pumped(): + """A pump that all but never fails: its plan's rest is its rest.""" + return RepairableRBD( + LINE, + { + "p": { + "reliability": E([1e-9]), + "repairability": E([0.1]), + "repair_cost": 500.0, + } + }, + downtime_cost_rate=10.0, + ) + + +def test_the_rest_from_now_is_grown_and_discounted_to_the_start(): + rbd, now = pumped(), 100.0 + kwargs = dict(discount_rate=R, value_rate=SCHEDULE, escalation=GROWTH) + result = rbd.plan_vs_actual( + {"p": Timeline([], end=now)}, now, H, periods=[now, H], **kwargs + ) + assert ( + result.plan.npv == rbd.expected_npv(H, periods=[now, H], **kwargs).npv + ) + # The rest is valued with the step at 150 at 50 on its own clock. + assert result.rest.value_schedule == ValueSchedule([0.0, 50.0], [3.0, 5.0]) + # Up throughout: the value from now is the plan's after now. (Its + # downtime is not: known up now, the rest starts with none.) + assert result.rest_npv == pytest.approx(result.plan_rest_npv, rel=1e-6) + by_row = {(r["period"], r["category"]): r for r in result.plan.cash_flows} + for row in result.rest_cash_flows: + if row["category"] != "value": + continue + planned = by_row[(row["period"], row["category"])] + assert row["present_value"] == pytest.approx( + planned["present_value"], rel=1e-6, abs=1e-9 + ) + assert row["undiscounted"] == pytest.approx( + planned["undiscounted"], rel=1e-6, abs=1e-9 + ) + assert result.revalued_npv == pytest.approx( + result.actual_so_far + result.as_planned_so_far + result.rest_npv, + rel=1e-12, + ) + value = by_hand( + Timeline([], end=now), [(0.0, 150.0, 3.0)], R, GROWTH["value"] + ) + assert result.actual_so_far == pytest.approx(value, rel=1e-12) + + +def test_so_far_and_the_rest_average_to_the_plan(): + # The tower property, with a schedule stepping inside the rest and + # growing streams: what each history yielded plus the rest valued from + # its state now averages to the plan's value. + rbd, now, n = age_replaced(), 150.0, 60 + kwargs = dict( + discount_rate=R, + value_rate=ValueSchedule([0.0, 200.0], [3.0, 5.0]), + escalation=GROWTH, + ) + plan = rbd.expected_npv(300.0, periods=[now, 300.0], **kwargs) + sim = rbd.simulate_timelines(now, mc_samples=n, seed=11) + whole = np.zeros(n) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + for i in range(n): + logs = {node: sim.components[node][i] for node in rbd.components} + whole[i] = rbd.plan_vs_actual( + logs, now, 300.0, periods=[now, 300.0], **kwargs + ).revalued_npv + se = whole.std(ddof=1) / math.sqrt(n) + assert abs(whole.mean() - plan.npv) < 4.0 * se + + +def test_the_best_switch_time_takes_the_basis(): + 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 + rbd = RepairableRBD( + LINE, + { + "p": { + "reliability": surv.WeibullPH.fit(x, Z=load[:, None]), + "repairability": E([0.5]), + "repair_cost": 5.0, + "covariates": surv.StepSchedule.from_changepoints( + [0.0], [[1.0]] + ), + } + }, + ) + kwargs = dict( + discount_rate=R, + mc_samples=50, + seed=1, + scan=3, + escalation={"value": 1e-3}, + rates="real", + ) + real = rbd.best_switch_time( + {"p": [[1.5], [1.0]]}, [1.5, 1.0], 100.0, **kwargs + ) + lifted = rbd.best_switch_time( + {"p": [[1.5], [1.0]]}, [1.5, 1.0], 100.0, inflation=1e-3, **kwargs + ) + np.testing.assert_allclose(lifted.npvs, real.npvs, rtol=1e-12) + assert lifted.escalation == {"value": 1e-3} + assert lifted.inflation == 1e-3 and lifted.rate_basis == "real" + + +def test_it_is_asked_and_answered_as_json(): + rbd = age_replaced() + answer = value_plan( + { + "schema": 1, + "diagram": rbd.to_dict(), + "analysis": "npv_distribution", + "inputs": { + "horizon": H, + "discount_rate": R, + "value_rate": SCHEDULE.to_dict(), + "escalation": GROWTH, + "mc_samples": 20, + "seed": 1, + }, + } + ) + direct = rbd.npv_distribution( + H, + discount_rate=R, + value_rate=SCHEDULE, + escalation=GROWTH, + mc_samples=20, + seed=1, + ) + assert answer["result"]["mean"] == direct.mean + assert answer["result"]["value_schedule"] == SCHEDULE.to_dict() + json.dumps(answer, allow_nan=False) diff --git a/repyability/tests/test_one_eac.py b/repyability/tests/test_one_eac.py new file mode 100644 index 00000000..e58e9303 --- /dev/null +++ b/repyability/tests/test_one_eac.py @@ -0,0 +1,88 @@ +"""One definition of the equivalent annual cost of age replacement +(``maintenance._options.cycle_eac``), which a part alone +(``NonRepairable``) and a diagram's component (``node_eac``) both take, +against Fox's closed form for an exponential life.""" + +import math + +import pytest +import surpyval as surv + +from repyability import NonRepairable, RepairableRBD +from repyability.maintenance._options import ( + cycle_eac, + discounted_optimum, + discounted_run_to_failure, +) +from repyability.rbd._discounted_long_run import node_eac + +LAMBDA, RATE, AGE = 1e-3, 2e-4, 700.0 +CP, CU = 30.0, 200.0 +E = surv.Exponential.from_params([LAMBDA]) + + +def fox(age: float) -> float: + """``(cu l M + cp exp(-(l + r) T)) / M``, ``M = (1 - exp(-(l + r) T)) + / (l + r)``: an exponential life replaced at ``T``, discounted.""" + both = LAMBDA + RATE + kept = math.exp(-both * age) + length = (1.0 - kept) / both + return (CU * LAMBDA * length + CP * kept) / length + + +def test_the_one_eac_is_fox_s(): + part = NonRepairable(E) + assert cycle_eac( + part, AGE, RATE, failure_cost=CU, planned_cost=CP + ) == pytest.approx(fox(AGE), rel=1e-9) + + +def test_a_part_alone_and_a_component_take_the_one_eac(): + rbd = RepairableRBD( + [("s", "u"), ("u", "t")], + { + "u": { + "reliability": E, + "repairability": "instant", + "repair_cost": CU, + "preventive": {"interval": AGE, "cost": CP}, + } + }, + ) + part = rbd.components["u"] + assert node_eac(rbd, "u", RATE) == cycle_eac( + part, AGE, RATE, failure_cost=CU, planned_cost=CP + ) + best, eac = discounted_optimum(part, RATE, CP, CU) + if math.isinf(best): + assert eac == discounted_run_to_failure(part, RATE, CU) + else: + assert eac == pytest.approx( + cycle_eac(part, best, RATE, failure_cost=CU, planned_cost=CP), + rel=1e-12, + ) + assert discounted_run_to_failure(part, RATE, CU) == cycle_eac( + part, math.inf, RATE, failure_cost=CU + ) + + +def test_downtime_and_work_that_takes_time_lengthen_the_cycle(): + part = NonRepairable(E) + down, repair, planned = 5.0, 12.0, 4.0 + both = LAMBDA + RATE + kept = math.exp(-both * AGE) + length = (1.0 - kept) / both + failed = LAMBDA * length + expected = ( + failed * (CU + down * repair) + kept * (CP + down * planned) + ) / (length + failed * repair + kept * planned) + assert cycle_eac( + part, + AGE, + RATE, + failure_cost=CU, + planned_cost=CP, + downtime=down, + repair=repair, + planned=planned, + ) == pytest.approx(expected, rel=1e-9) diff --git a/repyability/tests/test_opportunistic_maintenance.py b/repyability/tests/test_opportunistic_maintenance.py index a813ca78..764d6f2b 100644 --- a/repyability/tests/test_opportunistic_maintenance.py +++ b/repyability/tests/test_opportunistic_maintenance.py @@ -124,6 +124,8 @@ def test_a_timeline_worked_by_hand(): "system_downtime": 0.0, "setup": 2500.0, "shutdown": 0.0, + "crews": 0.0, + "capital": 0.0, } used = rbd.spares_demand(200.0, method="simulate", mc_samples=2, seed=1) assert used["b"].probabilities[5] == 1.0 diff --git a/repyability/tests/test_opportunities.py b/repyability/tests/test_opportunities.py new file mode 100644 index 00000000..acdb40a2 --- /dev/null +++ b/repyability/tests/test_opportunities.py @@ -0,0 +1,695 @@ +"""Opportunities with the prices on the part (UC-45 of +``repyability/maintenance/README.md``): ``Opportunity`` and +``Opportunities`` in model time and on real dates, each part's prices +(``opportunity_cost``, ``opportunity_costs``, ``job_duration``), the +helper that works prices out from a replacement's cost and downtime, and +the deprecated 0.14 and 0.19 forms giving the same numbers.""" + +import json +import math +import warnings + +import numpy as np +import pytest +import surpyval as surv + +from repyability import ( + RBD, + Calendar, + NonRepairable, + Opportunities, + Opportunity, + OpportunityPrices, + RepairableRBD, + Shutdown, + Shutdowns, + __version__, +) +from repyability.schedule import Recurrence, Usage +from repyability.utils.deprecation import NEXT_REMOVAL + +LIFE = surv.Weibull.from_params([1000.0, 2.5]) +NOW = "2026-11-16" + + +def old(make): + """``make()``, with the deprecated forms' warnings silenced.""" + with warnings.catch_warnings(): + warnings.simplefilter("ignore", FutureWarning) + return make() + + +def new(make): + """``make()``, refusing any warning of a deprecated form.""" + with warnings.catch_warnings(): + warnings.simplefilter("error", FutureWarning) + return make() + + +def same_policy(a, b): + """Two policies' numbers, bit for bit.""" + assert a.to_dict().keys() == b.to_dict().keys() + for key, value in a.items(): + other = b[key] + if isinstance(value, float) and math.isnan(value): + assert math.isnan(other), key + else: + assert json.dumps(value, default=str, sort_keys=True) == ( + json.dumps(other, default=str, sort_keys=True) + ), key + + +# ------------------------------------------------- the old forms' numbers + + +def plant_part(**more): + return NonRepairable( + LIFE, + planned_cost=4.0, + unplanned_cost=20.0, + opportunity_costs={"weekly": 3.0, "quarterly": 2.0, "annual": 1.0}, + **more, + ) + + +PLANT = Opportunities( + [ + Opportunity("weekly", period=7.0), + Opportunity("quarterly", period=91.0), + Opportunity("annual", period=364.0), + ] +) + + +def old_plant(anytime=4.0): + return old( + lambda: Calendar( + [ + Opportunity("weekly", 3.0, period=7.0), + Opportunity("quarterly", 2.0, period=91.0), + Opportunity("annual", 1.0, period=364.0), + ], + failure=20.0, + anytime=anytime, + ) + ) + + +def test_model_time_is_bit_identical_to_the_calendar(): + before = old( + lambda: NonRepairable(LIFE).optimal_calendar_policy(old_plant()) + ) + after = new(lambda: plant_part().optimal_opportunity_policy(PLANT)) + same_policy(before, after) + assert after.cost_rate == pytest.approx(0.006943, abs=5e-7) + assert before.schedule() == after.schedule() + rule = {"annual": 0.0} + assert old( + lambda: NonRepairable(LIFE).calendar_policy_cost(old_plant(), rule) + ) == new(lambda: plant_part().opportunity_policy_cost(PLANT, rule)) + + +def test_model_time_discounted_is_bit_identical(): + rate = math.log(1.07) / 365.25 + stops = Opportunities([Opportunity("stop", period=28.0)], any_day=False) + before = old( + lambda: NonRepairable(LIFE).optimal_calendar_policy( + Calendar( + [Opportunity("stop", 3.0, period=28.0)], + failure=20.0, + anytime=None, + ), + discount_rate=rate, + ) + ) + part = NonRepairable(LIFE, unplanned_cost=20.0, opportunity_cost=3.0) + after = new( + lambda: part.optimal_opportunity_policy(stops, discount_rate=rate) + ) + same_policy(before, after) + assert after.npv == before.npv and after.eac == before.eac + + +SITE_PART = NonRepairable( + LIFE, + planned_cost=4.0, + unplanned_cost=20.0, + opportunity_costs={"stop": 3.0, "turnaround": 0.5}, +) +STOP_PART = NonRepairable( + LIFE, planned_cost=4.0, unplanned_cost=20.0, opportunity_cost=3.0 +) +STOP = Opportunity("stop", Recurrence.every(4, "weeks", "2026-11-21")) +TURNAROUND = Opportunity("turnaround", dates=["2027-03-03", "2028-09-09"]) + + +def old_site(any_day=4.0, turnaround=True): + def make(): + shuts = [ + Shutdown( + "stop", + Recurrence.every(4, "weeks", "2026-11-21"), + replace_cost=3.0, + ) + ] + if turnaround: + shuts.append( + Shutdown( + "turnaround", + dates=["2027-03-03", "2028-09-09"], + replace_cost=0.5, + ) + ) + return Shutdowns(shuts, any_day=any_day) + + return old(make) + + +@pytest.mark.parametrize("discount", [None, 0.07]) +@pytest.mark.parametrize("turnaround", [False, True]) +def test_a_site_is_bit_identical_to_shutdowns(discount, turnaround): + site = Opportunities([STOP, TURNAROUND] if turnaround else [STOP]) + part = SITE_PART if turnaround else STOP_PART + options = dict(unit="days", now=NOW, discount=discount) + before = old( + lambda: NonRepairable( + LIFE, planned_cost=1.0, unplanned_cost=20.0 + ).optimal_calendar_policy(old_site(turnaround=turnaround), **options) + ) + after = new(lambda: part.optimal_opportunity_policy(site, **options)) + same_policy(before, after) + assert before.schedule("2029-12-31") == after.schedule("2029-12-31") + + +def test_a_site_s_rule_cost_is_bit_identical(): + rule = {"stop": 300.0} + options = dict(unit="days", now=NOW) + before = old( + lambda: NonRepairable( + LIFE, planned_cost=1.0, unplanned_cost=20.0 + ).calendar_policy_cost(old_site(turnaround=False), rule, **options) + ) + after = new( + lambda: STOP_PART.opportunity_policy_cost( + Opportunities([STOP]), rule, **options + ) + ) + assert before.cost == after.cost + assert after.prices.price("stop") == 3.0 + + +def test_the_old_forms_on_the_new_method_give_the_same_numbers(): + # A Calendar or Shutdowns given to the new method: its prices are the + # part's for those opportunities. + part = NonRepairable(LIFE, planned_cost=1.0, unplanned_cost=20.0) + via_old = old(lambda: part.optimal_calendar_policy(old_plant())) + via_new = old(lambda: part.optimal_opportunity_policy(old_plant())) + same_policy(via_old, via_new) + assert via_new.prices.row("weekly").source == "opportunity" + assert via_new.prices.row("any day").source == "collection" + assert via_new.prices.row("failure").price == 20.0 + + +# ----------------------------------------------------------- the prices + + +def test_overrides_by_name_and_by_object(): + weekly, annual = Opportunity("weekly", period=7.0), Opportunity( + "annual", period=364.0 + ) + plant = Opportunities([weekly, annual]) + by_name = NonRepairable( + LIFE, + planned_cost=4.0, + unplanned_cost=20.0, + opportunity_cost=3.0, + opportunity_costs={"annual": 1.0}, + ) + by_object = NonRepairable( + LIFE, + planned_cost=4.0, + unplanned_cost=20.0, + opportunity_cost=3.0, + opportunity_costs={annual: 1.0}, + ) + a = new(lambda: by_name.optimal_opportunity_policy(plant)) + b = new(lambda: by_object.optimal_opportunity_policy(plant)) + same_policy(a, b) + rows = {r.name: (r.price, r.source) for r in a.prices.rows} + assert rows == { + "weekly": (3.0, "opportunity_cost"), + "annual": (1.0, "override"), + "any day": (4.0, "planned_cost"), + "failure": (20.0, "unplanned_cost"), + } + + +def test_a_typo_is_refused_with_the_names(): + part = NonRepairable( + LIFE, + planned_cost=4.0, + unplanned_cost=20.0, + opportunity_costs={"anual": 1.0}, + ) + with pytest.raises(ValueError, match="'anual'.*'weekly', 'quarterly'"): + part.optimal_opportunity_policy(PLANT) + stranger = Opportunity("annual", period=365.0) + part = NonRepairable( + LIFE, + planned_cost=4.0, + unplanned_cost=20.0, + opportunity_costs={stranger: 1.0}, + ) + with pytest.raises(ValueError, match="'annual', which is not one"): + part.optimal_opportunity_policy(PLANT) + + +def test_with_no_opportunity_cost_an_opportunity_is_any_other_day(): + part = NonRepairable(LIFE, planned_cost=4.0, unplanned_cost=20.0) + policy = new(lambda: part.optimal_opportunity_policy(PLANT)) + assert {r.name: r.price for r in policy.prices.rows} == { + "weekly": 4.0, + "quarterly": 4.0, + "annual": 4.0, + "any day": 4.0, + "failure": 20.0, + } + assert policy.prices.row("weekly").source == "planned_cost" + # Every opportunity at the any-day price is age replacement. + age = part.optimal_replacement_policy() + assert policy.cost_rate == pytest.approx(age.cost_rate, rel=1e-5) + + +def test_an_opportunity_with_no_price_at_all_is_refused(): + part = NonRepairable(LIFE, unplanned_cost=20.0) + with pytest.raises(ValueError, match="'weekly' has no price"): + part.optimal_opportunity_policy(PLANT) + + +def test_a_stop_too_short_for_the_job_is_skipped_and_said(): + site = Opportunities( + [ + Opportunity( + "weekly stop", Recurrence.weekly("Sat"), duration="8h" + ), + Opportunity("short stop", Recurrence.weekly("Wed"), duration="4h"), + ], + any_day=False, + ) + part = NonRepairable( + LIFE, unplanned_cost=20.0, opportunity_cost=3.0, job_duration="6h" + ) + policy = new( + lambda: part.optimal_opportunity_policy(site, unit="days", now=NOW) + ) + assert policy.prices.unused == ("short stop",) + row = policy.prices.row("short stop") + assert not row.used and math.isnan(row.price) + assert row.reason == "the 6 h job doesn't fit in the 4 h short stop" + assert "short stop" not in policy.rule.thresholds + # The same as the site without it. + alone = new( + lambda: part.optimal_opportunity_policy( + Opportunities([site["weekly stop"]], any_day=False), + unit="days", + now=NOW, + ) + ) + assert policy.cost == alone.cost + # A job of no stated length uses every stop. + quick = NonRepairable(LIFE, unplanned_cost=20.0, opportunity_cost=3.0) + assert ( + new( + lambda: quick.optimal_opportunity_policy( + site, unit="days", now=NOW + ) + ).prices.unused + == () + ) + + +def test_a_job_too_long_in_model_time(): + stops = Opportunities( + [ + Opportunity("long", period=28.0, duration=1.0), + Opportunity("short", period=7.0, duration=0.1), + ] + ) + part = NonRepairable( + LIFE, + planned_cost=4.0, + unplanned_cost=20.0, + opportunity_cost=3.0, + job_duration=0.25, + ) + policy = new(lambda: part.optimal_opportunity_policy(stops)) + assert policy.prices.unused == ("short",) + assert "doesn't fit" in policy.prices.row("short").reason + text = NonRepairable( + LIFE, planned_cost=4.0, unplanned_cost=20.0, job_duration="6h" + ) + with pytest.raises(ValueError, match="in model time give it as a number"): + text.optimal_opportunity_policy(stops) + + +def test_one_record_serves_two_parts_with_their_own_prices(): + pump = NonRepairable( + LIFE, planned_cost=4.0, unplanned_cost=20.0, opportunity_cost=1.0 + ) + seal = NonRepairable( + LIFE, planned_cost=4.0, unplanned_cost=20.0, opportunity_cost=3.5 + ) + stops = Opportunities([Opportunity("stop", period=28.0)]) + a = new(lambda: pump.optimal_opportunity_policy(stops)) + b = new(lambda: seal.optimal_opportunity_policy(stops)) + assert a.prices.price("stop") == 1.0 and b.prices.price("stop") == 3.5 + assert a.cost_rate < b.cost_rate + # Each is that part's policy over a calendar priced for it. + for part, policy, price in ((pump, a, 1.0), (seal, b, 3.5)): + alone = old( + lambda: NonRepairable(LIFE).optimal_calendar_policy( + Calendar( + [Opportunity("stop", price, period=28.0)], + failure=20.0, + anytime=4.0, + ) + ) + ) + same_policy(alone, policy) + + +def test_where_uses_only_what_takes_that_label_down(): + site = Opportunities( + [ + Opportunity("site stop", Recurrence.weekly("Sat")), + Opportunity( + "line 2 shut", + Recurrence.every(4, "weeks", "2026-11-18"), + takes_down=["Line 2"], + ), + ], + any_day=False, + ) + part = NonRepairable(LIFE, unplanned_cost=20.0, opportunity_cost=3.0) + line1 = new( + lambda: part.optimal_opportunity_policy( + site, where="Line 1", unit="days", now=NOW + ) + ) + assert line1.prices.unused == ("line 2 shut",) + assert ( + "doesn't take 'Line 1' down" in line1.prices.row("line 2 shut").reason + ) + line2 = new( + lambda: part.optimal_opportunity_policy( + site, where="Line 2", unit="days", now=NOW + ) + ) + assert line2.prices.unused == () + + +def test_any_day_false_allows_no_other_day(): + part = NonRepairable(LIFE, planned_cost=4.0, unplanned_cost=20.0) + stops = Opportunities([Opportunity("stop", period=28.0)], any_day=False) + policy = new(lambda: part.optimal_opportunity_policy(stops)) + assert not policy.prices.row("any day").used + assert policy.replacement_rates.get("anytime", 0.0) == 0.0 + + +# ------------------------------------------------------------ the helper + + +def test_the_helper_s_prices_by_hand(): + site = Opportunities( + [ + Opportunity( + "weekly stop", Recurrence.weekly("Sat"), duration="8h" + ), + Opportunity("short stop", Recurrence.weekly("Wed"), duration="4h"), + Opportunity("turnaround", dates=["2027-03-03"]), + ] + ) + prices = NonRepairable.opportunity_prices( + site, + replacement_cost=1_200, + replacement_duration="6h", + failure_cost=4_200, + failure_duration="18h", + downtime_cost=2_500, + ) + assert isinstance(prices, OpportunityPrices) + assert prices.price("weekly stop") == 1_200.0 + assert prices.price("turnaround") == 1_200.0 # no length: used + assert prices.unused == ("short stop",) + assert prices.price("any day") == 1_200.0 + 2_500.0 * 6.0 == 16_200.0 + assert prices.price("failure") == 4_200.0 + 2_500.0 * 18.0 == 49_200.0 + json.dumps(prices.to_dict()) + # Applied: the part's own prices, the downtime cost kept off it. + part = prices.apply(NonRepairable(LIFE)) + assert (part.cp, part.cu, part.opportunity_cost) == ( + 16_200.0, + 49_200.0, + 1_200.0, + ) + assert part.job_duration == "6h" and part.opportunity_costs == {} + assert not hasattr(part, "downtime_cost") + policy = new( + lambda: part.optimal_opportunity_policy(site, unit="days", now=NOW) + ) + for given, worked_out in zip(policy.prices.rows, prices.rows): + assert given.name == worked_out.name + assert given.used == worked_out.used + if given.used: + assert given.price == worked_out.price + + +def test_the_helper_in_model_time(): + stops = Opportunities( + [ + Opportunity("long", period=28.0, duration=1.0), + Opportunity("short", period=7.0, duration=0.1), + ] + ) + prices = NonRepairable.opportunity_prices( + stops, + replacement_cost=1.0, + replacement_duration=0.25, + failure_cost=5.0, + failure_duration=1.0, + downtime_cost=8.0, + ) + assert prices.price("long") == 1.0 and prices.unused == ("short",) + assert prices.price("any day") == 3.0 and prices.price("failure") == 13.0 + with pytest.raises(ValueError, match="in model time"): + NonRepairable.opportunity_prices( + stops, + replacement_cost=1.0, + replacement_duration="6h", + failure_cost=5.0, + failure_duration=1.0, + downtime_cost=8.0, + ) + + +def test_a_policy_s_prices_cannot_be_applied(): + policy = plant_part().optimal_opportunity_policy(PLANT) + with pytest.raises(ValueError, match="only"): + policy.prices.apply(NonRepairable(LIFE)) + + +# ------------------------------------------------- the opportunities + + +def test_a_mix_of_clocks_is_refused(): + with pytest.raises(ValueError, match="'stop' is in model time"): + Opportunities( + [ + Opportunity("stop", period=7.0), + Opportunity("shut", Recurrence.weekly("Sat")), + ] + ) + with pytest.raises(ValueError, match="period= is for model time"): + Opportunity("x", Recurrence.weekly("Sat"), period=7.0) + with pytest.raises(ValueError, match="time_zone is for"): + Opportunities( + [Opportunity("stop", period=7.0)], time_zone="Australia/Brisbane" + ) + with pytest.raises(ValueError, match="model time a duration is a number"): + Opportunity("stop", period=7.0, duration="8h") + with pytest.raises(ValueError, match="takes_down"): + Opportunity("stop", period=7.0, takes_down=[]) + + +@pytest.mark.parametrize( + "opportunity", + [ + Opportunity("stop", period=28.0, offset=3.0, duration=0.5), + Opportunity("turnaround", dates=[100.0, 400.0]), + Opportunity( + "weekly stop", + Recurrence.weekly("Sat"), + duration="8h", + at="21:00", + takes_down=["Line 2"], + ), + Opportunity( + "turnaround", + dates=["2027-03-03", "2028-09-09"], + then_every="4 years", + duration="21d", + ), + Opportunity( + "service", every=Usage(15_000, "km"), also_every="6 months" + ), + ], +) +def test_an_opportunity_is_saved_and_loaded(opportunity): + data = json.loads(json.dumps(opportunity.to_dict())) + assert Opportunity.from_dict(data) == opportunity + hash(opportunity) + + +def test_opportunities_are_saved_and_loaded(): + site = Opportunities( + [STOP, TURNAROUND], any_day=False, time_zone="Australia/Brisbane" + ) + data = json.loads(json.dumps(site.to_dict())) + assert Opportunities.from_dict(data) == site + # A saved Shutdowns loads, its prices kept as the deprecated ones. + saved = old_site().to_dict() + loaded = new(lambda: Opportunities.from_dict(saved)) + part = NonRepairable(LIFE, planned_cost=1.0, unplanned_cost=20.0) + options = dict(unit="days", now=NOW) + same_policy( + old(lambda: part.optimal_calendar_policy(old_site(), **options)), + new(lambda: part.optimal_opportunity_policy(loaded, **options)), + ) + + +def test_the_part_s_prices_are_saved_with_it(): + part = NonRepairable( + LIFE, + opportunity_cost=1.0, + job_duration="6h", + opportunity_costs={Opportunity("annual", period=364.0): 0.5}, + ) + rbd = RepairableRBD([("s", "p"), ("p", "t")], {"p": part}) + back = RBD.from_dict(json.loads(json.dumps(rbd.to_dict()))).components["p"] + assert back.opportunity_cost == 1.0 and back.job_duration == "6h" + assert back.opportunity_costs == {"annual": 0.5} + + +def test_part_prices_are_checked(): + with pytest.raises(ValueError, match="opportunity_cost"): + NonRepairable(LIFE, opportunity_cost=-1.0) + with pytest.raises(ValueError, match="job_duration"): + NonRepairable(LIFE, job_duration=0.0) + with pytest.raises(ValueError, match="job_duration"): + NonRepairable(LIFE, job_duration="six hours") + with pytest.raises(TypeError, match="keys"): + NonRepairable(LIFE, opportunity_costs={3: 1.0}) + with pytest.raises(ValueError, match="opportunity_costs"): + NonRepairable(LIFE, opportunity_costs={"a": -1.0}) + + +def test_the_site_s_dates_and_outages_need_no_prices(): + site = Opportunities( + [Opportunity("weekly stop", Recurrence.weekly("Sat"), duration="8h")] + ) + assert site.dates(NOW, "2026-11-30")["weekly stop"][0].isoformat() == ( + "2026-11-21" + ) + outages = site.on_diagram(NOW, "2026-11-30", unit="hours") + assert outages["weekly stop"]["duration"] == 8.0 + part = NonRepairable(LIFE, planned_cost=1.0, unplanned_cost=5.0) + route = site.route(part, unit="days", now=NOW) + assert route.route == "exact" + + +# --------------------------------------------------------- deprecations + + +@pytest.mark.parametrize( + "make, match", + [ + ( + lambda: Opportunity("w", 3.0, period=7.0), + r"Opportunity\(name, cost, ...\) puts a price.*opportunity_cost", + ), + ( + lambda: Opportunity("w", period=7.0, cost=3.0), + r"Opportunity\(..., cost=\) puts a price", + ), + ( + lambda: Calendar(), + "Calendar is deprecated: use Opportunities", + ), + ( + lambda: Shutdown("s", Recurrence.weekly("Sat"), replace_cost=1.0), + "Shutdown is deprecated: use Opportunity", + ), + ( + lambda: Shutdowns([]), + "Shutdowns is deprecated: use Opportunities", + ), + ( + lambda: Opportunities(any_day=4.0), + r"Opportunities\(any_day=\) puts a price", + ), + ( + lambda: NonRepairable( + LIFE, planned_cost=1.0, unplanned_cost=5.0 + ).optimal_calendar_policy(Opportunities()), + "optimal_calendar_policy is deprecated: use " + "NonRepairable.optimal_opportunity_policy", + ), + ( + lambda: NonRepairable( + LIFE, planned_cost=1.0, unplanned_cost=5.0 + ).calendar_policy_cost(Opportunities(), {}), + "calendar_policy_cost is deprecated: use " + "NonRepairable.opportunity_policy_cost", + ), + ], +) +def test_each_old_form_warns_with_its_replacement(make, match): + with pytest.warns(FutureWarning, match=match) as caught: + make() + assert any(NEXT_REMOVAL in str(w.message) for w in caught) + + +def test_the_0_14_positional_form_still_reads(): + legacy = old(lambda: Opportunity("annual", 1.0, 364.0, 182.0)) + assert (legacy.cost, legacy.period, legacy.offset) == (1.0, 364.0, 182.0) + overhaul = old( + lambda: Opportunity.from_recurrence( + "overhaul", + 1.0, + Recurrence.yearly(month=11, weekday="Tuesday", nth=1), + "2026-11-14", + "2029-12-31", + unit="days", + ) + ) + assert overhaul.cost == 1.0 and overhaul.dates == (353.0, 724.0, 1088.0) + + +def test_what_0_20_deprecates_goes_in_0_21(): + # Calendar, Shutdown, Shutdowns, the prices on opportunities and the + # two calendar method names: removed in 0.21. This fails as a reminder + # once the version reaches it. + version = tuple(map(int, __version__.split(".")))[:2] + assert version < tuple(map(int, NEXT_REMOVAL.split("."))) + + +def test_prices_go_through_json(): + policy = plant_part().optimal_opportunity_policy(PLANT) + data = json.loads(json.dumps(policy.to_dict())) + assert [r["name"] for r in data["prices"]["rows"]] == [ + "weekly", + "quarterly", + "annual", + "any day", + "failure", + ] + assert np.isfinite(data["cost_rate"]) diff --git a/repyability/tests/test_opportunities_on_diagram.py b/repyability/tests/test_opportunities_on_diagram.py new file mode 100644 index 00000000..761d61af --- /dev/null +++ b/repyability/tests/test_opportunities_on_diagram.py @@ -0,0 +1,181 @@ +"""A diagram's shutdowns given as the site's ``Opportunities`` in model +time: each opportunity is a shutdown of its name, and the record is the +diagram its dicts make, value for value and run for run.""" + +import json +import warnings + +import numpy as np +import pytest +import surpyval as surv + +from repyability import ( + Opportunities, + Opportunity, + RepairableRBD, + ShutdownPolicy, +) + +E = surv.Exponential.from_params +W = surv.Weibull.from_params +EDGES = [("s", "p"), ("p", "q"), ("q", "t")] + + +def components(): + return { + "p": { + "reliability": W([500.0, 2.0]), + "repairability": E([0.1]), + "repair_cost": 50.0, + "preventive": {"shutdown": "overhaul", "cost": 5.0}, + }, + "q": { + "reliability": W([800.0, 2.5]), + "repairability": E([0.2]), + "repair_cost": 20.0, + "replace_cost": 30.0, + "preventive": {"interval": 700.0, "policy": "age", "cost": 8.0}, + }, + } + + +def both(opportunities, shutdowns, **record): + site = Opportunities(opportunities, **record) + return ( + RepairableRBD(EDGES, components(), shutdowns=site), + RepairableRBD(EDGES, components(), shutdowns=shutdowns), + ) + + +def test_a_record_is_the_diagram_its_dicts_make(): + # Every 300 from 900 (both ways): on the diagram's clock, the first at + # 300, as a dict's offset 0 puts it. + by_record, by_dicts = both( + [ + Opportunity( + "overhaul", + period=300.0, + offset=900.0, + duration=10.0, + takes_down=["p"], + ) + ], + { + "overhaul": { + "period": 300.0, + "offset": 0.0, + "duration": 10.0, + "scope": ["p"], + "cost": 40.0, + } + }, + shut_costs={"overhaul": 40.0}, + ) + assert by_record.to_dict() == by_dicts.to_dict() + a = by_record.expected_cost(2000.0) + b = by_dicts.expected_cost(2000.0) + assert a.mean == b.mean and a.by_category == b.by_category + assert a.by_category["shutdown"] == 6 * 40.0 + runs = by_record.availability(2000.0, mc_samples=100, seed=4) + again = by_dicts.availability(2000.0, mc_samples=100, seed=4) + np.testing.assert_array_equal(runs.availability, again.availability) + # Saved, it is the dicts, and comes back as the same diagram. + saved = json.loads(json.dumps(by_record.to_dict())) + assert RepairableRBD.from_dict(saved).to_dict() == by_dicts.to_dict() + + +def test_times_idle_ageing_and_opportunistic_renewals_carry_over(): + by_record, by_dicts = both( + [ + Opportunity( + "overhaul", + dates=[250.0, 900.0, 1400.0], + duration=12.0, + idle_ageing=False, + opportunistic={"q": 300.0}, + ) + ], + { + "overhaul": { + "times": [250.0, 900.0, 1400.0], + "duration": 12.0, + "idle_ageing": False, + "opportunistic": {"q": 300.0}, + } + }, + ) + assert by_record.to_dict() == by_dicts.to_dict() + runs = by_record.cost(2000.0, mc_samples=100, seed=7) + again = by_dicts.cost(2000.0, mc_samples=100, seed=7) + np.testing.assert_array_equal(runs.samples, again.samples) + jobs = by_record.availability(2000.0, mc_samples=100, seed=7) + assert ( + jobs.outage_jobs + == by_dicts.availability(2000.0, mc_samples=100, seed=7).outage_jobs + ) + assert jobs.outage_jobs + + +def test_a_shut_with_no_duration_takes_no_time(): + by_record, by_dicts = both( + [Opportunity("overhaul", period=400.0)], + {"overhaul": {"period": 400.0, "offset": 0.0, "duration": 0.0}}, + ) + assert by_record.to_dict() == by_dicts.to_dict() + + +def test_the_diagram_options_are_saved_with_the_opportunity(): + stop = Opportunity( + "overhaul", + period=300.0, + idle_ageing=False, + opportunistic={"q": 300.0}, + ) + assert repr(stop) == ( + "Opportunity('overhaul', period=300.0, idle_ageing=False, " + "opportunistic=(('q', 300.0),))" + ) + saved = json.loads(json.dumps(stop.to_dict())) + assert Opportunity.from_dict(saved) == stop + plain = Opportunity("overhaul", period=300.0) + # A record saved before these options is read as it was. + assert "idle_ageing" not in plain.to_dict() + assert "opportunistic" not in plain.to_dict() + site = Opportunities([stop], shut_costs={"overhaul": 12.0}) + assert Opportunities.from_dict(site.to_dict()) == site + assert Opportunities([plain]).to_dict().get("shut_costs") is None + + +def test_refusals_say_what_to_give(): + dated = Opportunities([Opportunity("stop", dates=["2027-03-03"])]) + with pytest.raises(ValueError, match="on_diagram"): + RepairableRBD(EDGES, components(), shutdowns=dated) + with pytest.raises(ValueError, match="Opportunities the policy"): + RepairableRBD(EDGES, components(), shutdowns=ShutdownPolicy()) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", FutureWarning) + priced = Opportunity("overhaul", period=300.0, cost=10.0) + with pytest.raises(ValueError, match="shut_costs"): + RepairableRBD(EDGES, components(), shutdowns=Opportunities([priced])) + with pytest.raises(ValueError, match="not one of the opportunities"): + Opportunities( + [Opportunity("overhaul", period=300.0)], shut_costs={"x": 1.0} + ) + with pytest.raises(ValueError, match="at least 0"): + Opportunities( + [Opportunity("overhaul", period=300.0)], + shut_costs={"overhaul": -1.0}, + ) + with pytest.raises(ValueError, match="idle_ageing must be True"): + Opportunity("overhaul", period=300.0, idle_ageing="no") + with pytest.raises(ValueError, match="opportunistic must be an age"): + Opportunity("overhaul", period=300.0, opportunistic=-1.0) + # The diagram checks the scope against its nodes, as for a dict. + with pytest.raises(ValueError, match="scope"): + RepairableRBD( + EDGES, + components(), + shutdowns=Opportunities( + [Opportunity("overhaul", period=300.0, takes_down=["x"])] + ), + ) diff --git a/repyability/tests/test_outage_opportunistic.py b/repyability/tests/test_outage_opportunistic.py new file mode 100644 index 00000000..fc0fb566 --- /dev/null +++ b/repyability/tests/test_outage_opportunistic.py @@ -0,0 +1,178 @@ +"""Opportunistic work at a planned outage: a shutdown's +``"opportunistic"`` renews, at each of its starts, the components under +age replacement that are at least as old as their ages there, as their +own age replacement would (simulated; the exact methods refuse).""" + +import json +import math + +import numpy as np +import pytest +import surpyval as surv + +from repyability import RepairableRBD, SimulationChunk +from repyability.rbd import _compiled, _event_loop + +E, W = surv.Exponential.from_params, surv.Weibull.from_params +LIFE = W([1000.0, 3.0]) +TIMES = [800.0, 1500.0, 2500.0] +SERIES = [("s", "a"), ("a", "b"), ("b", "t")] + + +def line(opportunistic=None, times=TIMES, duration=10.0, **shut): + spec = {"duration": duration, "scope": ["a", "b"]} + if times is not None: + spec["times"] = times + spec.update(shut) + if opportunistic is not None: + spec["opportunistic"] = opportunistic + return RepairableRBD( + SERIES, + { + "a": { + "reliability": LIFE, + "repairability": E([0.1]), + "replace_cost": 500.0, + "preventive": { + "policy": "age", + "interval": 1200.0, + "cost": 100.0, + "duration": E([0.5]), + }, + }, + "b": { + "reliability": E([1e-4]), + "repairability": E([0.1]), + "repair_cost": 50.0, + }, + }, + shutdowns={"big": spec}, + ) + + +def test_an_age_never_reached_is_the_plan_without_the_rule(): + # Same seed, same numbers: an age of inf renews nothing. + plain = line().availability(3000.0, mc_samples=300, seed=4) + never = line({"a": math.inf}).availability(3000.0, mc_samples=300, seed=4) + np.testing.assert_array_equal(plain.uptimes, never.uptimes) + np.testing.assert_array_equal(plain.cost.samples, never.cost.samples) + assert never.opportunistic_renewals == {"a": 0, "b": 0} + assert [job["mean"] for job in never.outage_jobs] == [0.0, 0.0, 0.0] + # Nor does it stop the exact methods. + assert line({"a": math.inf}).expected_cost(3000.0).mean == pytest.approx( + line().expected_cost(3000.0).mean, rel=1e-12 + ) + + +def test_renewed_at_the_first_outage_exactly_when_it_never_failed(): + # At an age of the first outage's time, only a unit that has not + # failed since new is old enough: renewed there with chance R(800). + n = 4000 + result = line({"a": 800.0}).availability(3000.0, mc_samples=n, seed=2) + first = result.outage_jobs[0] + assert (first["shutdown"], first["start"]) == ("big", 800.0) + p = float(LIFE.sf(800.0)) + assert first["standard_error"] == pytest.approx( + math.sqrt(p * (1 - p) / n), rel=0.05 + ) + assert abs(first["mean"] - p) < 4 * first["standard_error"] + assert first["lower"] < first["mean"] < first["upper"] + total = sum(job["mean"] for job in result.outage_jobs) * n + assert result.opportunistic_renewals["a"] == pytest.approx(total) + + +def test_the_renewals_are_charged_as_its_preventive_work(): + # Renewed early, the unit is replaced at 100 instead of failing at + # 500 and being repaired: the run costs less, and every renewal is a + # preventive replacement, charged as one. + plain = line().cost(3000.0, mc_samples=1000, seed=3) + renewed = line({"a": 300.0}).cost(3000.0, mc_samples=1000, seed=3) + assert renewed.mean < plain.mean + assert renewed.by_category["preventive"] > plain.by_category["preventive"] + + +def test_a_number_renews_every_component_under_age_replacement(): + rbd = line(500.0) + assert rbd._outage_rules == {"big": (("a", 500.0),)} + given = line({"a": 500.0}) + a = rbd.availability(3000.0, mc_samples=200, seed=1) + b = given.availability(3000.0, mc_samples=200, seed=1) + np.testing.assert_array_equal(a.uptimes, b.uptimes) + + +def test_a_shut_in_no_time_renews_too(): + result = line({"a": 800.0}, duration=0.0).availability( + 3000.0, mc_samples=500, seed=5 + ) + assert result.outage_jobs[0]["mean"] > 0.0 + + +def test_the_exact_methods_refuse_naming_the_simulation(): + rbd = line({"a": 500.0}) + with pytest.raises(NotImplementedError, match=r"availability\(\)"): + rbd.expected_cost(3000.0) + with pytest.raises(NotImplementedError, match="opportunistically"): + rbd.expected_npv(3000.0, value_rate=1.0) + routes = rbd.analysis_routes() + assert routes["expected_npv"].route == "refused" + assert "opportunistically" in routes["expected_npv"].reason + assert routes["availability"].route == "simulated" + + +def test_the_compiled_engine_leaves_them_to_the_python_loop(): + rbd = line({"a": 500.0}, times=None, period=700.0, duration=0.0) + plan, _ = _event_loop._stream_plan(rbd, 100.0, 1, False) + assert _compiled.unsupported(rbd, plan, None, numba=True) == "shutdowns" + + +@pytest.mark.parametrize( + "opportunistic, match", + [ + ({"a": -1.0}, "0 or more"), + ({"c": 1.0}, "not a component"), + ({"b": 1.0}, "'policy': 'age'"), + ({}, "names no component"), + ("soon", "0 or more"), + ], +) +def test_the_rule_is_checked(opportunistic, match): + with pytest.raises(ValueError, match=match): + line(opportunistic) + + +def test_a_component_out_of_the_scope_is_refused(): + with pytest.raises(ValueError, match="in its scope"): + line({"a": 1.0}, scope=["b"]) + + +def test_no_component_under_age_replacement_is_refused(): + with pytest.raises(ValueError, match="no component in its scope"): + line(1.0, scope=["b"]) + + +def test_it_is_saved_and_read_back(): + rbd = line({"a": 500.0}) + back = RepairableRBD.from_dict(json.loads(json.dumps(rbd.to_dict()))) + assert back._outage_rules == rbd._outage_rules + a = rbd.availability(3000.0, mc_samples=100, seed=6) + b = back.availability(3000.0, mc_samples=100, seed=6) + np.testing.assert_array_equal(a.uptimes, b.uptimes) + assert json.loads(json.dumps(a.to_dict()))["outage_jobs"][0]["start"] == ( + 800.0 + ) + + +def test_chunks_merged_count_the_renewals_as_one_run(): + rbd = line({"a": 500.0}) + whole = rbd.availability(3000.0, mc_samples=60, seed=8) + chunks = [ + rbd.simulate_chunk(3000.0, k, k + 20, seed=8) for k in (0, 20, 40) + ] + merged = rbd.availability_from_chunks( + [ + SimulationChunk.from_dict(json.loads(json.dumps(c.to_dict()))) + for c in chunks + ] + ) + assert merged.outage_jobs == whole.outage_jobs + assert merged.opportunistic_renewals == whole.opportunistic_renewals diff --git a/repyability/tests/test_overhaul_replace_policy.py b/repyability/tests/test_overhaul_replace_policy.py index 1bfd6ab1..37e61efd 100644 --- a/repyability/tests/test_overhaul_replace_policy.py +++ b/repyability/tests/test_overhaul_replace_policy.py @@ -1,12 +1,19 @@ """The repair, overhaul and replace policy with cycles (``Repairable.overhaul_replace_cost_rate`` and ``optimal_overhaul_replace_policy``): checked against closed forms, the -periodic replacement it reduces to, and a seeded simulation of failure -times that does not use the formula's expected counts.""" +periodic replacement it reduces to, a seeded simulation of failure +times that does not use the formula's expected counts, and the plans it +is compared with (overhaul only, replace only, a failure limit), each +worked out independently.""" + +import itertools +import json +import math import numpy as np import pytest import surpyval as surv +from scipy.special import gammaln from surpyval.recurrent import CrowAMSAA, GeneralizedRenewal from repyability import OverhaulReplacePolicy, Repairable @@ -30,9 +37,11 @@ def test_one_cycle_is_periodic_replacement_at_the_replacement_cost(): part = unit(co=40.0) policy = part.optimal_overhaul_replace_policy(0.5, 40.0, max_cycles=1) classic = part.optimal_overhaul_policy() - assert policy.cycles == 1 - assert policy.interval == pytest.approx(classic.interval, rel=1e-6) - assert policy.cost_rate == pytest.approx(classic.cost_rate, rel=1e-9) + replace = policy.alternatives["replace only"] + assert "overhaul and replace" not in policy.alternatives + assert replace["cycles"] == 1 + assert replace["interval"] == pytest.approx(classic.interval, rel=1e-6) + assert replace["cost_rate"] == pytest.approx(classic.cost_rate, rel=1e-9) # By hand for a power law: T* = alpha (cp / (cr (b - 1)))^(1/b). assert classic.interval == pytest.approx( 100.0 * (40.0 / 1.0) ** 0.5, rel=1e-6 @@ -93,8 +102,11 @@ def test_the_best_policy_beats_every_other_choice(): assert best.cost_rate <= part.overhaul_replace_cost_rate( grid, k, f, cp ).min() * (1 + 1e-9) - assert best.cost_rate == pytest.approx( - part.overhaul_replace_cost_rate(best.interval, best.cycles, f, cp), + found = best.alternatives["overhaul and replace"] + assert found["cost_rate"] == pytest.approx( + part.overhaul_replace_cost_rate( + found["interval"], found["cycles"], f, cp + ), rel=1e-12, ) @@ -104,25 +116,169 @@ def test_a_unit_that_does_not_wear_out_is_never_overhauled(): 0.5, 20.0 ) assert policy.interval == np.inf and policy.cycles == 1 + assert policy.plan == "run to failure" assert policy.cost_rate == pytest.approx(0.01, rel=1e-3) -def test_a_cheap_overhaul_that_renews_is_never_followed_by_a_replacement(): +def test_an_overhaul_that_renews_is_the_as_new_overhaul_policy(): # Factor 0 and an overhaul cheaper than a replacement: replacing never - # pays, and the cycles run to the limit. + # pays, and overhauling only is the periodic overhaul policy at co. policy = unit().optimal_overhaul_replace_policy(0.0, 40.0, max_cycles=15) - assert policy.cycles == 15 periodic = unit().optimal_overhaul_policy() - assert policy.cost_rate > periodic.cost_rate - # More periods spread the replacement thinner, towards the periodic - # overhaul's rate from above. + assert policy.plan == "overhaul only" and policy.cycles == np.inf + assert policy.interval == pytest.approx(periodic.interval, rel=1e-6) + assert policy.cost_rate == pytest.approx(periodic.cost_rate, rel=1e-9) + # The cycles of overhaul and replace run to the limit, and more + # periods spread the replacement thinner, towards it from above. + k_cycle = policy.alternatives["overhaul and replace"] + assert k_cycle["cycles"] == 15 and policy.cycles_limit_reached longer = unit().optimal_overhaul_replace_policy(0.0, 40.0, max_cycles=60) - assert periodic.cost_rate < longer.cost_rate < policy.cost_rate + assert ( + periodic.cost_rate + < longer.alternatives["overhaul and replace"]["cost_rate"] + < k_cycle["cost_rate"] + ) + assert policy.saving == pytest.approx( + min( + v["cost_rate"] + for k, v in policy.alternatives.items() + if k != "overhaul only" + ) + - policy.cost_rate, + rel=1e-12, + ) + + +def test_many_periods_tend_to_never_replacing(): + # g(T, K) falls towards g_inf(T) = (cr [L(v* + T) - L(v*)] + co) / T, + # v* = f T / (1 - f), as K grows: by hand for L(a) = (a / 100)^2. + part = unit() + f, t, cp = 0.6, 80.0, 20.0 + v = f * t / (1 - f) + g_inf = (((v + t) / 100.0) ** 2 - (v / 100.0) ** 2 + 5.0) / t + rates = [part.overhaul_replace_cost_rate(t, k, f, cp) for k in (10, 100)] + assert rates[0] > rates[1] > g_inf + assert part.overhaul_replace_cost_rate(t, 100_000, f, cp) == ( + pytest.approx(g_inf, rel=1e-4) + ) + policy = part.optimal_overhaul_replace_policy(f, cp) + best = policy.alternatives["overhaul only"] + v = f * best["interval"] / (1 - f) + assert best["cost_rate"] == pytest.approx( + (((v + best["interval"]) / 100.0) ** 2 - (v / 100.0) ** 2 + 5.0) + / best["interval"], + rel=1e-12, + ) + + +def test_overhauling_for_ever_beats_the_old_answer(): + # The case the search over K alone got wrong: its best (overhaul every + # 177.7, replace every second period, 0.1172) loses to overhauling + # every 73.8 and never replacing (0.1129). + part = unit(100.0, 2.5, 1.0, 5.0) + policy = part.optimal_overhaul_replace_policy(0.6, 20.0, max_cycles=5) + old = policy.alternatives["overhaul and replace"] + assert (old["cycles"], round(old["interval"], 1)) == (2, 177.7) + assert round(old["cost_rate"], 4) == 0.1172 + assert policy.plan == "overhaul only" and policy.cycles == np.inf + assert policy.interval == pytest.approx(73.79, abs=0.01) + assert policy.cost_rate == pytest.approx(0.11293, abs=1e-5) + assert policy.failure_count is None + assert not policy.cycles_limit_reached + + +def test_a_small_restoration_makes_replacing_at_a_failure_count_pay(): + part = unit(100.0, 2.5, 1.0, 5.0) + policy = part.optimal_overhaul_replace_policy(0.9, 20.0, max_cycles=5) + assert policy.plan == "failure limit" + assert policy.failure_count == 13 + assert policy.interval == np.inf and policy.cycles == 1 + # By hand: (12 cr + cp) / E[T_13], E[T_n] = alpha Gamma(n + 1/b) / + # Gamma(n) for a power law. + e_t13 = 100.0 * math.gamma(13 + 1 / 2.5) / math.gamma(13) + assert policy.cost_rate == pytest.approx(32.0 / e_t13, rel=1e-9) + + +def _independent_best(alpha, beta, cr, co, f, cp, max_cycles, max_failures): + """The four plans' cost rates, each worked out without the optimiser: + closed forms where there are, a fine grid of intervals otherwise.""" + t = np.logspace(0.0, 4.0, 40_001) + + def lam(a): + return (a / alpha) ** beta + + # Periodic replacement of a power law: T* = alpha (cp / (cr (b-1)))^(1/b). + t_star = alpha * (cp / (cr * (beta - 1.0))) ** (1.0 / beta) + replace = (cr * lam(t_star) + cp) / t_star + v = f * t / (1.0 - f) + never = ((cr * (lam(v + t) - lam(v)) + co) / t).min() + k_cycle = math.inf + for k in range(2, max_cycles + 1): + v, repairs = np.zeros_like(t), np.zeros_like(t) + for _ in range(k): + repairs += lam(v + t) - lam(v) + v = f * (v + t) + rate = (cr * repairs + (k - 1) * co + cp) / (k * t) + k_cycle = min(k_cycle, rate.min()) + n = np.arange(1, max_failures + 1) + e_tn = alpha * np.exp(gammaln(n + 1.0 / beta) - gammaln(n)) + limit = ((cr * (n - 1) + cp) / e_tn).min() + return { + "replace only": replace, + "overhaul only": never, + "overhaul and replace": k_cycle, + "failure limit": limit, + } + + +GRID = list( + itertools.product( + (1.5, 2.5, 3.5), + (0.2, 0.5, 0.8), + (10.0, 20.0, 50.0, 100.0), + (2.0, 5.0, 10.0), + ) +) + + +def test_the_returned_plan_is_never_beaten_over_a_grid_of_cases(): + # 108 cases: shape 1.5-3.5, overhauls keeping 20-80% of the age, and a + # range of overhaul and replacement costs. + assert len(GRID) == 108 + plans = set() + for beta, f, cp, co in GRID: + part = unit(100.0, beta, 1.0, co) + policy = part.optimal_overhaul_replace_policy(f, cp, max_cycles=6) + others = _independent_best(100.0, beta, 1.0, co, f, cp, 6, 30) + best = min(others.values()) + # Never beaten by any of the four (a grid can only overstate a + # minimum), and no lower than the true one by more than the grid's + # resolution. + assert policy.cost_rate <= best * (1 + 1e-9) + assert policy.cost_rate >= best * (1 - 1e-5) + for plan, rate in others.items(): + assert policy.alternatives[plan]["cost_rate"] <= rate * (1 + 1e-9) + plans.add(policy.plan) + # Overhauling for ever and replacing at a failure count both win in + # some cases, so the comparison matters. + assert {"overhaul only", "failure limit"} <= plans def test_the_result_is_plain_data(): policy = unit().optimal_overhaul_replace_policy(0.5, 40.0) - assert set(policy.to_dict()) == {"interval", "cycles", "cost_rate"} + out = policy.to_dict() + assert set(out) == { + "interval", + "cycles", + "cost_rate", + "plan", + "failure_count", + "alternatives", + "saving", + "cycles_limit_reached", + } + assert out["alternatives"]["overhaul only"]["cycles"] == math.inf + json.dumps(out) def test_inputs_are_checked(): @@ -137,13 +293,15 @@ def test_inputs_are_checked(): part.optimal_overhaul_replace_policy(0.5, -3.0) with pytest.raises(ValueError, match="max_cycles"): part.optimal_overhaul_replace_policy(0.5, 3.0, max_cycles=0) + with pytest.raises(ValueError, match="max_failures"): + part.optimal_overhaul_replace_policy(0.5, 3.0, max_failures=0) bare = Repairable(CrowAMSAA.from_params([100.0, 2.0])) with pytest.raises(ValueError, match="costs not set"): bare.optimal_overhaul_replace_policy(0.5, 3.0) def test_a_simulation_backed_model_is_refused(): - grp = GeneralizedRenewal.fit_from_parameters( + grp = GeneralizedRenewal.from_params( [100.0, 2.0], 0.5, kijima="i", dist=surv.Weibull ) part = Repairable(grp) diff --git a/repyability/tests/test_plan_alone.py b/repyability/tests/test_plan_alone.py new file mode 100644 index 00000000..35176b90 --- /dev/null +++ b/repyability/tests/test_plan_alone.py @@ -0,0 +1,406 @@ +"""A unit's plan valued alone (UC-65 of the maintenance README): every +valuation of a ``UnitPlan`` is its one-node diagram's, so the plan alone +equals a diagram holding it, on every plan kind of the catalogue, with +and without a calendar; and the plan's own salvage, escalation and +retirement are the valuation's arguments for its node.""" + +import json +import math + +import numpy as np +import pytest +import surpyval as surv + +from repyability import RepairableRBD, Timeline +from repyability.maintenance import ( + AgePolicy, + BlockPolicy, + Inspection, + Prices, + UnitPlan, +) +from repyability.rbd import routes +from repyability.rbd.serialisation import rbd_from_json, rbd_to_json +from repyability.schedule import ( + CalendarContext, + DutyPlan, + Shifts, + UsageForecast, + events_by_period, +) +from repyability.tests import catalogue + +W = surv.Weibull.from_params([400.0, 2.0]) +REPAIR = surv.LogNormal.from_params([1.0, 0.5]) +HORIZON = 300.0 +RATE = 1e-3 + + +def holding(plan: UnitPlan) -> RepairableRBD: + """A diagram holding ``plan`` as its one node, drawn with other end + nodes than the plan's own diagram (the node keeps its name: a seeded + run's streams are named by their node).""" + node = UnitPlan.NODE + return RepairableRBD([("in", node), (node, "out")], {node: plan}) + + +def _plans(): + """Each distinct plan the catalogue's repairable diagrams hold that + can stand alone (no maintenance group, no site shutdown, no standby + group of the diagram's), by a name.""" + out = {} + for name, rbd in catalogue.repairable_kinds().items(): + for node, plan in rbd.plans.items(): + if plan.group is not None or plan.standby is not None: + continue + task = plan.task("preventive") + if getattr(task, "shutdown", None) is not None: + continue + if getattr(plan.task("inspection"), "shutdown", None): + continue + if getattr(task, "policy", None) is not None and not isinstance( + getattr(task, "policy"), str + ): + continue # a calendar policy is built from its site + key = repr(plan.spec()) + if key not in {repr(p.spec()) for p in out.values()}: + out[f"{name}: {node}"] = plan + return out + + +PLANS = _plans() + + +def outcome(call): + """``call()``'s result, or the refusal it raised (its type and + message).""" + try: + return call() + except (NotImplementedError, ValueError) as error: + return (type(error), str(error)) + + +def same_npv(a, b) -> None: + if isinstance(a, tuple) or isinstance(b, tuple): + assert a == b + return + for field in ("npv", "value", "cost", "salvage", "eac"): + x, y = getattr(a, field), getattr(b, field) + assert x == pytest.approx(y, rel=1e-12, abs=1e-12), field + mine = [row["present_value"] for row in a.cash_flows] + theirs = [row["present_value"] for row in b.cash_flows] + np.testing.assert_allclose(mine, theirs, rtol=1e-12, atol=1e-12) + + +def test_the_catalogue_has_plans_of_many_kinds(): + assert len(PLANS) >= 15 + + +@pytest.mark.parametrize("name", sorted(PLANS)) +def test_a_plan_alone_is_a_diagram_holding_it(name): + plan = PLANS[name] + other = holding(plan) + options = dict(discount_rate=RATE, value_rate=1.0, periods=3) + same_npv( + outcome(lambda: plan.expected_npv(HORIZON, **options)), + outcome(lambda: other.expected_npv(HORIZON, **options)), + ) + rate = outcome(plan.expected_cost_rate) + theirs = outcome(other.expected_cost_rate) + if isinstance(rate, tuple) or isinstance(theirs, tuple): + assert rate == theirs + else: + assert rate == pytest.approx(theirs, rel=1e-12, abs=1e-12) + runs = dict(discount_rate=RATE, value_rate=1.0, mc_samples=40, seed=3) + mine = outcome(lambda: plan.npv_distribution(HORIZON, **runs)) + theirs = outcome(lambda: other.npv_distribution(HORIZON, **runs)) + if isinstance(mine, tuple) or isinstance(theirs, tuple): + assert mine == theirs + else: + np.testing.assert_allclose( + mine.samples, theirs.samples, rtol=1e-12, atol=1e-12 + ) + + +@pytest.mark.parametrize("name", sorted(PLANS)) +def test_a_plan_says_how_it_is_valued_as_its_diagram_does(name): + plan = PLANS[name] + mine = plan.analysis_routes() + theirs = holding(plan).analysis_routes() + assert mine["expected_npv"].route == theirs["expected_npv"].route + assert mine["cash_flows"] == mine["expected_npv"] + assert mine["npv_distribution"].route == theirs["npv_distribution"].route + + +# -- on a calendar ----------------------------------------------------------- + +FRAME = UsageForecast.calendar("2027-01-04", "2027-02-01") +SHIFTS = DutyPlan(Shifts("Mon-Fri", "06:00", "22:00")).forecast( + "2027-01-04", "2027-02-01" +) +SHARE = CalendarContext(FRAME, {UnitPlan.NODE: 0.5}) +CHANGING = CalendarContext(FRAME, {UnitPlan.NODE: SHIFTS}) + +ON_CALENDAR = { + "run to failure": UnitPlan(W, REPAIR, prices=Prices(repair=5.0)), + "age in operating hours": UnitPlan( + W, + REPAIR, + tasks=( + AgePolicy( + interval=250.0, cost=2.0, duration=REPAIR, basis="operating" + ), + ), + prices=Prices(repair=5.0, downtime=1.0), + ), + "block": UnitPlan( + W, + REPAIR, + tasks=(BlockPolicy(interval=200.0, cost=2.0, duration=REPAIR),), + prices=Prices(repair=5.0), + ), +} + + +def on_calendar(plan, calendar): + return calendar.diagram( + RepairableRBD( + [("s", UnitPlan.NODE), (UnitPlan.NODE, "t")], + {UnitPlan.NODE: plan}, + ) + ) + + +@pytest.mark.parametrize("calendar", [SHARE, CHANGING], ids=["share", "plan"]) +@pytest.mark.parametrize("name", sorted(ON_CALENDAR)) +def test_a_plan_alone_on_a_calendar_is_its_diagram_on_it(name, calendar): + plan = ON_CALENDAR[name] + other = on_calendar(plan, calendar) + runs = dict(discount_rate=RATE, mc_samples=40, seed=11) + np.testing.assert_allclose( + plan.npv_distribution(HORIZON, calendar=calendar, **runs).samples, + other.npv_distribution(HORIZON, **runs).samples, + rtol=1e-12, + atol=1e-12, + ) + same_npv( + outcome(lambda: plan.expected_npv(HORIZON, calendar=calendar)), + outcome(lambda: other.expected_npv(HORIZON)), + ) + events = dict(period="week", mc_samples=40, seed=2) + mine = plan.failures_by_period(calendar, **events) + theirs = events_by_period(other, calendar, **events) + assert json.dumps(mine.to_dict(), default=str) == json.dumps( + theirs.to_dict(), default=str + ) + + +def test_a_calendar_must_name_the_plan_node(): + plan = ON_CALENDAR["block"] + calendar = CalendarContext(FRAME, {"pump": 0.5}) + with pytest.raises(ValueError, match="no node 'pump'"): + plan.expected_npv(HORIZON, calendar=calendar) + with pytest.raises(TypeError, match="CalendarContext"): + plan.expected_npv(HORIZON, calendar=FRAME) + + +# -- the plan's own money ---------------------------------------------------- + +TIMED = UnitPlan( + W, + REPAIR, + tasks=(AgePolicy(interval=250.0, cost=2.0, duration=REPAIR),), + prices=Prices(repair=5.0, downtime=1.0, acquisition=20.0), +) + + +def with_money(**money) -> UnitPlan: + from dataclasses import replace + + return replace(TIMED, **money) + + +def test_its_salvage_escalation_and_retirement_are_the_arguments_for_it(): + options = dict(discount_rate=RATE, value_rate=1.0, periods=4) + plan = with_money(salvage=7.0, escalation=2e-4, retire_at=240.0) + same_npv( + plan.expected_npv(HORIZON, **options), + TIMED.expected_npv( + HORIZON, + salvage={UnitPlan.NODE: 7.0}, + escalation={UnitPlan.NODE: 2e-4}, + retire_at=240.0, + **options, + ), + ) + + +def test_a_salvage_by_age_is_the_argument_for_it(): + def worth(age): + return 10.0 * np.exp(-np.asarray(age) / 300.0) + + # A salvage by age is worked out for a plain unit from new. + plain = UnitPlan(W, REPAIR, prices=Prices(repair=5.0)) + from dataclasses import replace + + same_npv( + replace(plain, salvage=worth).expected_npv( + HORIZON, discount_rate=RATE + ), + plain.expected_npv( + HORIZON, discount_rate=RATE, salvage={UnitPlan.NODE: worth} + ), + ) + + +def test_the_arguments_take_precedence_over_the_plan(): + plan = with_money(salvage=7.0, escalation=2e-4, retire_at=240.0) + same_npv( + plan.expected_npv( + HORIZON, + discount_rate=RATE, + salvage={UnitPlan.NODE: 1.0}, + escalation={UnitPlan.NODE: 0.0}, + retire_at=100.0, + ), + TIMED.expected_npv( + HORIZON, + discount_rate=RATE, + salvage={UnitPlan.NODE: 1.0}, + retire_at=100.0, + ), + ) + # The system's salvage, a number, is added to the unit's own. + both = plan.expected_npv(HORIZON, discount_rate=RATE, salvage=2.0) + alone = plan.expected_npv(HORIZON, discount_rate=RATE) + assert both.salvage - alone.salvage == pytest.approx( + 2.0 * math.exp(-RATE * 240.0), rel=1e-12 + ) + + +def test_a_retirement_after_the_horizon_is_the_horizon(): + late = with_money(retire_at=10 * HORIZON) + same_npv( + late.expected_npv(HORIZON, discount_rate=RATE), + TIMED.expected_npv(HORIZON, discount_rate=RATE), + ) + + +def test_a_salvage_on_a_diagram_of_several_is_its_node_s(): + unit = with_money(salvage=7.0, escalation=2e-4) + other = {"reliability": W, "repairability": REPAIR, "repair_cost": 3.0} + edges = [("s", "a"), ("s", "b"), ("a", "t"), ("b", "t")] + mine = RepairableRBD(edges, {"a": unit, "b": other}) + given = RepairableRBD(edges, {"a": TIMED, "b": other}) + same_npv( + mine.expected_npv(HORIZON, discount_rate=RATE), + given.expected_npv( + HORIZON, + discount_rate=RATE, + salvage={"a": 7.0}, + escalation={"a": 2e-4}, + ), + ) + + +def test_one_unit_retiring_in_a_diagram_of_several_is_refused(): + unit = with_money(retire_at=100.0) + other = {"reliability": W, "repairability": REPAIR, "repair_cost": 3.0} + rbd = RepairableRBD( + [("s", "a"), ("a", "b"), ("b", "t")], {"a": unit, "b": other} + ) + with pytest.raises(NotImplementedError, match="retiring one unit"): + rbd.expected_npv(HORIZON) + assert rbd.analysis_routes()["expected_npv"].route == routes.REFUSED + # Retiring the whole system is the valuation's. + rbd.expected_npv(HORIZON, retire_at=100.0) + + +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) + 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) + np.testing.assert_array_equal( + grown.npv_distribution(HORIZON, **runs).samples, + TIMED.npv_distribution( + HORIZON, escalation={UnitPlan.NODE: 2e-4}, **runs + ).samples, + ) + + +def test_its_own_money_is_checked_and_saved(): + plan = with_money(salvage=7.0, escalation=2e-4, retire_at=240.0) + assert UnitPlan.from_spec(plan.spec()) == plan + saved = plan.to_dict() + assert {"salvage", "escalation", "retire_at"} <= set(saved["spec"]) + assert UnitPlan.from_dict(saved).to_dict() == saved + loaded = rbd_from_json(rbd_to_json(plan.diagram())) + assert loaded.plans[UnitPlan.NODE].to_dict() == saved + for money, match in ( + (dict(salvage=math.inf), "salvage"), + (dict(escalation="fast"), "escalation"), + (dict(retire_at=0.0), "retire_at"), + ): + with pytest.raises((ValueError, TypeError), match=match): + with_money(**money).diagram() + with pytest.raises(NotImplementedError, match="function"): + with_money(salvage=lambda age: age).to_dict() + + +# -- the plan's other valuations ---------------------------------------------- + + +def test_cash_flows_and_costs_are_its_diagram_s(): + other = holding(TIMED) + assert ( + TIMED.cash_flows(HORIZON, periods=3) + == other.expected_npv(HORIZON, periods=3).cash_flows + ) + assert TIMED.expected_cost(HORIZON).total == pytest.approx( + other.expected_cost(HORIZON).total, rel=1e-12 + ) + mine = TIMED.optimal_replacement_interval() + theirs = other.optimal_replacement_intervals() + assert mine.intervals[UnitPlan.NODE] == pytest.approx( + theirs.intervals[UnitPlan.NODE], rel=1e-12 + ) + + +def test_a_plan_against_what_happened_is_its_diagram_s(): + log = Timeline.from_outages([(50.0, 52.0)], 100.0) + plan = UnitPlan(W, REPAIR, prices=Prices(repair=5.0)) + mine = plan.plan_vs_actual(log, 100.0, HORIZON, discount_rate=RATE) + theirs = holding(plan).plan_vs_actual( + {UnitPlan.NODE: log}, 100.0, HORIZON, discount_rate=RATE + ) + assert mine.actual_so_far == pytest.approx(theirs.actual_so_far) + assert mine.expected_so_far == pytest.approx(theirs.expected_so_far) + + +def test_a_tested_unit_s_interval_is_chosen_alone(): + plan = UnitPlan( + surv.Exponential.from_params([1e-3]), + "instant", + tasks=(Inspection(interval=100.0, cost=1.0),), + prices=Prices(downtime=2.0), + ) + mine = plan.optimal_inspection_interval() + theirs = holding(plan).optimal_inspection_intervals() + assert mine.intervals[UnitPlan.NODE] == pytest.approx( + theirs.intervals[UnitPlan.NODE], rel=1e-12 + ) + + +def test_the_exact_npv_is_the_mean_of_the_runs(): + # Bounds fixed before running: four standard errors of the runs' mean. + options = dict(discount_rate=RATE, value_rate=1.0) + exact = TIMED.expected_npv(2000.0, **options).npv + runs = TIMED.npv_distribution( + 2000.0, mc_samples=4000, seed=20261121, **options + ) + error = np.std(runs.samples, ddof=1) / math.sqrt(runs.samples.size) + assert abs(runs.mean - exact) <= 4.0 * error diff --git a/repyability/tests/test_plan_vs_actual.py b/repyability/tests/test_plan_vs_actual.py index c43aa8de..8984fb6c 100644 --- a/repyability/tests/test_plan_vs_actual.py +++ b/repyability/tests/test_plan_vs_actual.py @@ -20,7 +20,7 @@ RepairableRBD, Timeline, ) -from repyability.rbd import _npv, _plan_actual +from repyability.rbd import _npv, _plan_actual, _pricing E = surv.Exponential.from_params W = surv.Weibull.from_params @@ -289,15 +289,15 @@ def test_each_kind_of_cost_left_out_says_why(): ) reasons = { (category, node): why - for category, node, why in _plan_actual._not_compared(rbd) + for category, node, why in _pricing.unrecorded(rbd) } assert reasons == { - ("repair", "a"): _plan_actual._UNITS, - ("replace", "a"): _plan_actual._UNITS, - ("preventive", "b"): _plan_actual._INSTANT, - ("inspection", "c"): _plan_actual._INSPECTIONS, - ("replace", "d"): _plan_actual._REPLACED, - ("setup", None): _plan_actual._SETUP, + ("repair", "a"): _pricing._UNITS, + ("replace", "a"): _pricing._UNITS, + ("preventive", "b"): _pricing._INSTANT, + ("inspection", "c"): _pricing._INSPECTIONS, + ("replace", "d"): _pricing._REPLACED, + ("setup", None): _pricing._SETUP, } @@ -449,7 +449,7 @@ def priced(rbd, sim, ends, rate, value_rate): for i in range(n): logs = {node: sim.components[node][i] for node in rbd.components} for r in _plan_actual._priced_log( - rbd, logs, ends, rate, value_rate, set() + rbd, logs, ends, _npv.Money(rbd, rate, value_rate), set() ): key = (r["period"], r["category"], r["component"]) out.setdefault(key, np.zeros(n))[i] = r["present_value"] @@ -557,7 +557,7 @@ def test_so_far_and_the_rest_from_each_state_average_to_the_plan(make, n): so_far[i] = sum( r["present_value"] for r in _plan_actual._priced_log( - rbd, logs, ends[:1], rate, value, set() + rbd, logs, ends[:1], _npv.Money(rbd, rate, value), set() ) ) states, _ = _plan_actual._states_now(rbd, logs, now, {}, None) @@ -699,8 +699,8 @@ def test_each_kind_whose_state_the_log_does_not_give_is_named( reason = _plan_actual._log_state_refusal(rbd, "a") assert words in reason and "'a'" in reason and "state=" in reason if kind == "replaced on a calendar policy": - assert ("preventive", "a", _plan_actual._CALENDAR) in ( - _plan_actual._not_compared(rbd) + assert ("preventive", "a", _pricing._CALENDAR) in ( + _pricing.unrecorded(rbd) ) diff --git a/repyability/tests/test_pm_restoration.py b/repyability/tests/test_pm_restoration.py index 2169a186..b882c31f 100644 --- a/repyability/tests/test_pm_restoration.py +++ b/repyability/tests/test_pm_restoration.py @@ -199,6 +199,15 @@ def agree(simulated: np.ndarray, reference: np.ndarray) -> None: dict(policy="block", interval=400.0, q=0.5, kijima="kijima1"), dict(duration=40.0, repair=50.0), ), + # Harmful maintenance: a task that leaves the unit older (q > 1). + "block, Kijima II, harmful": ( + dict(policy="block", interval=400.0, q=1.1, kijima="kijima2"), + {}, + ), + "age, Kijima I, harmful": ( + dict(policy="age", interval=300.0, q=1.2, kijima="kijima1"), + dict(duration=40.0, repair=50.0), + ), "on condition, Kijima I": ( dict(policy="condition", interval=100.0, q=0.3, kijima="kijima1"), dict(threshold=0.1), @@ -455,6 +464,12 @@ def test_the_compiled_engines_hand_it_to_python(): reason = "partial restoration by preventive maintenance" assert _compiled.unsupported(rbd, plan, None) == reason assert _compiled.unsupported(rbd, plan, None, numba=True) == reason + harmful = unit( + {"interval": 400.0, "restoration": {"model": "kijima2", "q": 1.1}} + ) + plan, _ = _event_loop._stream_plan(harmful, 100.0, 1, False) + assert _compiled.unsupported(harmful, plan, None) == reason + assert _compiled.unsupported(harmful, plan, None, numba=True) == reason def test_a_task_that_restores_uses_no_spare(): @@ -549,11 +564,13 @@ def test_its_restoration_factor_is_a_lever(): (lever,) = [ x for x in rbd.levers() if x.name == "preventive.restoration.q" ] - assert (lever.value, lever.bounds) == (0.3, (0.0, 1.0)) + assert (lever.value, lever.bounds) == (0.3, (0.0, math.inf)) moved = rbd.with_levers({lever: 0.8}) assert moved._restoring["a"].q == 0.8 - with pytest.raises(ValueError, match="between 0 and 1"): - rbd.with_levers({lever: 1.5}) + # Above 1 is harmful maintenance, a value the spec takes. + assert rbd.with_levers({lever: 1.5})._restoring["a"].q == 1.5 + with pytest.raises(ValueError, match="preventive.restoration.q"): + rbd.with_levers({lever: -0.5}) @pytest.mark.parametrize( @@ -564,8 +581,15 @@ def test_its_restoration_factor_is_a_lever(): "restoration must be a dict of a 'model'.*GeneralizedRenewal", ), ( - {"interval": 400.0, "restoration": {"model": "kijima1", "q": 2}}, - "q must be a number in \\[0, 1\\].*as old as it was", + {"interval": 400.0, "restoration": {"model": "kijima1", "q": -1}}, + "q must be a finite number, 0 or more.*as old as it was.*harmful", + ), + ( + { + "interval": 400.0, + "restoration": {"model": "kijima2", "q": math.inf}, + }, + "q must be a finite number, 0 or more", ), ( {"interval": 400.0, "replace_every": 3}, @@ -732,3 +756,104 @@ def test_a_run_conditioned_on_its_module_agrees_with_a_plain_one(): abs(conditioned.mean_availability - plain.mean_availability) <= Z * error ) + + +# Harmful maintenance (q > 1): a task that leaves the unit older than it +# was. Weibull(1000, 2.5) served every 250 h in no time, repairs instant. +SERVICE = 250.0 + + +def harmful(q, model, **more): + return unit( + { + "interval": SERVICE, + "policy": "block", + "restoration": {"model": model, "q": q}, + }, + **more, + ) + + +def survives_tasks(q, model, until=1000.0): + """The chance of no failure by ``until`` with tasks every ``SERVICE``, + from Kijima's definition: each piece adds ``H(v + x) - H(v)``.""" + + def H(x): + return (x / ALPHA) ** BETA + + v, t, total = 0.0, 0.0, 0.0 + while t < until: + x = min(SERVICE, until - t) + total += H(v + x) - H(v) + v = q * (v + x) if model == "kijima2" else v + q * x + t += x + return math.exp(-total) + + +def test_harmful_tasks_against_the_closed_form(): + # The hand-worked values of UC-62. + assert survives_tasks(1.1, "kijima2") == pytest.approx(0.295142, abs=5e-7) + assert survives_tasks(1.1, "kijima1") == pytest.approx(0.326487, abs=5e-7) + # q = 1 is the unit with no service: exp(-H(1000)) = exp(-1). + for model in ("kijima1", "kijima2"): + assert survives_tasks(1.0, model) == pytest.approx( + math.exp(-1.0), rel=1e-14 + ) + n = 4000 + for model in ("kijima1", "kijima2"): + run = harmful(1.1, model, repair_cost=1.0).cost( + 1000.0, mc_samples=n, seed=21, control_variate=False + ) + p = survives_tasks(1.1, model) + error = math.sqrt(p * (1.0 - p) / n) + assert abs(np.mean(run.samples == 0.0) - p) <= Z * error + + +def test_at_one_kijima_one_and_two_are_the_same_runs(): + # v + 1 x and 1 (v + x) are the same number, so the runs agree to the + # bit; and they are the failures of no service (the renewal function). + runs = [ + harmful(1.0, model, repair_cost=1.0).cost( + 3000.0, mc_samples=2000, seed=8, control_variate=False + ) + for model in ("kijima1", "kijima2") + ] + assert np.array_equal(runs[0].samples, runs[1].samples) + + +@pytest.mark.parametrize("model", ["kijima1", "kijima2"]) +def test_failures_and_cost_rise_with_q_above_one(model): + n = 4000 + failures, costs = [], [] + for q in (1.0, 1.1, 1.2): + run = harmful(q, model, repair_cost=1.0).cost( + 3000.0, mc_samples=n, seed=8, control_variate=False + ) + failures.append(run) + costs.append( + harmful(q, model, repair_cost=400.0) + .cost(3000.0, mc_samples=n, seed=8, control_variate=False) + .mean + ) + for lower, higher in zip(failures, failures[1:]): + error = math.sqrt( + lower.samples.var(ddof=1) / n + higher.samples.var(ddof=1) / n + ) + assert higher.mean - lower.mean > Z * error + assert costs[0] < costs[1] < costs[2] + + +def test_a_repair_keeps_its_factor_in_zero_to_one(): + with pytest.raises( + ValueError, match="Only a preventive task's restoration may be above 1" + ): + RepairableRBD( + EDGES, + { + "a": { + "reliability": LIFE, + "repairability": "instant", + "repair": {"model": "kijima1", "q": 1.1}, + } + }, + ) diff --git a/repyability/tests/test_preventive_maintenance.py b/repyability/tests/test_preventive_maintenance.py index f1ada63d..96bc2ea8 100644 --- a/repyability/tests/test_preventive_maintenance.py +++ b/repyability/tests/test_preventive_maintenance.py @@ -149,6 +149,8 @@ def test_maintenance_that_takes_time_is_a_planned_outage(): "system_downtime": 140.0, "setup": 0.0, "shutdown": 0.0, + "crews": 0.0, + "capital": 0.0, } ) assert result.cost.by_component == pytest.approx({"c": 110.0}) @@ -492,7 +494,7 @@ def test_forced_nodes_are_not_maintained(): ), ({"policy": "calendar"}, "needs a calendar"), ({"interval": 10, "duration": "quick"}, "time-to-maintain model"), - ({"interval": 10, "duration": 2.0}, "time-to-maintain model"), + ({"interval": 10, "duration": -2.0}, "time-to-maintain model"), ({"interval": 10, "cost": -1.0}, "non-negative"), ( {"interval": 10, "cost": surv.Normal.from_params([1, 5])}, diff --git a/repyability/tests/test_public_internals.py b/repyability/tests/test_public_internals.py index 006ffb76..f28e4203 100644 --- a/repyability/tests/test_public_internals.py +++ b/repyability/tests/test_public_internals.py @@ -63,6 +63,12 @@ def fault_tree_kinds(): PAIR = [("s", "a"), ("s", "b"), ("a", "t"), ("b", "t")] +def once_upgraded(rbd): + """The diagram a long-run method is asked of: ``rbd`` once upgraded + where it has upgrades (``_long_run.follows_upgrades``).""" + return _long_run.after_upgrades(rbd) if rbd._upgrades else rbd + + def quietly(call): """``call()``, or the error it raises, with warnings silenced.""" with warnings.catch_warnings(): @@ -115,7 +121,9 @@ def test_the_action_rates_are_the_private_call_s(name): public = quietly(rbd.node_action_rates) if isinstance(public, Exception): return # refused: the routes test checks it says so - private = quietly(lambda: private_actions(rbd)) + # The long run of a diagram with upgrades is that once upgraded + # (``_long_run.follows_upgrades``): the private call is asked of it. + private = quietly(lambda: private_actions(once_upgraded(rbd))) assert list(public) == list(rbd.components) for node, rates in public.items(): assert isinstance(rates, NodeActionRates) @@ -253,7 +261,7 @@ def test_the_replacement_cycle_is_the_private_call_s(name): public = quietly(lambda: rbd.replacement_cycle(node)) if isinstance(public, Exception): continue # refused: the routes test checks it says so - private = _long_run._block_cycle(rbd, node) + private = _long_run._block_cycle(once_upgraded(rbd), node) assert isinstance(public, ReplacementCycle) for field in public: assert np.array_equal( diff --git a/repyability/tests/test_public_surpyval_api.py b/repyability/tests/test_public_surpyval_api.py index 77555a90..da9977fd 100644 --- a/repyability/tests/test_public_surpyval_api.py +++ b/repyability/tests/test_public_surpyval_api.py @@ -38,15 +38,13 @@ "surpyval.univariate.nonparametric", "surpyval.univariate.regression", "surpyval.univariate.competing_risks", + "surpyval.univariate.joint", "surpyval.univariate.regression.kinds", } #: Names RePyability needs that surpyval has no public home for yet, each #: with why. Remove an entry once surpyval gives the name a public home. NO_PUBLIC_HOME = { - # A joint model's prediction for one unit, which a diagram takes as a - # block (``rbd/joint_node.py``). - ("surpyval.univariate.joint", "DynamicPrediction"), # A lifetime's life left at a virtual age, from a uniform: what # ``_event_loop._aged_life`` draws for any model it has no closed form # for (and the tests check ``MixtureLife`` against). @@ -180,7 +178,8 @@ def test_the_check_catches_a_private_import(tmp_path): ")\n" "import surpyval as surv\n" "surv.utils._private\n" - '"""\n>>> from surpyval.univariate.joint import JointModel\n"""\n' + '"""\n>>> from surpyval.univariate.joint.dynamic import ' + 'DynamicPrediction\n"""\n' ) imports = [ (module, name) @@ -190,7 +189,7 @@ def test_the_check_catches_a_private_import(tmp_path): assert imports == [ ("surpyval.univariate.regression._kinds", "PH"), ("surpyval.degradation.process_models", "WienerProcessModel"), - ("surpyval.univariate.joint", "JointModel"), + ("surpyval.univariate.joint.dynamic", "DynamicPrediction"), ] assert [d for _, d in _private_attributes(source)] == [ "surv.utils._private" diff --git a/repyability/tests/test_redundancy_strategies.py b/repyability/tests/test_redundancy_strategies.py index b83adda1..fb3d3a61 100644 --- a/repyability/tests/test_redundancy_strategies.py +++ b/repyability/tests/test_redundancy_strategies.py @@ -454,3 +454,104 @@ def test_cold_target_beyond_active_reach(): rbd.allocate_redundancy( {"n0": 1.0}, target=0.9, t=MISSION, max_units=3 ) + + +# -- start_probability: a spare that fails to start is skipped ------------- + + +@pytest.mark.parametrize("required", [1, 2]) +def test_start_probability_search_matches_the_design_applied(required): + # Two nodes in series, cold standby with spares that start with + # probability 0.9. The search's reliability is the diagram's once its + # design is fitted as a StandbyModel with that start_probability. + names, rbd = series([2000.0, 1500.0]) + models = {n: rbd.reliabilities[n] for n in names} + result = rbd.allocate_redundancy( + {"n0": 1.0, "n1": 1.0}, + budget=4 * required + 2, + t=MISSION, + required=required, + strategy="cold", + start_probability=0.9, + ) + assert max(result.units[n] for n in names) - required >= 2 + applied = NonRepairableRBD( + [("s", "n0"), ("n0", "n1"), ("n1", "t")], + { + n: StandbyModel( + [models[n]] * result.units[n], + k=required, + start_probability=0.9, + ) + for n in names + }, + ) + shown = float(np.ravel(applied.sf(MISSION))[0]) + assert result.reliability == pytest.approx(shown, rel=1e-12) + front = rbd.redundancy_front( + {"n0": 1.0, "n1": 1.0}, + budget=4 * required + 2, + t=MISSION, + required=required, + strategy="cold", + start_probability=0.9, + ) + same = [d for d in front if d.units == result.units] + assert same and same[0].reliability == pytest.approx(shown, rel=1e-12) + + +def test_start_probability_is_not_a_failed_switch(): + # One exponential unit and three cold spares: a spare that fails to + # start is skipped, so the arrangement works while fewer than four + # failures and skipped spares together have happened; a failed switch + # ends it. Closed forms of each, at mean 2000 over 1000. + rbd = NonRepairableRBD([("s", "a"), ("a", "t")], {"a": exponential(2000)}) + p, m = 0.9, MISSION / 2000 + skipped = rbd.allocate_redundancy( + {"a": 1.0}, budget=4, t=MISSION, strategy="cold", start_probability=p + ) + ended = rbd.allocate_redundancy( + {"a": 1.0}, + budget=4, + t=MISSION, + strategy="cold", + switching_probability=p, + ) + assert skipped.units == ended.units == {"a": 4} + # Skipped: the j-th failure is survived if a later spare starts; each + # failure uses up a started spare, so with j failures by t, the + # arrangement works if the 3 spares hold at least j that start. + starts = binom(3, p) + want = sum(poisson.pmf(j, m) * starts.sf(j - 1) for j in range(4)) + assert skipped.reliability == pytest.approx(want, rel=1e-6) + assert ended.reliability == pytest.approx( + sum(p**j * poisson.pmf(j, m) for j in range(4)), rel=2e-3 + ) + assert skipped.reliability > ended.reliability + + +@pytest.mark.parametrize( + "kwargs, match", + [ + ({"strategy": "cold", "start_probability": 1.5}, r"\[0, 1\]"), + ({"start_probability": 0.9}, "which no node uses"), + ( + {"strategy": {"n0": "cold"}, "start_probability": {"n1": 0.9}}, + "not a cold standby node", + ), + ( + { + "strategy": "cold", + "switching_probability": 0.95, + "start_probability": 0.9, + }, + "not both", + ), + ], +) +def test_start_probability_validation(kwargs, match): + names, rbd = series([2000.0, 1500.0]) + with pytest.raises(ValueError, match=match): + rbd.allocate_redundancy( + {"n0": 1.0, "n1": 1.0}, budget=10, t=MISSION, **kwargs + ) diff --git a/repyability/tests/test_refused_inputs.py b/repyability/tests/test_refused_inputs.py index 4a181c21..8027fb5d 100644 --- a/repyability/tests/test_refused_inputs.py +++ b/repyability/tests/test_refused_inputs.py @@ -279,3 +279,67 @@ def test_a_component_is_stocked_on_one_shelf(): ) pooled = rbd.spares_demand(300.0, parts={"p": ["a", "b"]})["p"] assert pooled.members == ("a", "b") + + +# -- a task's duration as a plain number (a fixed time) ----------------------- + + +def _maintained(task, duration): + spec = {"interval": 400.0, "cost": 50.0, "duration": duration} + if task == "preventive": + spec["policy"] = "age" + return RepairableRBD( + [("s", "a"), ("a", "t")], + { + "a": { + "reliability": W([1000.0, 2.0]), + "repairability": E([1 / 24]), + task: spec, + } + }, + ) + + +@pytest.mark.parametrize("task", ["preventive", "inspection"]) +def test_a_number_is_a_fixed_duration(task): + number = _maintained(task, 8.0) + exact = _maintained(task, surv.ExactEventTime.from_params([8.0])) + assert number.mean_availability() == exact.mean_availability() + times = np.array([100.0, 404.0, 900.0]) + assert np.array_equal( + number.point_availability(times), exact.point_availability(times) + ) + seeded = dict(mc_samples=200, seed=3) + assert np.array_equal( + number.availability(1000.0, **seeded).availability, + exact.availability(1000.0, **seeded).availability, + ) + # 0 is a task done in no time, as 'instant' + assert ( + _maintained(task, 0).mean_availability() + == _maintained(task, "instant").mean_availability() + ) + + +@pytest.mark.parametrize("task", ["preventive", "inspection"]) +@pytest.mark.parametrize("bad", [-1.0, float("nan"), float("inf"), True, "8"]) +def test_a_duration_that_is_no_time_is_refused(task, bad): + with pytest.raises(ValueError, match=f"the {task} duration must be"): + _maintained(task, bad) + + +def test_an_uncertainty_method_refuses_mc_samples_naming_n_draws(): + rbd = NonRepairableRBD( + [("s", "a"), ("a", "t")], + { + "a": surv.Weibull.fit( + surv.Weibull.random(30, 10, 2, random_state=1) + ) + }, + ) + for name in ("mc_samples", "N"): + with pytest.raises(TypeError, match="it takes n_draws="): + rbd.sf_uncertainty(5.0, **{name: 10}) + with pytest.raises(TypeError, match="it takes n_draws="): + rbd.mean_uncertainty(**{name: 10}) + assert rbd.sf_uncertainty(5.0, n_draws=20, seed=1).samples.shape == (20,) diff --git a/repyability/tests/test_regression_node.py b/repyability/tests/test_regression_node.py index d5675e0d..8671ff9d 100644 --- a/repyability/tests/test_regression_node.py +++ b/repyability/tests/test_regression_node.py @@ -13,7 +13,7 @@ import numpy as np import pytest import surpyval as surv -from surpyval.univariate.regression import StepSchedule +from surpyval.univariate.regression import ProportionalOddsFitter, StepSchedule from repyability import NodeState, NonRepairableRBD, RegressionNode @@ -32,7 +32,7 @@ def models(data): return { "aft": surv.WeibullAFT.fit(x, Z=Z), "ph": surv.CoxPH.fit(x, Z=Z), - "po": surv.ProportionalOddsFitter(surv.Weibull).fit(x, Z=Z), + "po": ProportionalOddsFitter(surv.Weibull).fit(x, Z=Z), } diff --git a/repyability/tests/test_repairable_cost.py b/repyability/tests/test_repairable_cost.py index f1a644f6..b6de1a06 100644 --- a/repyability/tests/test_repairable_cost.py +++ b/repyability/tests/test_repairable_cost.py @@ -262,6 +262,8 @@ def test_cost_breakdowns_are_internally_consistent(): "system_downtime", "setup", "shutdown", + "crews", + "capital", } assert result.by_category["preventive"] == 0.0 # nothing is maintained assert result.by_category["inspection"] == 0.0 # nor inspected diff --git a/repyability/tests/test_repairable_shocks.py b/repyability/tests/test_repairable_shocks.py new file mode 100644 index 00000000..fd911cb9 --- /dev/null +++ b/repyability/tests/test_repairable_shocks.py @@ -0,0 +1,276 @@ +"""Shocks at a rate of their own in a repairable diagram (`Shocks`): the +simulation against the rate-split groups it equals for exponential +members (the same strikes from the same streams), against their chains' +exact values, and, for members that wear out, against a simulation of +the member's own renewal process written here; and what refuses.""" + +from math import comb + +import numpy as np +import pytest +import surpyval as surv + +from repyability import ( + AlphaFactor, + BetaFactor, + CCFGroup, + NodeState, + PerfectReliability, + RepairableRBD, + Shocks, +) +from repyability.rbd import _ccf_groups + +W = surv.Weibull.from_params +E = surv.Exponential.from_params +PARALLEL = [("s", "a"), ("s", "b"), ("a", "t"), ("b", "t")] +TEST = {"interval": 100.0, "coverage": 0.8, "full_test": 300.0} + + +def pair(model, rate, repair=lambda: E([0.1]), inspection=None): + spec = {"reliability": E([rate]), "repairability": repair()} + if inspection: + spec = {**spec, "repairability": "instant", "inspection": inspection} + return RepairableRBD( + PARALLEL, + {"a": dict(spec), "b": dict(spec)}, + ccf_groups=[CCFGroup(["a", "b"], model)], + ) + + +def same_run(one, other, t=2e4, n=2000): + a = one.availability(t, mc_samples=n, seed=1, control_variate=False) + b = other.availability(t, mc_samples=n, seed=1, control_variate=False) + return ( + a.mean_availability == b.mean_availability + and a.system_failures == b.system_failures + ) + + +def test_lethal_shocks_on_exponential_members_are_the_beta_factor_run(): + """Own rate 2^-10 and lethal shocks at 2^-10 are the beta-factor pair + of rate 2^-9 with beta 1/2 (rates the split gives back exactly): the + same causes at the same rates, drawn from the same streams, so the + same run to the last bit.""" + own = shock = 2.0**-10 + total, beta = own + shock, 0.5 + assert (1 - beta) * total == own and beta * total == shock + assert same_run(pair(Shocks(shock), own), pair(BetaFactor(beta), total)) + + +def test_tested_members_are_the_beta_factor_run_too(): + """Hidden failures: a strike's damage waits for each member's test, + one coin for the failures a partial test may miss.""" + own = shock = 2.0**-10 + assert same_run( + pair(Shocks(shock), own, inspection=TEST), + pair(BetaFactor(0.5), own + shock, inspection=TEST), + ) + + +def test_partial_shocks_against_the_alpha_factor_chain(): + """Three exponential members, two needed; shocks fail each with + probability 0.4. The alpha-factor group with the same causes has an + exact mean availability (its chain), which the simulation's interval + of three standard errors covers.""" + own, rate, p, m = 2e-3, 6e-4, 0.4, 3 + total = own + rate * p + share = {j: rate * p**j * (1 - p) ** (m - j) for j in range(1, m + 1)} + share[1] += own + alphas = [comb(m - 1, j - 1) * share[j] / total for j in range(1, m + 1)] + edges = [("s", n) for n in "abc"] + [(n, "j") for n in "abc"] + edges += [("j", "t")] + + def build(model, life): + return RepairableRBD( + edges, + { + **{ + n: {"reliability": E([life]), "repairability": E([0.05])} + for n in "abc" + }, + "j": PerfectReliability, + }, + k={"j": 2}, + ccf_groups=[CCFGroup(list("abc"), model)], + ) + + t = 5000.0 + group = build(AlphaFactor(alphas), total) + route = group.analysis_routes()["mission_availability"].route + assert route in ("exact", "numerical") + exact = group.mission_availability(t) + run = build(Shocks(rate, p), own).availability(t, mc_samples=4000, seed=0) + assert run.control_variate is None # a plain run: nothing exact + error = run.mean_availability_interval().standard_error + assert abs(run.mean_availability - exact) <= 3 * error + + +def member_availability(life, repair, shock, t, n, seed): + """The mean availability over ``[0, t]`` of one unit, new at 0, that + fails at the earlier of its own life and the next shock and is then + repaired, by plain simulation: the mean and its standard error.""" + rng = np.random.default_rng(seed) + clock, up = np.zeros(n), np.zeros(n) + while np.any(clock < t): + going = clock < t + own = life.qf(rng.random(n)) + works = np.minimum(own, rng.exponential(1 / shock, n)) + up += np.where(going, np.minimum(works, t - clock), 0.0) + clock += works + repair.qf(rng.random(n)) + share = up / t + return share.mean(), share.std(ddof=1) / np.sqrt(n) + + +def test_a_member_that_wears_out_against_its_own_renewal_process(): + """Lethal shocks on Weibull members with Weibull repairs: a member is + up from each repair to the earlier of its life and the next shock. + The system here is up exactly while member ``a`` is.""" + life, repair, shock, t = W([300.0, 2.0]), W([20.0, 1.5]), 4e-3, 5000.0 + spec = {"reliability": life, "repairability": repair} + rbd = RepairableRBD( + [("s", "a"), ("a", "b"), ("b", "t"), ("a", "j"), ("j", "t")], + {"a": dict(spec), "b": dict(spec), "j": PerfectReliability}, + ccf_groups=[CCFGroup(["a", "b"], Shocks(shock))], + ) + run = rbd.availability(t, mc_samples=4000, seed=0) + mean, error = member_availability(life, repair, shock, t, 40000, seed=0) + assert abs(run.mean_availability - mean) <= 3 * np.hypot( + run.mean_availability_interval().standard_error, error + ) + # Without the shocks the member is up more: the check tells them. + plain, _ = member_availability(life, repair, 1e-12, t, 40000, seed=0) + assert plain - mean > 20 * error + + +def test_a_strike_fails_its_members_in_the_group_s_order(): + """Each cause names its members in the group's order, which is the + order a strike fails them in (`_event_loop._strike`).""" + spec = {"reliability": W([300.0, 2.0]), "repairability": E([0.1])} + rbd = RepairableRBD( + [("s", n) for n in "abc"] + [(n, "t") for n in "abc"], + {n: dict(spec) for n in "abc"}, + ccf_groups=[CCFGroup(["c", "a", "b"], Shocks(1e-3, 0.5))], + ) + struck = [cause.struck for cause in _ccf_groups._shared_causes(rbd)] + assert struck == [ + ("c",), + ("a",), + ("b",), + ("c", "a"), + ("c", "b"), + ("a", "b"), + ("c", "a", "b"), + ] + assert all(_ccf_groups._own_rate(rbd, n) is None for n in "abc") + + +def shocked(extra=None, **options): + spec = {"reliability": W([300.0, 2.0]), "repairability": E([0.1])} + return RepairableRBD( + PARALLEL, + {"a": {**spec, **(extra or {})}, "b": dict(spec)}, + ccf_groups=[CCFGroup(["a", "b"], Shocks(1e-3, 0.5))], + **options, + ) + + +def test_the_exact_methods_refuse_naming_the_simulation(): + rbd = shocked() + report = rbd.analysis_routes() + assert report["availability"].route == "simulated" + for name, call in ( + ("point_availability", lambda: rbd.point_availability(100.0)), + ("mean_availability", lambda: rbd.mean_availability()), + ("birnbaum_importance", lambda: rbd.birnbaum_importance()), + ): + assert report[name].route == "refused" + assert "availability() or cost()" in report[name].reason + with pytest.raises(NotImplementedError, match="rate of their own"): + call() + + +def test_maintenance_on_a_member_is_refused_by_name(): + rbd = shocked({"preventive": {"interval": 150.0, "duration": "instant"}}) + with pytest.raises( + NotImplementedError, match="scheduled maintenance.*left out" + ): + rbd.availability(1000.0, mc_samples=10, seed=0) + + +def test_a_tested_member_started_from_a_state_is_refused(): + spec = { + "reliability": W([300.0, 2.0]), + "repairability": "instant", + "inspection": {"interval": 100.0}, + } + rbd = RepairableRBD( + PARALLEL, + {"a": dict(spec), "b": dict(spec)}, + ccf_groups=[CCFGroup(["a", "b"], Shocks(1e-3))], + ) + rbd.availability(1000.0, mc_samples=10, seed=0) + with pytest.raises(NotImplementedError, match="Start it as new"): + rbd.availability( + 1000.0, mc_samples=10, seed=0, state={"a": NodeState(age=50.0)} + ) + + +def test_a_revealed_member_starts_from_its_age(): + rbd = shocked() + old = rbd.availability( + 200.0, mc_samples=2000, seed=0, state={"a": NodeState(age=250.0)} + ) + new = rbd.availability(200.0, mc_samples=2000, seed=0) + assert old.system_failures > new.system_failures + + +def test_saved_and_read_back_it_runs_the_same(): + import json + + rbd = shocked() + again = RepairableRBD.from_dict(json.loads(json.dumps(rbd.to_dict()))) + assert same_run(rbd, again, t=2000.0, n=200) + + +def test_a_group_of_too_many_members_is_refused(): + names = [f"n{i}" for i in range(11)] + spec = {"reliability": E([1e-3]), "repairability": E([0.1])} + with pytest.raises(ValueError, match="up to 10"): + RepairableRBD( + [("s", n) for n in names] + [(n, "t") for n in names], + {n: dict(spec) for n in names}, + ccf_groups=[CCFGroup(names, Shocks(1e-3, 0.5))], + ) + + +@pytest.mark.parametrize("life", [E([1e-3]), W([300.0, 2.0])]) +@pytest.mark.parametrize("crews", [None, 1]) +def test_a_member_s_own_values_refuse_and_say_what_to_run(life, crews): + """A member's own long-run availability and its spares come from its + own life, which the shocks add to, so they refuse (with crews, as + the crews' chain does), as the routes say; the simulated count of + spares runs.""" + spec = {"reliability": life, "repairability": E([0.1])} + rbd = RepairableRBD( + PARALLEL, + {"a": dict(spec), "b": dict(spec)}, + ccf_groups=[CCFGroup(["a", "b"], Shocks(1e-3, 0.5))], + repair_crews=crews, + ) + report = rbd.analysis_routes() + for name, call in ( + ("node_availability", rbd.node_availability), + ("spares_demand", lambda: rbd.spares_demand(1000.0)), + ("spares_stock", lambda: rbd.spares_stock(1000.0, fill_rate=0.9)), + ): + assert report[name].route == "refused" + with pytest.raises(NotImplementedError): + call() + if crews is None: + assert "shocks fail it too" in report["node_availability"].reason + assert "simulat" in report["spares_demand"].reason + demand = rbd.spares_demand( + 1000.0, method="simulate", mc_samples=50, seed=0 + ) + assert set(demand) == {"a", "b"} diff --git a/repyability/tests/test_replace_at.py b/repyability/tests/test_replace_at.py new file mode 100644 index 00000000..e6cce1a4 --- /dev/null +++ b/repyability/tests/test_replace_at.py @@ -0,0 +1,617 @@ +"""A component replaced at the times of a plan (``"replace_at"``): block +replacement at any list of times, and after the last no more. + +The references are block replacement on a period, which equally spaced +times are; closed forms (a memoryless unit between its replacements, a +unit that fails once at most, events at exact times discounted there); +and the simulation. +""" + +import json +import math + +import numpy as np +import pytest +import surpyval as surv + +from repyability import NodeState, RepairableRBD +from repyability.rbd import _compiled + +E = surv.Exponential.from_params +W = surv.Weibull.from_params +LN = surv.LogNormal.from_params +FIXED = surv.ExactEventTime.from_params +EDGES = [("s", "a"), ("a", "t")] + + +def one(life, repair, preventive, **more): + """A system of one component with a preventive task.""" + spec = { + "reliability": life, + "repairability": repair, + "preventive": preventive, + **more, + } + return RepairableRBD(EDGES, {"a": spec}) + + +# -- equally spaced times are block replacement ------------------------------- + + +@pytest.mark.parametrize( + "repair, duration", + [ + (LN([3, 0.5]), None), + (LN([3, 0.5]), W([6, 2])), + ("instant", FIXED([12.0])), + (E([0.02]), FIXED([5.0])), + ], +) +def test_equally_spaced_times_are_block_replacement(repair, duration): + life = W([1000, 2.5]) + task = {"cost": 50.0} + if duration is not None: + task["duration"] = duration + costs = {"repair_cost": 30.0, "downtime_cost": 2.0} + block = one( + life, repair, {"interval": 400.0, "policy": "block", **task}, **costs + ) + times = [400.0 * k for k in range(1, 6)] + plan = one(life, repair, {"replace_at": times, **task}, **costs) + t = np.linspace(0.0, 1900.0, 381) + np.testing.assert_allclose( + plan.point_availability(t), + block.point_availability(t), + rtol=0, + atol=1e-10, + ) + for T in (350.0, 400.0, 1234.5, 1900.0): + assert plan.mission_availability(T) == pytest.approx( + block.mission_availability(T), abs=1e-10 + ) + mine, theirs = plan.expected_events(T), block.expected_events(T) + for key in ("node_failures", "node_preventive", "node_downtime"): + assert getattr(mine, key)["a"] == pytest.approx( + getattr(theirs, key)["a"], abs=1e-10 + ) + assert mine.system_planned_outages == pytest.approx( + theirs.system_planned_outages, abs=1e-10 + ) + assert plan.expected_cost(T).mean == pytest.approx( + block.expected_cost(T).mean, rel=1e-10 + ) + assert plan.expected_cost(T, discount_rate=1e-3).mean == pytest.approx( + block.expected_cost(T, discount_rate=1e-3).mean, rel=1e-10 + ) + mine = plan.expected_npv( + 1900.0, discount_rate=1e-3, value_rate=7.0, periods=5 + ) + theirs = block.expected_npv( + 1900.0, discount_rate=1e-3, value_rate=7.0, periods=5 + ) + assert mine.npv == pytest.approx(theirs.npv, rel=1e-10) + assert mine.cost == pytest.approx(theirs.cost, rel=1e-10) + + +def test_no_times_before_the_horizon_change_nothing(): + life, repair = W([1000, 2.5]), LN([3, 0.5]) + plain = RepairableRBD( + EDGES, {"a": {"reliability": life, "repairability": repair}} + ) + plan = one(life, repair, {"replace_at": [5000.0], "cost": 9.0}) + t = np.linspace(0.0, 3000.0, 61) + # The plain unit's curve is on a grid of its own: to its precision. + np.testing.assert_allclose( + plan.point_availability(t), plain.point_availability(t), atol=2e-6 + ) + events = plan.expected_events(3000.0) + assert events.node_preventive["a"] == 0.0 + assert events.node_failures["a"] == pytest.approx( + plain.expected_events(3000.0).node_failures["a"], abs=2e-6 + ) + + +# -- closed forms ------------------------------------------------------------- + + +def memoryless(t, times, lam, mu, d): + """The point availability of a unit of failure rate ``lam`` and repair + rate ``mu``, new at 0, replaced in a time ``d`` at each of ``times`` + if it is up: a two-state chain between them, the units replaced back + as new ``d`` later and those in a repair carrying on.""" + total = lam + mu + + def from_up(s): + return mu / total + lam / total * np.exp(-total * s) + + def from_down(s): + return mu / total * (1.0 - np.exp(-total * s)) + + # (probability, when it starts, up or down then) of each part. + parts = [(1.0, 0.0, True)] + out = np.zeros_like(t) + edges = list(times) + [math.inf] + start = 0.0 + for end in edges: + inside = (t >= start) & (t < end) + for weight, since, up in parts: + s = t[inside] - since + value = from_up(s) if up else from_down(s) + out[inside] += weight * np.where(s >= 0.0, value, 0.0) + if not math.isfinite(end): + break + up_at = sum( + w * (from_up(end - s) if up else from_down(end - s)) + for w, s, up in parts + if end >= s + ) + waiting = sum(w for w, s, _ in parts if end < s) + assert waiting == 0.0, "a replacement longer than a gap" + parts = [(up_at, end + d, True), (1.0 - up_at, end, False)] + start = end + return out + + +@pytest.mark.parametrize("d", [0.0, 7.0]) +def test_an_exponential_unit_against_its_closed_form(d): + lam, mu = 1 / 200.0, 1 / 20.0 + times = [130.0, 310.0, 365.0, 640.0] + task = {"replace_at": times, "cost": 11.0} + if d: + task["duration"] = FIXED([d]) + rbd = one(E([lam]), E([mu]), task) + # (Not within a grid step of the end of a fixed replacement, where + # the curve bends between two points of its grid.) + t = np.array([0.0, 50.0, 129.9, 130.0, 133.0, 138.0, 200.0, 310.0]) + t = np.concatenate([t, [316.0, 364.0, 365.0, 373.0, 500.0, 640.0, 900.0]]) + expected = memoryless(t, times, lam, mu, d) + np.testing.assert_allclose(rbd.point_availability(t), expected, atol=2e-6) + # One replacement at T: up to it the chain from new, then the units + # replaced as new again (none, replaced in no time: it is memoryless). + single = one(E([lam]), E([mu]), {**task, "replace_at": [130.0]}) + np.testing.assert_allclose( + single.point_availability(t), + memoryless(t, [130.0], lam, mu, d), + atol=2e-6, + ) + up_at = memoryless(np.array([130.0 - 1e-9]), [], lam, mu, d)[0] + events = single.expected_events(400.0) + assert events.node_preventive["a"] == pytest.approx(up_at, abs=2e-6) + # Its replacement is charged once, at 130, and discounted from there. + rate = 2e-3 + assert single.expected_cost(400.0, discount_rate=rate).by_category[ + "preventive" + ] == pytest.approx(11.0 * up_at * math.exp(-rate * 130.0), rel=1e-5) + + +def test_a_weibull_unit_that_fails_once_against_its_closed_form(): + # Its repairs outlast the horizon, so a unit fails once at most: it is + # up before T if its first life is, and after T if that life reached T + # (when it is replaced, in no time) and the second has lasted since. + life, T = W([300, 2.2]), 180.0 + rbd = one( + life, + FIXED([10_000.0]), + {"replace_at": [T], "cost": 40.0}, + repair_cost=15.0, + ) + t = np.array([0.0, 60.0, 179.0, 180.0, 181.0, 300.0, 520.0]) + R = life.sf + expected = np.where(t < T, R(t), R(T) * R(np.maximum(t - T, 0.0))) + np.testing.assert_allclose(rbd.point_availability(t), expected, atol=2e-6) + events = rbd.expected_events(520.0) + failures = float(life.ff(T) + R(T) * life.ff(520.0 - T)) + assert events.node_failures["a"] == pytest.approx(failures, abs=2e-6) + assert events.node_preventive["a"] == pytest.approx(float(R(T)), abs=2e-6) + cost = rbd.expected_cost(520.0) + assert cost.mean == pytest.approx( + 15.0 * failures + 40.0 * float(R(T)), rel=1e-5 + ) + + +def test_replacements_are_discounted_at_their_times(): + # Repaired in no time, the unit is up at every time of the plan, and + # replaced there; memoryless, it fails at its rate throughout. + lam, rate, horizon = 1 / 500.0, 1.5e-3, 1000.0 + times = [120.0, 333.0, 480.0, 910.0, 1500.0] + rbd = one( + E([lam]), + "instant", + {"replace_at": times, "cost": 100.0}, + repair_cost=8.0, + ) + result = rbd.expected_npv(horizon, discount_rate=rate, value_rate=3.0) + planned = sum(100.0 * math.exp(-rate * t) for t in times if t < horizon) + annuity = (1.0 - math.exp(-rate * horizon)) / rate + # (The unit's chance of being up at each time is on its grid.) + assert result.cost_by_category["preventive"] == pytest.approx( + planned, rel=1e-7 + ) + assert result.cost_by_category["repair"] == pytest.approx( + 8.0 * lam * annuity, rel=1e-6 + ) + assert result.npv == pytest.approx( + 3.0 * annuity - planned - 8.0 * lam * annuity, rel=1e-6 + ) + # By period, each replacement falls in its own. + by_period = rbd.expected_npv( + horizon, discount_rate=rate, periods=[200.0, 400.0, 1000.0] + ) + rows = { + r["period"]: -r["present_value"] + for r in by_period.cash_flows + if r["category"] == "preventive" + } + assert rows[1] == pytest.approx(100.0 * math.exp(-rate * 120.0), rel=1e-7) + assert rows[2] == pytest.approx(100.0 * math.exp(-rate * 333.0), rel=1e-7) + assert rows[3] == pytest.approx( + 100.0 * (math.exp(-rate * 480.0) + math.exp(-rate * 910.0)), rel=1e-7 + ) + + +def test_stretches_of_any_lengths_agree_with_a_finer_grid(monkeypatch): + # Uneven stretches, each on a grid of its own, with repairs and + # replacements carried from one onto the next: against the same on + # grids four times as fine. + import repyability.rbd._block_replacement as block + + def build(): + return one( + W([400, 1.8]), + LN([3.0, 0.6]), + { + "replace_at": [90.0, 130.0, 317.0, 700.0, 760.0], + "duration": W([8, 1.5]), + }, + ) + + t = np.linspace(0.0, 1200.0, 241) + coarse = build().point_availability(t) + events = build().expected_events(1200.0) + monkeypatch.setattr(block, "_MIN_STEPS", 4 * block._MIN_STEPS) + monkeypatch.setattr( + block, "_STEPS_PER_SPREAD", 4 * block._STEPS_PER_SPREAD + ) + fine = build().point_availability(t) + finer = build().expected_events(1200.0) + np.testing.assert_allclose(coarse, fine, atol=2e-6) + for key in ("node_failures", "node_preventive"): + assert getattr(events, key)["a"] == pytest.approx( + getattr(finer, key)["a"], abs=5e-6 + ) + + +# -- the simulation ----------------------------------------------------------- + + +def plant(): + """Two units in parallel before a third, each on a plan of its own.""" + return RepairableRBD( + [("s", "a"), ("s", "b"), ("a", "c"), ("b", "c"), ("c", "t")], + { + "a": { + "reliability": W([300, 2.0]), + "repairability": LN([2.5, 0.6]), + "preventive": { + "replace_at": [150.0, 420.0, 600.0], + "duration": W([6, 2]), + "cost": 25.0, + }, + "repair_cost": 60.0, + }, + "b": { + "reliability": W([250, 1.5]), + "repairability": E([0.1]), + "preventive": {"replace_at": [200.0, 500.0], "cost": 20.0}, + "repair_cost": 40.0, + }, + "c": { + "reliability": W([900, 3.0]), + "repairability": LN([2.0, 0.5]), + "preventive": { + "replace_at": [400.0], + "duration": FIXED([10.0]), + "cost": 80.0, + }, + "repair_cost": 200.0, + }, + }, + downtime_cost_rate=5.0, + ) + + +def se(run) -> float: + """The standard error of a run's mean availability.""" + return float(run.mean_availability_interval().standard_error) + + +def test_the_simulation_agrees_with_the_exact_values(): + rbd, T = plant(), 800.0 + run = rbd.availability( + T, mc_samples=20_000, seed=11, control_variate=False + ) + exact = rbd.mission_availability(T) + assert abs(run.sample_mean_availability - exact) < 4.0 * se(run) + assert se(run) < 5e-4 + cost = rbd.expected_cost(T) + assert abs(run.cost.mean - cost.mean) < 4.0 * run.cost.mean_se + assert run.cost.mean_se < 0.005 * cost.mean + # By default the run's means are the exact ones. + default = rbd.availability(T, mc_samples=200, seed=11) + assert default.mean_availability == pytest.approx(exact, abs=1e-9) + + +def test_the_simulation_replaces_at_the_times_and_no_more(): + rbd = one( + W([1e9, 2.0]), + "instant", + {"replace_at": [100.0, 250.0], "duration": FIXED([10.0])}, + ) + lines = rbd.simulate_timelines(1000.0, mc_samples=3, seed=2) + history = lines.components["a"] + np.testing.assert_array_equal(history.planned_outages, [2, 2, 2]) + np.testing.assert_allclose(history.downtime, 20.0) + np.testing.assert_allclose(history.point_availability([105.0, 255.0]), 0.0) + np.testing.assert_allclose(history.point_availability([99.0, 111.0]), 1.0) + assert rbd.mission_availability(1000.0) == pytest.approx(0.98, abs=1e-9) + + +def test_a_compiled_engine_leaves_a_plan_to_the_python_loop(): + rbd = plant() + reason = _compiled._unsupported_maintenance(rbd, None) + assert reason == "replacement at the times of a plan" + route = rbd.analysis_routes()["availability"] + assert route.engine == "python" + assert "replacement at the times of a plan" in route.engine_reason + + +# -- from a state ------------------------------------------------------------- + + +def test_from_a_state_the_plan_is_counted_from_now(): + rbd, T = plant(), 700.0 + state = { + "a": NodeState(age=120.0), + "b": NodeState(alive=False, down_for=4.0), + "c": NodeState(age=300.0), + } + exact = rbd.mission_availability(T, state=state) + assert exact != pytest.approx(rbd.mission_availability(T), abs=1e-4) + run = rbd.availability( + T, mc_samples=20_000, seed=5, state=state, control_variate=False + ) + assert abs(run.sample_mean_availability - exact) < 4.0 * se(run) + cost = rbd.expected_cost(T, state=state) + assert abs(run.cost.mean - cost.mean) < 4.0 * run.cost.mean_se + # Memoryless and up, a unit's state changes nothing. + lam, mu = 1 / 200.0, 1 / 20.0 + task = {"replace_at": [130.0, 310.0], "duration": FIXED([7.0])} + memory = one(E([lam]), E([mu]), task) + t = np.array([10.0, 129.0, 131.0, 138.0, 250.0, 311.0, 400.0]) + np.testing.assert_allclose( + memory.point_availability(t, state={"a": NodeState(age=55.0)}), + memoryless(t, [130.0, 310.0], lam, mu, 7.0), + atol=2e-6, + ) + + +@pytest.mark.parametrize( + "state, message", + [ + ( + NodeState(since_scheduled=10.0), + "Component 'a' is replaced at the times of its plan " + "(replace_at), counted from now, which place its " + "replacements: leave its since_scheduled out.", + ), + ( + "stationary", + "Component 'a' is replaced at the times of a plan " + "(replace_at), which ends, so it has no long-run state: give " + "its age now (NodeState(age=...)), or leave it out (new).", + ), + ], +) +def test_a_plan_takes_no_place_on_a_calendar_and_no_long_run_state( + state, message +): + rbd = one(W([300, 2.0]), E([0.1]), {"replace_at": [100.0]}) + with pytest.raises(ValueError) as error: + rbd.point_availability([50.0], state={"a": state}) + assert str(error.value) == message + with pytest.raises(ValueError) as error: + rbd.availability(200.0, mc_samples=10, seed=1, state={"a": state}) + assert str(error.value) == message + + +# -- refusals ----------------------------------------------------------------- + +NO_LONG_RUN = ( + "Component 'a' is replaced at the times of a plan (replace_at), which " + "ends, so the diagram has no long run with it: ask for its values over " + "a horizon (expected_npv(horizon), expected_cost(T), " + "mission_availability(T), point_availability(t)), or give the " + "component an interval, block replacement for ever, for the long run." +) + + +@pytest.mark.parametrize( + "call", + [ + lambda rbd: rbd.mean_availability(), + lambda rbd: rbd.mean_unavailability(), + lambda rbd: rbd.node_availability(), + lambda rbd: rbd.system_failure_frequency(), + lambda rbd: rbd.expected_cost_rate(), + lambda rbd: rbd.birnbaum_importance(), + lambda rbd: rbd.replacement_cycle("a"), + lambda rbd: rbd.parameter_sensitivity(), + ], +) +def test_the_long_run_is_refused_saying_what_to_ask_for(call): + rbd = one( + W([300, 2.0]), E([0.1]), {"replace_at": [100.0]}, repair_cost=1.0 + ) + with pytest.raises(NotImplementedError) as error: + call(rbd) + assert str(error.value) == NO_LONG_RUN + for name in ("mean_availability", "expected_cost_rate"): + route = rbd.analysis_routes()[name] + assert (route.route, route.reason) == ("refused", NO_LONG_RUN) + for name in ("point_availability", "expected_cost", "expected_npv"): + assert rbd.analysis_routes()[name].route == "numerical" + + +def test_spares_and_the_plan_against_the_actual_say_what_to_do(): + rbd = one( + W([300, 2.0]), E([0.1]), {"replace_at": [100.0]}, repair_cost=1.0 + ) + with pytest.raises(NotImplementedError, match="replace_at.*simulat"): + rbd.spares_demand(200.0) + route = rbd.analysis_routes()["plan_vs_actual"] + assert route.route == "refused" + assert "counted from today, with expected_npv(state=)" in route.reason + + +@pytest.mark.parametrize( + "task, message", + [ + ( + {"replace_at": [100.0], "interval": 50.0}, + "Component 'a': give its preventive task an interval (replaced " + "every so often, for ever) or replace_at (replaced at those " + "times and no more), not both.", + ), + ( + {"replace_at": [100.0], "policy": "age"}, + "Component 'a': replace_at replaces the unit at each of its " + "times if it is up, which is the 'block' policy at given " + "times, so its policy cannot be 'age': leave the policy out, " + "or give that policy an interval and no replace_at.", + ), + ( + {"replace_at": [100.0, 100.0]}, + "Component 'a': replace_at must be the times at which the unit " + "is replaced, in the diagram's time from 0: positive, finite " + "and increasing, got [100.0, 100.0].", + ), + ( + {"replace_at": [0.0, 100.0]}, + "Component 'a': replace_at must be the times at which the unit " + "is replaced, in the diagram's time from 0: positive, finite " + "and increasing, got [0.0, 100.0].", + ), + ( + {"replace_at": []}, + "Component 'a': replace_at must be the times at which the unit " + "is replaced, in the diagram's time from 0: positive, finite " + "and increasing, got [].", + ), + ( + {"replace_at": ["100"]}, + "Component 'a': replace_at must be the times at which the unit " + "is replaced, in the diagram's time from 0: positive, finite " + "and increasing, got ['100'].", + ), + ( + {"replace_at": [100.0], "opportunity": 50.0}, + "Component 'a': an opportunity applies only to the 'age' and " + "'calendar' policies (a unit renewed early at a stop of its " + "maintenance group).", + ), + ], +) +def test_a_plan_s_spec_is_checked(task, message): + with pytest.raises(ValueError) as error: + one(W([300, 2.0]), E([0.1]), task) + assert str(error.value) == message + + +def test_a_plan_is_not_given_with_a_shutdown(): + with pytest.raises(ValueError) as error: + RepairableRBD( + EDGES, + { + "a": { + "reliability": W([300, 2.0]), + "repairability": E([0.1]), + "preventive": {"shutdown": "s1", "replace_at": [100.0]}, + } + }, + shutdowns={"s1": {"period": 100.0, "duration": 1.0}}, + ) + assert str(error.value) == ( + "Component 'a': its preventive task is done at shutdown 's1', " + "whose times apply, so it takes no replace_at: give the times to " + "the shutdown." + ) + + +# -- saving, levers, operating time ------------------------------------------- + + +def test_a_plan_is_saved_with_the_diagram(): + rbd = plant() + saved = json.loads(json.dumps(rbd.to_dict())) + again = RepairableRBD.from_dict(saved) + assert again._preventive["a"].times == (150.0, 420.0, 600.0) + assert again._preventive["a"].plan == (150.0, 420.0, 600.0) + t = np.linspace(0.0, 800.0, 33) + np.testing.assert_allclose( + again.point_availability(t), rbd.point_availability(t), atol=1e-12 + ) + assert again.expected_cost(800.0).mean == pytest.approx( + rbd.expected_cost(800.0).mean, rel=1e-12 + ) + + +def test_each_time_of_a_plan_is_a_lever(): + rbd = plant() + levers = { + (lever.key, lever.name): lever + for lever in rbd.levers() + if "replace_at" in lever.name + } + assert sorted(name for key, name in levers if key == "a") == [ + "preventive.replace_at.0", + "preventive.replace_at.1", + "preventive.replace_at.2", + ] + middle = levers[("a", "preventive.replace_at.1")] + assert (middle.value, middle.bounds) == (420.0, (150.0, 600.0)) + last = levers[("b", "preventive.replace_at.1")] + assert (last.value, last.bounds) == (500.0, (200.0, math.inf)) + moved = rbd.with_levers({("a", "preventive.replace_at.1"): 450.0}) + assert moved._preventive["a"].times == (150.0, 450.0, 600.0) + with pytest.raises(ValueError, match="between 150 and 600"): + rbd.with_levers({("a", "preventive.replace_at.1"): 600.0}) + # Over a window, a time's sensitivity is the system's own difference. + window = 800.0 + found = rbd.parameter_sensitivity(window=window)["a"] + step = 0.5 + name = "preventive.replace_at.1" + high = rbd.with_levers({("a", name): 420.0 + step}) + low = rbd.with_levers({("a", name): 420.0 - step}) + slope = ( + high.mission_availability(window) - low.mission_availability(window) + ) / (2.0 * step) + assert found[name] == pytest.approx(slope, rel=0.02, abs=1e-9) + + +def test_a_plan_counted_in_operating_time_goes_onto_the_calendar(): + life, repair = W([300, 2.0]), E([0.1]) + operating = RepairableRBD( + EDGES, + { + "a": { + "reliability": life, + "repairability": repair, + "duty": 0.5, + "preventive": { + "replace_at": [100.0, 250.0], + "basis": "operating", + }, + } + }, + ) + assert operating._preventive["a"].times == (200.0, 500.0) diff --git a/repyability/tests/test_restore_to.py b/repyability/tests/test_restore_to.py new file mode 100644 index 00000000..b12ffca7 --- /dev/null +++ b/repyability/tests/test_restore_to.py @@ -0,0 +1,146 @@ +"""A task that restores a part to a given virtual age (a preventive +spec's ``"restore_to"``; UC-58 of the maintenance README): simulated, the +exact methods refusing it by name.""" + +import json +import math + +import numpy as np +import pytest +import surpyval as surv +from scipy import integrate + +from repyability import RepairableRBD +from repyability.rbd import _compiled, _event_loop + +E, W = surv.Exponential.from_params, surv.Weibull.from_params +TAU, D, T = 300.0, 5.0, 900.0 + + +def outage(life, repair, **job): + return RepairableRBD( + [("s", "a"), ("a", "t")], + { + "a": { + "reliability": life, + "repairability": repair, + "preventive": {"shutdown": "overhaul", "cost": 1.0, **job}, + } + }, + shutdowns={"overhaul": {"times": [TAU], "duration": D}}, + ) + + +def test_restored_to_0_is_renewed_bit_for_bit(): + life, repair = W([400.0, 2.5]), E([0.05]) + renewed = outage(life, repair).availability(T, mc_samples=400, seed=3) + zero = outage(life, repair, restore_to=0.0).availability( + T, mc_samples=400, seed=3 + ) + np.testing.assert_array_equal(renewed.uptimes, zero.uptimes) + np.testing.assert_array_equal(renewed.cost.samples, zero.cost.samples) + # And the exact methods take it, as a renewal. + assert outage(life, repair, restore_to=0.0).expected_cost(T).mean == ( + outage(life, repair).expected_cost(T).mean + ) + + +def mean_up(result): + up = np.asarray(result.uptimes, float) / T + return float(up.mean()), float(up.std(ddof=1) / math.sqrt(up.size)) + + +def test_a_memoryless_part_is_as_if_renewed(): + life, repair = E([1 / 400.0]), E([0.05]) + exact = outage(life, repair).mission_availability(T) + found = outage(life, repair, restore_to=5000.0).availability( + T, mc_samples=4000, seed=7, control_variate=False + ) + mean, error = mean_up(found) + assert abs(mean - exact) < 4.0 * error + + +@pytest.mark.parametrize("age", [100.0, 500.0]) +def test_a_part_that_fails_once_at_most_against_its_survival(age): + # A repair that never ends inside the window: the part is up until + # its first failure. Overhauled at TAU (if up), it is down for D and + # then lives on from the virtual age: up at t > TAU + D with chance + # R(TAU) R(age + t - TAU - D) / R(age). + life = W([400.0, 2.5]) + found = outage(life, E([1e-9]), restore_to=age).availability( + T, mc_samples=4000, seed=11, control_variate=False + ) + + def up(t): + if t < TAU: + return float(life.sf(t)) + if t < TAU + D: + return 0.0 + return float(life.sf(TAU) * life.sf(age + t - TAU - D) / life.sf(age)) + + exact = ( + integrate.quad(up, 0.0, TAU, epsabs=1e-12)[0] + + integrate.quad(up, TAU + D, T, epsabs=1e-12)[0] + ) / T + mean, error = mean_up(found) + assert abs(mean - exact) < 4.0 * error + # It differs from a renewal by much more than its error. + renewed = outage(life, E([1e-9])).availability( + T, mc_samples=4000, seed=11, control_variate=False + ) + assert abs(mean_up(renewed)[0] - mean) > 10.0 * error + + +def test_the_exact_methods_refuse_naming_the_age_and_the_simulation(): + rbd = outage(W([400.0, 2.5]), E([0.05]), restore_to=500.0) + with pytest.raises(NotImplementedError, match="virtual age of 500"): + rbd.expected_cost(T) + routes = rbd.analysis_routes() + assert routes["expected_npv"].route == "refused" + assert "availability()" in routes["expected_npv"].reason + assert routes["availability"].route == "simulated" + # numba's loop leaves it to Python: the dated shut first, and a task + # that restores to an age on any calendar. + plan, _ = _event_loop._stream_plan(rbd, 100.0, 1, False) + assert _compiled.unsupported(rbd, plan, None, numba=True) == "shutdowns" + own = RepairableRBD( + [("s", "a"), ("a", "t")], + { + "a": { + "reliability": W([400.0, 2.5]), + "repairability": E([0.05]), + "preventive": {"interval": 200.0, "restore_to": 100.0}, + } + }, + ) + plan, _ = _event_loop._stream_plan(own, 100.0, 1, False) + assert _compiled.unsupported(own, plan, None, numba=True) == ( + "partial restoration by preventive maintenance" + ) + + +@pytest.mark.parametrize( + "job, match", + [ + ({"restore_to": -1.0}, "0 or more"), + ({"restore_to": "old"}, "0 or more"), + ( + { + "restore_to": 10.0, + "restoration": {"model": "kijima1", "q": 0.5}, + }, + "not both", + ), + ], +) +def test_what_is_refused(job, match): + with pytest.raises(ValueError, match=match): + outage(W([400.0, 2.5]), E([0.05]), **job) + + +def test_it_is_saved_and_read_back(): + rbd = outage(W([400.0, 2.5]), E([0.05]), restore_to=500.0) + back = RepairableRBD.from_dict(json.loads(json.dumps(rbd.to_dict()))) + a = rbd.availability(T, mc_samples=100, seed=2) + b = back.availability(T, mc_samples=100, seed=2) + np.testing.assert_array_equal(a.uptimes, b.uptimes) diff --git a/repyability/tests/test_schedule_discount.py b/repyability/tests/test_schedule_discount.py new file mode 100644 index 00000000..d5a697fd --- /dev/null +++ b/repyability/tests/test_schedule_discount.py @@ -0,0 +1,759 @@ +"""Present values on the calendar: ``discount=`` on ``Task.due``, +``work_by_period``, ``failures_by_period`` and ``events_by_period``, and +``Task.long_run_value``. + +The worked examples are UC-47 to UC-49 of +``repyability/schedule/README.md``, each checked by hand in the comments, +against closed forms and against sums and simulations written out +plainly here. +""" + +import json +import math +from datetime import date, timedelta + +import numpy as np +import pytest +import surpyval as surv + +from repyability import NonRepairable, RepairableRBD +from repyability.schedule import ( + DutyPlan, + Recurrence, + Shifts, + Task, + Usage, + UsageForecast, + _discount, + events_by_period, + failures_by_period, + work_by_period, +) +from repyability.schedule._forecast import _period_edges +from repyability.schedule._recurrence import _midnight + +TODAY = "2026-11-20" +RATE = math.log(1.07) # 7% a year, as a continuous rate a year + + +def grease(**options): + """$250 every 30 days from 20 November 2026.""" + return Task( + "grease bearings", + every=Recurrence.every(30, "days", TODAY), + cost=250.0, + **options, + ) + + +def first_tuesdays(**options): + return Task( + "inspect", + every=Recurrence.monthly(weekday="Tue", nth=1), + cost=250.0, + **options, + ) + + +@pytest.fixture +def pump(): + """Pump P-101: Mon-Fri 06:00-22:00 from Monday 16 Nov 2026.""" + plan = DutyPlan(Shifts("Mon-Fri", "06:00", "22:00")) + return plan.forecast( + "2026-11-16", "2027-12-01", readings={"hours": 12_340} + ) + + +def ring(**costs): + return NonRepairable(surv.Weibull.from_params([9000.0, 2.5]), **costs) + + +# ------------------------------------------------------------ the helpers + + +def test_the_discount_convention(): + # 7% a year: a year on is worth 1/1.07, a year being 365.25 days + assert _discount.factor(0.07, 1.0) == pytest.approx(1 / 1.07, rel=1e-15) + assert _discount.continuous(0.07) == math.log1p(0.07) + assert _discount.factor_on( + 0.07, date(2026, 11, 20), date(2027, 11, 20) + ) == pytest.approx(1.07 ** (-365 / 365.25), rel=1e-15) + # per hour of a model on the calendar + assert _discount.per_unit(0.07, 1.0) == pytest.approx(RATE / 8766.0) + assert _discount.per_unit(0.07, 24.0) == pytest.approx(RATE / 365.25) + # the equivalent annual cost: npv / years at no discount + assert _discount.equivalent_annual(300.0, 0.0, 2.0) == 150.0 + assert _discount.equivalent_annual(100.0, 0.07, math.inf) == ( + pytest.approx(100.0 * RATE) + ) + # 1 at 0, 1, 2, ... years for ever at 7%: 1.07 / 0.07 + assert _discount.perpetuity(0.07, 0.0, 1.0) == pytest.approx(1.07 / 0.07) + assert _discount.words(0.07, date(2026, 11, 20)) == ( + "Discounted to 2026-11-20 at 7% a year." + ) + for bad in (-0.01, "7%", True, 10.0, math.nan): + with pytest.raises(ValueError, match="yearly rate such as 0.07"): + _discount.yearly(bad) + assert _discount.yearly(None) is None + + +# ------------------------------------------------------------ UC-47 + + +def test_uc47_thirty_day_task_this_year_and_for_ever(): + task = grease() + year = task.due(TODAY, "2027-11-19", discount=0.07) + # days 0, 30, ..., 360: 13 tasks, $3,250; each 250 / 1.07^(days/365.25) + assert year.count == 13 and year.cost == 3250.0 + by_hand = sum(250.0 / 1.07 ** (30 * k / 365.25) for k in range(13)) + assert year.npv == pytest.approx(by_hand, rel=1e-14) + assert round(year.npv, 2) == 3144.10 + assert year.discount == 0.07 + assert year.notes[-1] == "Discounted to 2026-11-20 at 7% a year." + # the steady cost a year over the 365 days worth it + years = 365 / 365.25 + assert year.eac == pytest.approx( + RATE * year.npv / (1 - math.exp(-RATE * years)) + ) + # for ever: 250 / (1 - 1.07^(-30/365.25)) + value = task.long_run_value(TODAY, 0.07) + assert value.method == "closed form" and value.precision == 0.0 + assert value.npv == pytest.approx( + 250.0 / (1 - 1.07 ** (-30 / 365.25)), rel=1e-13 + ) + assert round(value.npv) == 45112 + assert value.eac == pytest.approx(value.npv * RATE) + assert round(value.eac) == 3052 + json.dumps(value.to_dict()) + json.dumps(year.to_dict()) + + +def test_uc47_by_quarter(): + work = work_by_period( + [grease()], "quarter", TODAY, "2027-11-19", discount=0.07 + ) + assert work.count == (2, 3, 3, 3, 2) + assert [round(x, 2) for x in work.npv] == [ + 498.61, + 737.61, + 725.41, + 713.42, + 469.05, + ] + assert round(work.total_npv, 2) == 3144.10 + assert work.notes == ("Discounted to 2026-11-20 at 7% a year.",) + json.dumps(work.to_dict()) + + +def test_long_run_against_100000_dates(): + # 100,000 dates 30 days apart reach past where dates go (8,200 + # years): summed as day counts, smallest first. + days = 30.0 * np.arange(100_000)[::-1] + brute = math.fsum(250.0 * np.exp(-RATE * days / 365.25)) + assert grease().long_run_value(TODAY, 0.07).npv == pytest.approx( + brute, rel=1e-12 + ) + # weekly, from an anchor three days on, at 3% + weekly = Task( + "check", every=Recurrence.every(2, "weeks", "2026-11-23"), cost=80.0 + ) + days = 3.0 + 14.0 * np.arange(100_000)[::-1] + brute = math.fsum(80.0 * np.exp(-math.log(1.03) * days / 365.25)) + assert weekly.long_run_value(TODAY, 0.03).npv == pytest.approx( + brute, rel=1e-12 + ) + + +def test_a_pattern_for_ever_against_2000_years_of_dates(): + # The first Tuesday of each month for 2,000 years, found from the + # calendar itself: the first day of the month moved on to a Tuesday. + start = date(2026, 11, 20) + brute = [] + for index in range(2026 * 12 + 10, 4026 * 12 + 10): + first = date(index // 12, index % 12 + 1, 1) + tuesday = first + timedelta(days=(1 - first.weekday()) % 7) + if tuesday >= start: + brute.append(250.0 * 1.07 ** (-(tuesday - start).days / 365.25)) + value = first_tuesdays().long_run_value(start, 0.07) + assert value.method == "summed" + assert value.npv == pytest.approx(math.fsum(brute[::-1]), rel=1e-9) + assert round(value.npv, 2) == 44350.51 + # what is left out is under the precision asked, and is what a task + # every day after the last date summed would add + assert 0.0 < value.precision <= 1e-9 * value.npv + days = (value.summed_to - start).days + v = 1.07 ** (-1 / 365.25) + assert value.precision == pytest.approx(250.0 * v ** (days + 1) / (1 - v)) + assert value.count == len( + first_tuesdays().due(start, value.summed_to).dates + ) + # a looser precision stops sooner, within its own bound of the value + loose = first_tuesdays().long_run_value(start, 0.07, precision=1e-3) + assert loose.summed_to < value.summed_to + assert 0.0 <= value.npv - loose.npv <= loose.precision + + +def test_long_run_with_visits_and_overdue(): + start = date(2026, 11, 20) + # Overdue (last done 1 September), the interval counting from when it + # is done: done today, then every 30 days. + overdue = grease(last_done="2026-09-01") + assert overdue.long_run_value(start, 0.07).npv == pytest.approx( + grease().long_run_value(start, 0.07).npv + ) + # Overdue with dates that stay fixed: done today, then on the rule's + # own dates (20 December on). + fixed = Task( + "fixed", + every=Recurrence.every(30, "days", "2026-09-21"), + last_done="2026-09-21", + resets=False, + cost=250.0, + ) + value = fixed.long_run_value(start, 0.07) + done = fixed.due(start, "2027-03-01").done + assert done[:3] == (start, date(2026, 12, 20), date(2027, 1, 19)) + assert value.npv == pytest.approx( + 250.0 + 250.0 * 1.07 ** (-30 / 365.25) / (1 - 1.07 ** (-30 / 365.25)) + ) + # A task that waits for Tuesday's visit is summed, and is the dates' + # own present value over a long period, to the bound. + waits = grease(visits=Recurrence.weekly("Tue")) + value = waits.long_run_value(start, 0.07, precision=1e-6) + assert value.method == "summed" + direct = waits.due(start, value.summed_to, discount=0.07) + assert value.npv == pytest.approx(direct.npv, rel=1e-14) + longer = waits.due(start, "2500-01-01", discount=0.07).npv + assert 0.0 < longer - value.npv <= value.precision + # nothing each time is nothing for ever + assert grease().cost == 250.0 + free = Task("look", every=Recurrence.weekly("Mon"), cost=0.0) + assert free.long_run_value(start, 0.07).npv == 0.0 + + +def test_what_has_no_long_run_value_is_refused(pump): + with pytest.raises(ValueError, match="costs without end.*due\\(start"): + grease().long_run_value(TODAY, 0.0) + with pytest.raises(ValueError, match="has no cost to value: give cost="): + Task("x", every=Recurrence.weekly("Mon")).long_run_value(TODAY, 0.07) + given = Task( + "x", every=Recurrence.on(["2027-01-05", "2027-06-01"]), cost=9.0 + ) + with pytest.raises( + ValueError, + match="given dates, which end on 2027-06-01: " + r"due\(2026-11-20, 2027-06-01, discount=...\)", + ): + given.long_run_value(TODAY, 0.07) + with pytest.raises(ValueError, match="nothing is left of it from then"): + given.long_run_value("2028-01-01", 0.07) + at_visits = grease(visits=Recurrence.on(["2027-01-05", "2027-06-01"])) + with pytest.raises(ValueError, match="visits on given dates"): + at_visits.long_run_value(TODAY, 0.07) + by_use = Task("service", every=Usage(500, "hours"), cost=300.0) + with pytest.raises(ValueError, match="limit by use.*usage=..., discount"): + by_use.long_run_value(TODAY, 0.07) + # given dates beside a rule that goes on are not an end + both = Task( + "x", + every=Recurrence.on(["2027-01-05"]), + also=Recurrence.yearly(month=7, day=1), + cost=9.0, + ) + assert both.long_run_value(TODAY, 0.07).method == "summed" + # a rate too low to settle before dates run out + with pytest.raises(ValueError, match="At 0.2% a year .* year 9999"): + first_tuesdays().long_run_value(TODAY, 0.002) + # ... also where only the sum itself shows it (a task once a year) + yearly = Task("x", every=Recurrence.yearly(month=7, day=1), cost=9.0) + with pytest.raises(ValueError, match=r"looser precision=.*due\(start"): + yearly.long_run_value(TODAY, 0.002, precision=5e-7) + loose = yearly.long_run_value(TODAY, 0.002, precision=1e-4) + # 9 a year for ever at 0.2%: about 9 / ln(1.002) + assert loose.npv == pytest.approx(9.0 / math.log(1.002), rel=2e-3) + with pytest.raises(ValueError, match="precision must be a share"): + grease().long_run_value(TODAY, 0.07, precision=0) + with pytest.raises(ValueError, match="yearly rate such as 0.07"): + grease().long_run_value(TODAY, None) + + +def test_no_discount_leaves_results_as_they_were(): + new = {"discount", "npv", "eac", "total_npv", "notes"} + task = grease() + plain = task.due(TODAY, "2027-11-19").to_dict() + assert plain["discount"] is None and plain["npv"] is None + assert plain["eac"] is None and plain["notes"] == [] + priced = task.due(TODAY, "2027-11-19", discount=0.07).to_dict() + assert {k: v for k, v in plain.items() if k not in new} == { + k: v for k, v in priced.items() if k not in new + } + tasks = [task, Task("walk round", every=Recurrence.weekly("Mon"))] + plain = work_by_period(tasks, "month", TODAY, "2027-11-19").to_dict() + assert plain["npv"] is None and plain["total_npv"] is None + assert plain["eac"] is None and plain["notes"] == [] + priced = work_by_period( + tasks, "month", TODAY, "2027-11-19", discount=0.07 + ).to_dict() + assert {k: v for k, v in plain.items() if k not in new} == { + k: v for k, v in priced.items() if k not in new + } + # the task with no cost is named, in no_cost and in the notes + assert priced["no_cost"] == ["walk round"] + assert priced["notes"][-1] == ( + "The present values leave out the tasks with no cost: walk round." + ) + no_cost = tasks[1].due(TODAY, "2027-11-19", discount=0.07) + assert no_cost.npv is None and no_cost.eac is None + assert no_cost.notes[-1] == ( + "No present value: the task has no cost (give cost=)." + ) + + +def test_discount_of_zero_is_the_plain_total(): + year = grease().due(TODAY, "2027-11-19", discount=0) + assert year.npv == year.cost == 3250.0 + assert year.eac == pytest.approx(3250.0 / (365 / 365.25)) + work = work_by_period( + [grease(), first_tuesdays()], "month", TODAY, "2027-11-19", discount=0 + ) + assert work.npv == work.cost + assert work.total_npv == sum(work.cost) + + +def test_periods_present_values_add_up(): + tasks = [ + grease(visits=Recurrence.weekly("Tue")), + first_tuesdays(), + Task( + "service", + every=Recurrence.every(3, "months", "2026-12-20"), + cost=480.0, + ), + ] + whole = sum(t.due(TODAY, "2029-11-19", discount=0.05).npv for t in tasks) + for period in ("day", "week", "month", "quarter", "year"): + work = work_by_period( + tasks, period, TODAY, "2029-11-19", discount=0.05 + ) + assert work.total_npv == pytest.approx(whole, rel=1e-13) + assert sum(work.npv) == pytest.approx(whole, rel=1e-13) + assert all(0.0 <= a <= b for a, b in zip(work.npv, work.cost)) + # each task is discounted from the date it is done (after its visit) + waits = tasks[0].due(TODAY, "2026-12-31", discount=0.05) + assert waits.done[0] == date(2026, 11, 24) + assert waits.npv == pytest.approx( + sum( + 250.0 * 1.05 ** (-(d - date(2026, 11, 20)).days / 365.25) + for d in waits.done + ) + ) + + +def test_far_dates_are_the_anchors_own(): + # A rule's dates far from its anchor, against dateutil's walked from + # the anchor itself. + rules = [ + Recurrence.every(30, "days", "2024-02-29"), + Recurrence.every(2, "weeks", "2026-01-31"), + Recurrence.every(5, "months", "2026-01-31"), + Recurrence.every(3, "months", "2026-01-31", short_months="skip"), + Recurrence.every(3, "years", "2024-02-29"), + Recurrence.weekly(["Mon", "Thu"], every=3, anchor="2026-11-14"), + Recurrence.monthly( + weekday="Fri", nth=-1, every=7, anchor="2025-03-01" + ), + Recurrence.monthly(day=31, every=2, anchor="2026-11-14"), + Recurrence.yearly( + month=3, weekday="Tue", nth=1, every=2, anchor="2026-11-14" + ), + Recurrence.yearly(month=2, day=29, every=5, anchor="2027-12-31"), + ] + for rule in rules: + walked = rule._rrule(rule.anchor) + for days in (0, 1, 27, 59, 365, 366, 1500, 25_000, 147_000): + lo = rule.anchor + timedelta(days=days) + want = [] + for moment in walked.xafter(_midnight(lo), inc=True): + want.append(moment.date()) + if len(want) == 4: + break + got = rule.dates(lo, want[-1]) + assert list(got) == want, (rule.describe(), lo) + + +# ------------------------------------------------------------ UC-48 + + +def test_uc48_wear_ring_present_value_by_month(pump): + part = ring(unplanned_cost=4800.0) + plain = failures_by_period(part, pump, "month", age=5200.0) + months = failures_by_period(part, pump, "month", age=5200.0, discount=0.07) + # every field there was is as it was + for name in plain: + if name in ("notes", "total"): + continue + a, b = plain[name], months[name] + if name in ("discount", "expected_npv", "npv", "npv_precision", "eac"): + assert a is None and b is not None + elif isinstance(a, np.ndarray): + assert np.array_equal(a, b) + else: + assert a == b + assert months.notes[:-1] == plain.notes + assert { + k: v for k, v in months.total.items() if "npv" not in k + } == plain.total + # A month's cost is worth at most its value from the month's start, + # at least from its end: $2,874.75 to $2,890.71 over the 13 months. + _, seconds = _period_edges(pump, "month") + ends = seconds / 86400.0 / 365.25 + starts = np.r_[0.0, ends[:-1]] + high = months.expected_cost * 1.07**-starts + low = months.expected_cost * 1.07**-ends + assert round(high.sum(), 2) == 2890.71 and round(low.sum(), 2) == 2874.75 + assert np.all(months.expected_npv <= high + 1e-9) + assert np.all(months.expected_npv >= low - 1e-9) + # Each failure's cost discounted from when it is expected to fall: + # $2,882.742, to within $0.0165 (the 36 windows' bracket of the + # method before gave $2,882.77 give or take $2.47). + assert months.npv == pytest.approx(2882.742, abs=5e-4) + assert months.npv_precision == pytest.approx(0.01646, abs=5e-5) + assert months.npv_precision <= 1e-3 * months.npv + finer = failures_by_period( + part, pump, "month", age=5200.0, discount=0.07, npv_tolerance=1e-5 + ) + assert abs(finer.npv - months.npv) <= months.npv_precision + assert finer.npv_precision <= 1e-5 * finer.npv + assert months.expected_npv.sum() == pytest.approx(months.npv, rel=1e-13) + assert months.total["expected_npv"] == months.npv + assert months.total["npv_precision"] == months.npv_precision + assert [round(float(x), 2) for x in months.expected_npv] == [ + 104.40, + 226.20, + 214.53, + 210.05, + 246.83, + 239.74, + 230.71, + 242.24, + 241.48, + 239.51, + 236.52, + 222.18, + 228.36, + ] + years = ends[-1] + assert months.eac == pytest.approx( + RATE * months.npv / (1 - math.exp(-RATE * years)) + ) + assert round(months.eac, 2) == 2869.51 + assert months.notes[-1] == ( + "Discounted to 2026-11-16 at 7% a year. The present values " + "(expected_npv, npv) discount the expected cost from when it is " + "expected to fall, to within 0.0165 in all; expected_cost and the " + "ranges are not discounted." + ) + json.dumps(months.to_dict()) + # no discount is the expected cost itself + zero = failures_by_period(part, pump, "month", age=5200.0, discount=0) + assert np.array_equal(zero.expected_npv, zero.expected_cost) + assert zero.npv == zero.total["expected_cost"] + assert zero.npv_precision == 0.0 + + +def test_constant_rate_in_calendar_time_against_the_closed_form(): + # A failure per 2,000 h, $1,000 each, replaced at once, in calendar + # time over 2027 (365 days): rate x cost x the integral of the + # discount factor, 0.5 (1 - exp(-r T)) / r with r an hour. + part = NonRepairable( + surv.Exponential.from_params([1 / 2000.0]), unplanned_cost=1000.0 + ) + usage = UsageForecast.calendar("2027-01-01", "2028-01-01") + r = RATE / 8766.0 + hours = 365 * 24.0 + exact = 0.5 * -math.expm1(-r * hours) / r + last = None + for tolerance in (1e-2, 1e-3, 1e-4): + quarters = failures_by_period( + part, + usage, + "quarter", + unit="hours", + discount=0.07, + npv_tolerance=tolerance, + ) + assert quarters.npv_precision <= tolerance * quarters.npv + assert abs(quarters.npv - exact) <= quarters.npv_precision + if last is not None: + assert quarters.npv_precision <= last + last = quarters.npv_precision + # each quarter against its own closed form + _, seconds = _period_edges(usage, "quarter") + t = np.r_[0.0, seconds / 3600.0] + by_quarter = 0.5 * np.diff(-np.expm1(-r * t)) / r + assert quarters.expected_npv == pytest.approx(by_quarter, rel=1e-4) + + +def calendar_years(operating): + """When the pump of the fixture reaches each operating hour, in years + from Monday 16 November 2026 00:00: 16 hours a weekday from 06:00.""" + week, rest = np.divmod(operating, 80.0) + day, hour = np.divmod(rest, 16.0) + return (week * 168.0 + day * 24.0 + 6.0 + hour) / 8766.0 + + +def test_the_present_value_holds_a_simulation(pump): + # 400,000 rings renewed at each failure over the forecast's 4,352 + # operating hours from age 5,200, each failure's $4,800 discounted + # from when the pump reaches that hour on its shifts. + rng = np.random.default_rng(48) + n, span = 400_000, 4352.0 + h0 = (5200.0 / 9000.0) ** 2.5 + t = 9000.0 * (h0 + rng.exponential(size=n)) ** 0.4 - 5200.0 + worth = np.zeros(n) + while True: + alive = t < span + if not alive.any(): + break + worth[alive] += 4800.0 * np.exp(-RATE * calendar_years(t[alive])) + t[alive] += 9000.0 * rng.weibull(2.5, alive.sum()) + se = worth.std() / np.sqrt(n) + part = ring(unplanned_cost=4800.0) + last = None + for tolerance in (5e-3, 1e-3, 1e-4): + months = failures_by_period( + part, + pump, + "month", + age=5200.0, + discount=0.07, + npv_tolerance=tolerance, + ) + assert months.npv_precision <= tolerance * months.npv + assert abs(worth.mean() - months.npv) < (4 * se + months.npv_precision) + if last is not None: + # the finer value is within the coarser one's precision + assert months.npv_precision <= last[1] + assert abs(months.npv - last[0]) <= last[1] + last = (months.npv, months.npv_precision) + assert abs(worth.mean() - months.npv) < 4 * se + + +def test_nothing_accrues_while_idle(pump): + days = failures_by_period( + ring(unplanned_cost=4800.0), pump, "day", age=5200.0, discount=0.07 + ) + # Sat 21 and Sun 22 Nov: no hours, no cost, no present value + assert days.operating[5:7].tolist() == [0.0, 0.0] + assert days.expected_npv[5:7].tolist() == [0.0, 0.0] + assert np.all(days.expected_npv[days.operating > 0] > 0.0) + assert np.all(days.expected_npv <= days.expected_cost) + months = failures_by_period( + ring(unplanned_cost=4800.0), pump, "month", age=5200.0, discount=0.07 + ) + # cut by day or by month, the same value, within the precisions + assert abs(days.npv - months.npv) <= ( + days.npv_precision + months.npv_precision + ) + + +def test_a_policy_as_a_present_value(pump): + part = ring(unplanned_cost=4800.0, planned_cost=900.0) + for resets in (True, False): + months = failures_by_period( + part, + pump, + "month", + age=1000.0, + every=3000.0, + resets=resets, + discount=0.07, + ) + _, seconds = _period_edges(pump, "month") + ends = seconds / 86400.0 / 365.25 + high = months.expected_cost * 1.07 ** -np.r_[0.0, ends[:-1]] + low = months.expected_cost * 1.07**-ends + assert np.all(months.expected_npv <= high + 1e-4) + assert np.all(months.expected_npv >= low - 1e-4) + assert months.npv_precision <= 1e-3 * months.npv + assert months.npv < months.total["expected_cost"] + # Block replacement: the planned $900 at 2,000 h on (3,000 less the + # 1,000 since the last) falls at one instant, in May 2027; that + # month's value holds it discounted from then. + at = float(calendar_years(np.array([2000.0]))[0]) + may = [s.strftime("%Y-%m") for s in months.starts].index("2027-05") + assert months.expected_planned[may] == pytest.approx(1.0) + assert months.expected_npv[may] > 900.0 * 1.07**-at + + +def test_a_part_with_no_cost_has_no_present_value(pump): + months = failures_by_period( + ring(), pump, "month", age=5200.0, discount=0.07 + ) + assert months.expected_npv is None and months.npv is None + assert months.eac is None and months.discount == 0.07 + assert months.notes[-1] == ( + "No present value: the part has no cost (give unplanned_cost=)." + ) + # A replacement that takes time is run to failure with failures' + # exact counts: its cost is discounted the same way. + slow = NonRepairable( + surv.Weibull.from_params([9000.0, 2.5]), + surv.Exponential.from_params([1 / 8.0]), + unplanned_cost=4800.0, + ) + months = failures_by_period(slow, pump, "month", age=5200.0, discount=0.07) + assert months.method == "exact" and months.cost_low is None + _, seconds = _period_edges(pump, "month") + ends = seconds / 86400.0 / 365.25 + high = months.expected_cost * 1.07 ** -np.r_[0.0, ends[:-1]] + low = months.expected_cost * 1.07**-ends + assert np.all(months.expected_npv <= high + 1e-9) + assert np.all(months.expected_npv >= low - 1e-9) + assert months.npv == pytest.approx(months.expected_npv.sum()) + assert 0.0 < months.npv_precision <= 1e-3 * months.npv + assert months.notes[-1].endswith( + f"to within {months.npv_precision:.3g} in all; expected_cost is " + "not discounted." + ) + with pytest.raises(ValueError, match="npv_tolerance must be a share"): + failures_by_period( + slow, pump, "month", discount=0.07, npv_tolerance=0.0 + ) + with pytest.raises(ValueError, match="yearly rate such as 0.07"): + failures_by_period(slow, pump, "month", discount=-0.07) + + +def test_a_forecast_short_of_the_tolerance_says_so(pump, monkeypatch): + # With two rounds of halving the most, 1e-7 is out of reach: the + # notes say how far it got. + from repyability.rbd import _common + + monkeypatch.setattr(_common, "_DISCOUNT_ROUNDS", 2) + months = failures_by_period( + ring(unplanned_cost=4800.0), + pump, + "month", + age=5200.0, + discount=0.07, + npv_tolerance=1e-7, + ) + assert 1e-7 * months.npv < months.npv_precision < 1e-3 * months.npv + assert any( + "short of npv_tolerance=1e-07: 2 rounds of halving is the most " + "worked out" in note + for note in months.notes + ) + assert abs(months.npv - 2882.741) <= months.npv_precision + 5e-4 + + +# ------------------------------------------------------------ UC-49 + + +def costed_pump(): + return RepairableRBD( + [("s", "pump"), ("pump", "t")], + { + "pump": { + "reliability": surv.Exponential.from_params([1 / 2000.0]), + "repairability": "instant", + "repair_cost": 1000.0, + } + }, + ) + + +def test_uc49_constant_rate_by_month_as_present_values(): + usage = UsageForecast.calendar("2027-01-01", "2028-01-01") + plain = events_by_period( + costed_pump(), usage, unit="hours", cost=True, seed=1, mc_samples=200 + ) + months = events_by_period( + costed_pump(), + usage, + unit="hours", + cost=True, + seed=1, + mc_samples=200, + discount=0.07, + ) + assert plain.discount is None and plain.expected_npv is None + assert plain.npv is None and plain.eac is None + assert np.array_equal(plain.cost.mean, months.cost.mean) + assert np.array_equal(plain.model_ends, months.model_ends) + # $0.50 an hour: 0.5 (1 - exp(-r T)) / r, r = ln(1.07) / 8,766 an hour + r = RATE / 8766.0 + to = [0.5 * -math.expm1(-r * hours) / r for hours in (744, 1416, 8760)] + assert [round(x, 2) for x in to] == [370.93, 704.15, 4235.21] + assert months.expected_npv[0] == pytest.approx(to[0], rel=1e-6) + assert months.expected_npv[1] == pytest.approx(to[1] - to[0], rel=1e-6) + assert months.npv == pytest.approx(to[2], rel=1e-7) + assert months.expected_npv.sum() == pytest.approx(months.npv) + # costs at a constant rate: the equivalent annual cost is the rate + assert months.eac == pytest.approx(0.5 * 8766.0, rel=1e-7) + assert months.notes[1].startswith( + "Discounted to 2027-01-01 at 7% a year. The present values " + "(expected_npv, npv) discount each cost from when it falls (exact); " + "cost (its mean and range) is not discounted" + ) + json.dumps(months.to_dict()) + # at no discount, the periods' means + zero = events_by_period( + costed_pump(), + usage, + unit="hours", + cost=True, + seed=1, + mc_samples=200, + discount=0, + ) + assert zero.expected_npv == pytest.approx(zero.cost.mean, rel=1e-9) + + +def test_events_present_value_is_expected_npvs_cost(): + # A unit that wears, takes time to repair, is replaced on a block + # schedule and costs while the system is down, with the diagram in + # days: the forecast's value is expected_npv's cost over the horizon. + rbd = RepairableRBD( + [("s", "a"), ("a", "t")], + { + "a": { + "reliability": surv.Weibull.from_params([200.0, 2.0]), + "repairability": surv.Exponential.from_params([1 / 2.0]), + "repair_cost": 700.0, + "preventive": { + "interval": 150.0, + "policy": "block", + "duration": surv.ExactEventTime.from_params([0.5]), + "cost": 120.0, + }, + } + }, + downtime_cost_rate=40.0, + ) + usage = UsageForecast.calendar("2027-01-01", "2029-01-01") + quarters = events_by_period( + rbd, + usage, + "quarter", + unit="days", + cost=True, + seed=2, + mc_samples=200, + discount=0.07, + ) + npv = rbd.expected_npv(731.0, discount_rate=RATE / 365.25) + assert quarters.npv == pytest.approx(npv.cost, rel=1e-7) + assert quarters.npv < float(np.sum(quarters.cost.mean)) + assert np.all(quarters.expected_npv <= quarters.cost.mean + 1e-9) + assert quarters.eac == pytest.approx(npv.eac * 365.25, rel=1e-7) + + +def test_events_discount_needs_cost(): + usage = UsageForecast.calendar("2027-01-01", "2028-01-01") + with pytest.raises(ValueError, match="with cost=True"): + events_by_period(costed_pump(), usage, unit="hours", discount=0.07) + with pytest.raises(ValueError, match="yearly rate such as 0.07"): + events_by_period( + costed_pump(), usage, unit="hours", cost=True, discount="7%" + ) diff --git a/repyability/tests/test_schedule_finds.py b/repyability/tests/test_schedule_finds.py new file mode 100644 index 00000000..e7701af6 --- /dev/null +++ b/repyability/tests/test_schedule_finds.py @@ -0,0 +1,429 @@ +"""What a test of a hidden failure is worth: ``task_value`` with +``Finds`` (UC-54 of ``repyability/schedule/README.md``). + +Checked against an exponential device's closed forms on the device's +clock, ``failure_finding_window`` in model time, and sums that must hold. +""" + +import json +import math +from datetime import date, datetime, timedelta + +import numpy as np +import pytest +import surpyval as surv + +from repyability import NonRepairable, failure_finding_window +from repyability.schedule import ( + DutyPlan, + Finds, + Recurrence, + Replaces, + Shifts, + Task, + UsageForecast, + task_value, +) +from repyability.tests.test_failure_finding_window import closed_form + +DAYS = 365.25 +RATE = math.log(1.07) # 7% a year, continuously, per year + + +def trip(): + """A trip failing hidden at 0.1 a year.""" + return NonRepairable(surv.Exponential.from_params([0.1])) + + +def trip_test(**options): + """Tested every 6 months from 1 January 2027, $400 a test.""" + options.setdefault("cost", 400.0) + return Task( + "trip test", + every=Recurrence.every(6, "months", "2027-01-01"), + **options, + ) + + +def finds(**options): + options.setdefault("demand_rate", 0.5) + options.setdefault("consequence_cost", 250_000.0) + options.setdefault("repair_cost", 3_000.0) + return Finds(trip(), **options) + + +@pytest.fixture(scope="module") +def three_years(): + return UsageForecast.calendar("2026-11-16", "2029-11-16") + + +def by_hand(tests, window, reveal, discount, price=400.0): + """Each side's cost from the closed form, in years: (with, without, + found, failed time with, failed time without).""" + demand, consequence, repair = 0.5, 250_000.0, 3_000.0 + each = consequence + (repair if reveal else 0.0) + shown = demand if reveal else 0.0 + q, failed, discounted = closed_form(0.1, tests, window, shown, discount) + factors = np.exp(-discount * np.array(tests)) + with_task = ( + price * factors.sum() + + repair * factors @ q + + each * demand * discounted + ) + _, never, never_discounted = closed_form(0.1, [], window, shown, discount) + return with_task, each * demand * never_discounted, q, failed, never + + +def test_uc54_six_monthly_trip_test(three_years): + tests = [d / DAYS for d in (46, 227, 411, 593, 777, 958)] + window = 1096 / DAYS + plain = task_value(trip_test(), finds(), three_years, unit="years") + assert [str(d) for d in plain.dates] == [ + "2027-01-01", + "2027-07-01", + "2028-01-01", + "2028-07-01", + "2029-01-01", + "2029-07-01", + ] + np.testing.assert_allclose(plain.model_times, tests, rtol=1e-12) + with_task, without, q, failed, never = by_hand(tests, window, True, 0.0) + total = plain.total + assert total["count"] == 6 + assert total["found"] == pytest.approx(q.sum(), rel=1e-9) + assert total["failures_with"] == pytest.approx(0.5 * failed, rel=1e-9) + assert total["failures_without"] == pytest.approx(0.5 * never, rel=1e-9) + assert total["unavailability_with"] == pytest.approx( + failed / window, rel=1e-9 + ) + assert total["unavailability_without"] == pytest.approx( + never / window, rel=1e-9 + ) + assert abs(total["with_task"] - with_task) <= plain.precision + assert abs(total["without_task"] - without) <= plain.precision + assert plain.precision < 1e-6 * without + # The README's numbers. + assert total["found"] == pytest.approx(0.2279, abs=5e-5) + assert total["failures_with"] == pytest.approx(0.0320, abs=5e-5) + assert total["failures_without"] == pytest.approx(0.1341, abs=5e-5) + assert total["with_task"] == pytest.approx(11_174.90, abs=0.01) + assert total["without_task"] == pytest.approx(33_931.58, abs=0.01) + assert total["value"] == pytest.approx(22_756.68, abs=0.01) + assert total["task_cost"] == 2400.0 and plain.eac is None + assert plain.total["with_task"] == plain.total["cost_with"] + + worth = task_value( + trip_test(), finds(), three_years, unit="years", discount=0.07 + ) + with_pv, without_pv, _, _, _ = by_hand(tests, window, True, RATE) + total = worth.total + assert total["task_cost"] == pytest.approx( + 400.0 * sum(1.07**-t for t in tests), rel=1e-12 + ) + assert abs(total["with_task"] - with_pv) <= worth.precision + assert abs(total["without_task"] - without_pv) <= worth.precision + assert abs(total["value"] - (without_pv - with_pv)) <= worth.precision + assert worth.precision < 2e-3 * without_pv + assert with_pv == pytest.approx(10_087.23, abs=0.01) + assert without_pv == pytest.approx(29_936.76, abs=0.01) + assert total["cost_with"] == plain.total["cost_with"] + assert set(worth.eac) == {"with_task", "without_task", "value"} + assert "never tested" in worth.without_words + assert "tests the device" in worth.does + json.dumps(worth.to_dict()) + + +def test_only_tests_find_a_failure(three_years): + """``demands_reveal=False``: without the task a failure is for good.""" + tests = [d / DAYS for d in (46, 227, 411, 593, 777, 958)] + window = 1096 / DAYS + found = task_value( + trip_test(), + finds(demands_reveal=False), + three_years, + unit="years", + discount=0.07, + ) + with_pv, without_pv, q, failed, never = by_hand(tests, window, False, RATE) + assert found.total["found"] == pytest.approx(q.sum(), rel=1e-9) + assert found.total["failures_without"] == pytest.approx( + 0.5 * never, rel=1e-9 + ) + assert never == pytest.approx( + window - (1 - math.exp(-0.1 * window)) / 0.1, rel=1e-12 + ) + assert abs(found.total["with_task"] - with_pv) <= found.precision + assert abs(found.total["without_task"] - without_pv) <= found.precision + assert "never found" in found.without_words + + +def test_matches_the_model_time_calculation(): + """Every 30 days in calendar time is every 720 h on a Weibull + device's clock, 1,000 h old: ``failure_finding_window``'s numbers, + its discount rate a year's as an hour's.""" + device = NonRepairable(surv.Weibull.from_params([6000.0, 1.8])) + task = Task( + "test", every=Recurrence.every(30, "days", "2027-01-11"), cost=50.0 + ) + usage = UsageForecast.calendar("2027-01-01", "2028-01-01") + does = Finds( + device, demand_rate=1e-3, consequence_cost=9_000.0, repair_cost=700.0 + ) + times = 240.0 + 720.0 * np.arange(12) + for discount, rate in ((None, 0.0), (0.07, RATE / (24.0 * DAYS))): + found = task_value(task, does, usage, age=1000.0, discount=discount) + prices = dict( + age=1000.0, + repair_cost=700.0, + demand_rate=1e-3, + consequence_cost=9_000.0, + discount_rate=rate, + ) + tested = failure_finding_window( + device, times, 8760.0, test_cost=50.0, **prices + ) + never = failure_finding_window(device, [], 8760.0, **prices) + np.testing.assert_allclose(found.model_times, times) + slack = found.precision + tested.precision + never.precision + assert found.total["found"] == pytest.approx( + tested.failures_found, rel=1e-9 + ) + assert found.total["cost_with"] == pytest.approx(tested.cost, rel=1e-9) + assert abs(found.total["with_task"] - tested.present_value) <= slack + assert abs(found.total["without_task"] - never.present_value) <= slack + if discount is None: + assert found.total["with_task"] == found.total["cost_with"] + assert found.total["without_task"] == pytest.approx( + never.cost, rel=1e-9 + ) + + +def test_uneven_dates_under_a_duty_plan(): + """The first Tuesday of each month on a pump that runs Mon-Fri 06:00 + to 22:00: the tests are at midnight, at uneven times on the pump's + clock, and demands come only while it runs. Against the closed form + on that clock, discounted by hand over each calendar day.""" + usage = DutyPlan(Shifts("Mon-Fri", "06:00", "22:00")).forecast( + "2026-11-16", "2027-12-01" + ) + task = Task( + "start test", + every=Recurrence.monthly(weekday="Tue", nth=1), + cost=120.0, + ) + rate, demand, consequence, repair = 2e-4, 1e-3, 20_000.0, 900.0 + device = NonRepairable(surv.Exponential.from_params([rate])) + does = Finds( + device, + demand_rate=demand, + consequence_cost=consequence, + repair_cost=repair, + ) + plain = task_value(task, does, usage) + assert plain.dates[:3] == ( + date(2026, 12, 1), + date(2027, 1, 5), + date(2027, 2, 2), + ) + assert len(plain.dates) == 12 + hours = [ + float(usage.model_time(datetime.combine(d, datetime.min.time()))) + for d in plain.dates + ] + np.testing.assert_allclose(plain.model_times, hours) + assert len(set(np.round(np.diff(hours)))) > 1 # 320 h and 400 h apart + window = float(usage.model_time(usage.end)) + q, failed, _ = closed_form(rate, hours, window, demand) + _, never, _ = closed_form(rate, [], window, demand) + assert plain.total["found"] == pytest.approx(q.sum(), rel=1e-9) + assert plain.total["failures_with"] == pytest.approx( + demand * failed, rel=1e-9 + ) + assert plain.total["failures_without"] == pytest.approx( + demand * never, rel=1e-9 + ) + + worth = task_value(task, does, usage, discount=0.07) + # By hand: each day's expected demands on a failed device (the closed + # form at the day's ends on the pump's clock) discounted at the day's + # start and at its end bracket the true value. + start = datetime(2026, 11, 16) + days = (datetime(2027, 12, 1) - start).days + stamps = [start + timedelta(days=d) for d in range(days + 1)] + clock = np.array([float(usage.model_time(s)) for s in stamps]) + k = rate + demand + + def failed_to(t, tests): + edges = np.array([0.0, *tests]) + since = t - edges[np.searchsorted(edges, t, side="right") - 1] + done = 0.0 + for a, b in zip(edges[:-1], edges[1:]): + if b <= t: + done += rate / k * ((b - a) + math.expm1(-k * (b - a)) / k) + return done + rate / k * (since + math.expm1(-k * since) / k) + + low = high = 0.0 + never_low = never_high = 0.0 + each = (consequence + repair) * demand + for day in range(days): + early, late = 1.07 ** (-day / DAYS), 1.07 ** (-(day + 1) / DAYS) + amount = failed_to(clock[day + 1], hours) - failed_to( + clock[day], hours + ) + low, high = low + each * amount * late, high + each * amount * early + amount = failed_to(clock[day + 1], []) - failed_to(clock[day], []) + never_low += each * amount * late + never_high += each * amount * early + lumps = sum( + (120.0 + repair * found) + * 1.07 ** (-(d - date(2026, 11, 16)).days / DAYS) + for d, found in zip(plain.dates, q) + ) + assert low + lumps <= worth.total["with_task"] <= high + lumps + assert never_low <= worth.total["without_task"] <= never_high + assert worth.total["task_cost"] == pytest.approx( + sum( + 120.0 * 1.07 ** (-(d - date(2026, 11, 16)).days / DAYS) + for d in plain.dates + ), + rel=1e-12, + ) + + +def test_tests_while_the_device_does_not_run(three_years): + """Two tests with no running between them are one test of the + device: both cost, and the second finds nothing.""" + usage = DutyPlan(Shifts("Mon-Fri", "06:00", "22:00")).forecast( + "2026-11-16", "2027-03-01" + ) + # Saturday and Sunday midnights: the pump last ran on Friday. + weekend = Task( + "start test", + every=Recurrence.weekly(["Sat", "Sun"]), + cost=10.0, + ) + saturdays = Task("start test", every=Recurrence.weekly(["Sat"]), cost=10.0) + device = NonRepairable(surv.Exponential.from_params([1e-3])) + does = Finds(device, demand_rate=1e-3, consequence_cost=5_000.0) + both = task_value(weekend, does, usage) + one = task_value(saturdays, does, usage) + assert both.total["count"] == 2 * one.total["count"] + assert both.total["found"] == pytest.approx(one.total["found"], rel=1e-12) + assert both.total["cost_with"] == pytest.approx( + one.total["cost_with"] + 10.0 * one.total["count"], rel=1e-12 + ) + + +def test_the_value_follows_the_prices(three_years): + """Dearer consequences make the tests worth more, dearer tests less; + with nothing at stake the value is minus the tests' cost, and it + changes sign at the test price that equals the saving.""" + + def value(**options): + cost = options.pop("cost", 400.0) + return task_value( + trip_test(cost=cost), + finds(**options), + three_years, + unit="years", + discount=0.07, + ) + + values = [ + value(consequence_cost=c).total["value"] + for c in (0.0, 1e3, 1e4, 1e5, 1e6) + ] + assert all(b > a for a, b in zip(values, values[1:])) + nothing = value(consequence_cost=0.0, repair_cost=0.0) + assert nothing.total["value"] == -nothing.total["task_cost"] < 0.0 + assert nothing.precision == 0.0 + free = value(cost=0.0) + dear = value(cost=4000.0) + assert free.total["value"] > value().total["value"] > dear.total["value"] + factors = value(cost=1.0).total["task_cost"] + break_even = free.total["value"] / factors + assert free.total["value"] > 0.0 + slack = 2.0 * free.precision + assert abs(value(cost=break_even).total["value"]) <= slack + assert value(cost=1.01 * break_even).total["value"] < 0.0 + assert value(cost=0.99 * break_even).total["value"] > 0.0 + # No demands: nothing to save. + idle = value(demand_rate=0.0) + assert idle.total["failures_without"] == 0.0 + assert idle.total["value"] < 0.0 + + +def test_periods_add_up(three_years): + months = task_value( + trip_test(), finds(), three_years, unit="years", discount=0.07 + ) + years = task_value( + trip_test(), + finds(), + three_years, + unit="years", + discount=0.07, + period="year", + ) + for found in (months, years): + for name in ( + "with_task", + "without_task", + "value", + "task_cost", + "cost_with", + "cost_without", + "failures_with", + "failures_without", + "failures_avoided", + "found", + ): + assert float(np.sum(getattr(found, name))) == pytest.approx( + found.total[name], rel=1e-12, abs=1e-12 + ) + np.testing.assert_allclose( + found.value, found.without_task - found.with_task + ) + assert np.all(found.unavailability_with <= 0.1) + # Each side is worked out on its own grid, to 1e-6 of itself + # (before the first test the two are the same curve). + assert np.all( + found.unavailability_with + <= found.unavailability_without * (1.0 + 1e-6) + ) + for name in ("cost_with", "cost_without", "found"): + assert months.total[name] == pytest.approx(years.total[name], rel=1e-9) + for name in ("with_task", "without_task", "value"): + assert months.total[name] == pytest.approx( + years.total[name], abs=months.precision + years.precision + ) + # Untested, the trip's unavailability climbs year on year. + assert np.all(np.diff(years.unavailability_without) > 0.0) + + +def test_a_replacement_has_no_hidden_failures(three_years): + part = NonRepairable( + surv.Weibull.from_params([3.0, 2.0]), unplanned_cost=100.0 + ) + found = task_value(trip_test(), Replaces(part), three_years, unit="years") + assert found.found is None and found.unavailability_with is None + assert "found" not in found.total + + +def test_refusals(three_years): + with pytest.raises(ValueError, match="what one test costs"): + task_value(trip_test(cost=None), finds(), three_years) + with pytest.raises(TypeError, match="NonRepairable"): + Finds( + surv.Exponential.from_params([0.1]), + demand_rate=1.0, + consequence_cost=1.0, + ) + with pytest.raises(TypeError, match="demand_rate"): + Finds(trip(), consequence_cost=1.0) + with pytest.raises(ValueError, match="demand_rate must be a number"): + Finds(trip(), demand_rate=-1.0, consequence_cost=1.0) + with pytest.raises(ValueError, match="demands_reveal"): + Finds(trip(), demand_rate=1.0, consequence_cost=1.0, demands_reveal=1) + with pytest.raises(TypeError, match="Finds\\(device"): + task_value(trip_test(), trip(), three_years) diff --git a/repyability/tests/test_schedule_forecast.py b/repyability/tests/test_schedule_forecast.py index 09958207..f682e695 100644 --- a/repyability/tests/test_schedule_forecast.py +++ b/repyability/tests/test_schedule_forecast.py @@ -432,10 +432,20 @@ def test_uc41_a_diagram_takes_the_dated_shuts(constant_pump): # two shuts in two years, $20,000 each spend = rbd.cost(17_520.0, mc_samples=200, seed=1) assert spend.by_category["shutdown"] == 40_000.0 - # the exact methods take shuts on a period only, and say so + # the values over a horizon take shuts at given times: the pump + # fails every 2,000 h whatever the shuts, which are counted as they + # start usage = UsageForecast.calendar("2026-11-14", "2027-12-01") - with pytest.raises(NotImplementedError, match="given times"): - events_by_period(rbd, usage, unit="hours") + events = events_by_period(rbd, usage, unit="hours") + hours = float(events.model_ends[-1]) + assert rbd.expected_events(hours).node_failures["pump"] == pytest.approx( + hours / 2000.0, rel=1e-6 + ) + assert rbd.expected_events(hours).shutdowns == 1 + assert len(events.model_ends) == 13 + # they end, so the long run refuses, and says what to ask for + with pytest.raises(NotImplementedError, match="given times, which end"): + rbd.mean_availability() # ---------------------------------------------- UC-42: two clocks' rate diff --git a/repyability/tests/test_schedule_services.py b/repyability/tests/test_schedule_services.py new file mode 100644 index 00000000..c18d920d --- /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) diff --git a/repyability/tests/test_schedule_value.py b/repyability/tests/test_schedule_value.py new file mode 100644 index 00000000..13fb481a --- /dev/null +++ b/repyability/tests/test_schedule_value.py @@ -0,0 +1,342 @@ +"""What a scheduled task is worth: ``task_value`` with ``Replaces``. + +The worked example is UC-50 of ``repyability/schedule/README.md``; the +rest check it against ``NonRepairable.renewal_forecast`` (block +replacement in model time), a constant rate's closed form, and a +simulation of both plans written out plainly here. +""" + +import json +import math + +import numpy as np +import pytest +import surpyval as surv + +from repyability import NonRepairable +from repyability.schedule import ( + DutyPlan, + Recurrence, + Replaces, + Shifts, + Task, + TaskValue, + Usage, + UsageForecast, + failures_by_period, + task_value, +) + +HOURS_A_YEAR = 24.0 * 365.25 + + +def ring(**costs): + """UC-38's wear ring: Weibull, scale 9,000 h, shape 2.5.""" + costs.setdefault("unplanned_cost", 4800.0) + return NonRepairable(surv.Weibull.from_params([9000.0, 2.5]), **costs) + + +def service(**options): + """A new ring at every 6-monthly service, from 1 December 2026.""" + options.setdefault("cost", 600.0) + return Task( + "new wear ring", + every=Recurrence.every(6, "months", "2026-12-01"), + **options, + ) + + +@pytest.fixture(scope="module") +def pump(): + """UC-32's pump: Mon-Fri 06:00-22:00 from Monday 16 Nov 2026.""" + return DutyPlan(Shifts("Mon-Fri", "06:00", "22:00")).forecast( + "2026-11-16", "2027-12-01", readings={"hours": 12_340.0} + ) + + +def test_uc50_wear_ring_six_monthly_service(pump): + plain = task_value(service(), Replaces(ring()), pump, age=5200.0) + assert isinstance(plain, TaskValue) + assert [str(d) for d in plain.dates] == ["2026-12-01", "2027-06-01"] + np.testing.assert_allclose(plain.model_times, [176.0, 2256.0]) + # By hand: 176 h from 5,200 h, then 2,080 h and 2,096 h from new. + by_hand = ( + ring().failures(176.0, age=5200.0).expected_failures + + ring().failures(2080.0).expected_failures + + ring().failures(2096.0).expected_failures + ) + assert plain.total["failures_with"] == pytest.approx(by_hand, rel=1e-12) + assert plain.total["failures_with"] == pytest.approx(0.0731, abs=5e-5) + assert plain.total["with_task"] == pytest.approx(1550.82, abs=0.005) + assert plain.total["without_task"] == pytest.approx(2987.56, abs=0.005) + assert plain.total["value"] == pytest.approx(1436.74, abs=0.01) + assert plain.total["failures_avoided"] == pytest.approx(0.549, abs=5e-4) + assert plain.total["count"] == 2 + np.testing.assert_allclose( + plain.failures_with[:8], + [0.0218, 0.0003, 0.0014, 0.0026, 0.0050, 0.0070, 0.0090, 0.0003], + atol=5e-5, + ) + np.testing.assert_array_equal(plain.task_cost[[1, 7]], [600.0, 600.0]) + assert plain.precision == 0.0 and plain.eac is None + # The same numbers as UC-38's run to failure. + rtf = failures_by_period(ring(), pump, age=5200.0) + np.testing.assert_allclose( + plain.failures_without, rtf.expected_failures, rtol=1e-6, atol=1e-9 + ) + + worth = task_value( + service(), Replaces(ring()), pump, age=5200.0, discount=0.07 + ) + assert worth.total["task_cost"] == pytest.approx(1176.83, abs=0.005) + # Inside the hand brackets, month by month. + assert 1516.22 <= worth.total["with_task"] <= 1517.84 + assert 2874.75 <= worth.total["without_task"] <= 2890.71 + assert 1356.92 <= worth.total["value"] <= 1374.49 + assert worth.precision < 1e-3 * worth.total["without_task"] + assert set(worth.eac) == {"with_task", "without_task", "value"} + assert "Without the task" in worth.without_words + json.dumps(worth.to_dict()) + assert "TaskValue('new wear ring'" in repr(worth) + + +def test_even_dates_match_renewal_forecast(): + """Every 30 days in calendar time is every 720 h: block replacement in + model time, which renewal_forecast works out from the same state.""" + part = NonRepairable( + surv.Weibull.from_params([3000.0, 2.5]), + planned_cost=500.0, + unplanned_cost=4000.0, + ) + task = Task("replace", every=Recurrence.every(30, "days", "2027-01-11")) + usage = UsageForecast.calendar("2027-01-01", "2028-01-01") + found = task_value(task, Replaces(part), usage, age=1000.0, discount=0) + assert found.model_times[0] == 240.0 + np.testing.assert_allclose(np.diff(found.model_times), 720.0) + plan = part.renewal_forecast( + 8760.0, 720.0, resets=False, age=1000.0, since_renewal=480.0 + ) + assert found.total["count"] == plan.expected_renewals == 12 + assert found.total["with_task"] == pytest.approx( + plan.expected_cost, rel=1e-6 + ) + assert found.total["failures_with"] == pytest.approx( + plan.expected_failures, rel=1e-6 + ) + assert found.total["without_task"] == pytest.approx( + 4000.0 * plan.expected_failures_without_renewals, rel=1e-9 + ) + assert found.precision == 0.0 + assert any("planned_cost, 500" in note for note in found.notes) + + +def test_constant_rate_task_only_costs(pump): + """Replacing a part whose rate is constant changes nothing but the + bill: the value is minus the task's own present value.""" + part = NonRepairable( + surv.Exponential.from_params([1 / 5000.0]), unplanned_cost=4800.0 + ) + worth = task_value( + service(), Replaces(part), pump, age=3000.0, discount=0.07 + ) + # Both sides are the closed form, the rate times the running hours, + # to NonRepairable.failures' own precision. Its count is the first + # unit's failures, exact, plus the later units', exact at the points + # of a grid (to 1e-16) and linear between them, of step h at most a + # thousandth of the life's median (_curves._POINT_STEPS). The later + # units' count, rate t - (1 - exp(-rate t)), is convex with second + # derivative at most rate**2, so a count from 0 is over by at most + # (rate h)**2 / 8 = (ln 2 / 1000)**2 / 8 = 6.0e-8, whatever the rate + # (5.97e-8 is found), an absolute error. A period's count is a + # difference of two such counts on each stretch it overlaps: within + # `bound` without the task, and 2 * bound with it (a period holds + # at most one task date, so overlaps two stretches). + bound = (math.log(2.0) / 1000.0) ** 2 / 8.0 + closed = np.diff(pump.model_time(list(worth.ends)), prepend=0.0) / 5000 + np.testing.assert_allclose(worth.failures_without, closed, atol=bound) + np.testing.assert_allclose(worth.failures_with, closed, atol=2 * bound) + # Each period's failure cost on the two sides then differs by at most + # 4800 * 3 * bound, discounted (a factor at most 1). + np.testing.assert_allclose( + worth.value, -worth.task_cost, atol=4800.0 * 3.0 * bound + ) + assert worth.total["value"] < 0.0 + by_hand = 600.0 * (1.07 ** (-15 / 365.25) + 1.07 ** (-197 / 365.25)) + assert worth.total["task_cost"] == pytest.approx(by_hand, rel=1e-12) + + +def _simulated(every, first, horizon, age, rng, runs): + """Each run's failures and their present value, at a continuous rate + of ln(1.07) a year with time in hours, for a Weibull(2000, 2.5) part + ``age`` old, renewed at ``first + k every`` (none if ``every`` is + None) and at each failure.""" + scale, shape = 2000.0, 2.5 + rate = math.log(1.07) / HOURS_A_YEAR + cuts = [] if every is None else list(np.arange(first, horizon, every)) + bounds = [0.0] + cuts + [horizon] + count = np.zeros(runs) + present = np.zeros(runs) + for k in range(len(bounds) - 1): + begin, end = bounds[k], bounds[k + 1] + t = np.full(runs, begin) + unit_age = np.full(runs, age if k == 0 else 0.0) + alive = np.ones(runs, bool) + while alive.any(): + # A life left at the unit's age, by inverting R(a + x) / R(a). + u = rng.random(alive.sum()) + a = unit_age[alive] + left = scale * ((a / scale) ** shape - np.log(u)) ** (1 / shape) + at = t[alive] + left - a + failed = at < end + index = np.flatnonzero(alive) + hit = index[failed] + count[hit] += 1 + present[hit] += np.exp(-rate * at[failed]) + t[hit] = at[failed] + unit_age[hit] = 0.0 + alive[index[~failed]] = False + return count, present + + +def test_wear_out_against_a_simulation(): + """A wear-out part with a dear failure: the task pays, and a seeded + simulation of both plans (not using the formulas) agrees.""" + part = NonRepairable( + surv.Weibull.from_params([2000.0, 2.5]), + planned_cost=300.0, + unplanned_cost=5000.0, + ) + task = Task("replace", every=Recurrence.every(30, "days", "2027-01-11")) + usage = UsageForecast.calendar("2027-01-01", "2027-07-01") + horizon = 181 * 24.0 + worth = task_value(task, Replaces(part), usage, age=1500.0, discount=0.07) + assert worth.total["value"] > 0.0 + rng = np.random.default_rng(20261120) + runs = 200_000 + with_n, with_pv = _simulated(720.0, 240.0, horizon, 1500.0, rng, runs) + without_n, without_pv = _simulated(None, 0.0, horizon, 1500.0, rng, runs) + planned = sum( + 300.0 * math.exp(-math.log(1.07) / HOURS_A_YEAR * t) + for t in np.arange(240.0, horizon, 720.0) + ) + for found, draws in ( + (worth.total["failures_with"], with_n), + (worth.total["failures_without"], without_n), + (worth.total["with_task"], 5000.0 * with_pv + planned), + (worth.total["without_task"], 5000.0 * without_pv), + ): + se = draws.std(ddof=1) / math.sqrt(runs) + assert abs(draws.mean() - found) < 4.0 * se + worth.precision + difference = 5000.0 * (without_pv - with_pv) - planned + se = difference.std(ddof=1) / math.sqrt(runs) + assert abs(difference.mean() - worth.total["value"]) < ( + 4.0 * se + worth.precision + ) + + +def test_periods_add_up(pump): + months = task_value( + service(), Replaces(ring()), pump, age=5200.0, discount=0.07 + ) + quarters = task_value( + service(), + Replaces(ring()), + pump, + age=5200.0, + discount=0.07, + period="quarter", + ) + for found in (months, quarters): + for name in ( + "with_task", + "without_task", + "value", + "task_cost", + "cost_with", + "cost_without", + "failures_with", + "failures_without", + "failures_avoided", + ): + assert float(np.sum(getattr(found, name))) == pytest.approx( + found.total[name], rel=1e-12, abs=1e-12 + ) + np.testing.assert_allclose( + found.value, found.without_task - found.with_task + ) + for name in ("cost_with", "cost_without", "task_cost"): + assert months.total[name] == pytest.approx( + quarters.total[name], rel=1e-9 + ) + for name in ("with_task", "without_task", "value"): + assert months.total[name] == pytest.approx( + quarters.total[name], + abs=months.precision + quarters.precision, + ) + + +def test_one_price(pump): + with pytest.raises(ValueError, match="costs 600 and the part's"): + task_value(service(), Replaces(ring(planned_cost=500.0)), pump) + with pytest.raises(ValueError, match="give the task's cost="): + task_value(service(cost=None), Replaces(ring()), pump) + agreed = task_value(service(), Replaces(ring(planned_cost=600.0)), pump) + taken = task_value( + service(cost=None), Replaces(ring(planned_cost=600.0)), pump + ) + assert agreed.total["with_task"] == taken.total["with_task"] + with pytest.raises(ValueError, match="unplanned_cost="): + task_value( + service(), + Replaces(NonRepairable(surv.Weibull.from_params([9000.0, 2.5]))), + pump, + ) + + +def test_what_is_not_a_replacement_is_refused(pump): + with pytest.raises(TypeError, match="Replaces"): + task_value(service(), ring(), pump) + with pytest.raises(TypeError, match="NonRepairable"): + Replaces(surv.Weibull.from_params([9000.0, 2.5])) + with pytest.raises(TypeError, match="Task"): + task_value("new wear ring", Replaces(ring()), pump) + + +def test_a_task_by_use_matches_block_replacement_in_model_time(pump): + """Every 2,000 running hours, last done at 11,840 h (500 h before the + forecast's 12,340 h): block replacement every 2,000 h in model time, + 500 h into the interval.""" + task = Task( + "new wear ring", + every=Usage(2000.0, "hours"), + last_done_reading=11_840.0, + cost=600.0, + ) + found = task_value(task, Replaces(ring()), pump, age=5200.0, discount=0) + np.testing.assert_allclose(found.model_times, [1500.0, 3500.0]) + plan = ring(planned_cost=600.0).renewal_forecast( + 4352.0, 2000.0, resets=False, age=5200.0, since_renewal=500.0 + ) + assert found.total["with_task"] == pytest.approx( + plan.expected_cost, rel=1e-6 + ) + assert found.total["failures_with"] == pytest.approx( + plan.expected_failures, rel=1e-6 + ) + # And by month, as failures_by_period's policy in model time. + policy = failures_by_period( + ring(planned_cost=600.0), + pump, + age=5200.0, + every=2000.0, + resets=False, + since_renewal=500.0, + discount=0.07, + ) + worth = task_value(task, Replaces(ring()), pump, age=5200.0, discount=0.07) + np.testing.assert_allclose( + worth.cost_with, policy.expected_cost, rtol=1e-5, atol=1e-6 + ) + assert worth.total["with_task"] == pytest.approx( + policy.npv, abs=worth.precision + policy.npv_precision + ) diff --git a/repyability/tests/test_shared_seeds.py b/repyability/tests/test_shared_seeds.py new file mode 100644 index 00000000..64de9f31 --- /dev/null +++ b/repyability/tests/test_shared_seeds.py @@ -0,0 +1,127 @@ +"""A result made of several runs on one seed, called without a seed, draws +that seed from numpy's global RNG (``rbd._streams.shared_seed``), so +``np.random.seed`` makes the call repeatable, and the result is the seeded +call of the seed drawn.""" + +import numpy as np +import pytest +import surpyval as surv +from surpyval import JointFrailty + +from repyability import RepairableRBD, RepairOrReplace +from repyability.rbd import _contract +from repyability.rbd._streams import shared_seed + +E = surv.Exponential.from_params +STEPS = surv.StepSchedule.from_changepoints +LINE = [("s", "p"), ("p", "t")] + + +def unseeded(call, k): + """``call()`` with numpy's global RNG seeded with ``k`` (restored + after), and the seed an unseeded call draws from it.""" + kept = np.random.get_state() + try: + np.random.seed(k) + drawn = shared_seed(None) + np.random.seed(k) + return call(), drawn + finally: + np.random.set_state(kept) + + +def pump(rate=1e-3): + return RepairableRBD( + LINE, + { + "p": { + "reliability": E([rate]), + "repairability": E([0.1]), + "repair_cost": 500.0, + } + }, + ) + + +def test_npv_distribution_draws_its_seed_from_the_global_rng(): + rbd = pump() + out, drawn = unseeded( + lambda: rbd.npv_distribution(500.0, value_rate=1.0, mc_samples=20), 3 + ) + assert out.seed == drawn + seeded = rbd.npv_distribution( + 500.0, value_rate=1.0, mc_samples=20, seed=drawn + ) + np.testing.assert_array_equal(out.samples, seeded.samples) + + +def test_compare_npv_draws_its_seed_from_the_global_rng(): + rbd, other = pump(), pump(2e-3) + out, drawn = unseeded( + lambda: rbd.compare_npv(other, 500.0, value_rate=1.0, mc_samples=20), + 4, + ) + assert out.seed == drawn + seeded = rbd.compare_npv( + other, 500.0, value_rate=1.0, mc_samples=20, seed=drawn + ) + assert out.mean == seeded.mean + + +def test_best_switch_time_draws_its_seed_from_the_global_rng(): + 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]) + rbd = RepairableRBD( + [("s", "a"), ("a", "t")], + { + "a": { + "reliability": model, + "repairability": E([1.0]), + "replace_cost": 80.0, + "covariates": STEPS([0.0], [[1.0]]), + } + }, + ) + rows, values = {"a": [[1.5], [1.0]]}, [1.5, 1.0] + options = dict(discount_rate=1e-3, mc_samples=20, scan=3) + out, drawn = unseeded( + lambda: rbd.best_switch_time(rows, values, 200.0, **options), 5 + ) + assert out.seed == drawn + seeded = rbd.best_switch_time(rows, values, 200.0, seed=drawn, **options) + np.testing.assert_array_equal(out.samples, seeded.samples) + + +@pytest.fixture(scope="module") +def fleet(): + truth = JointFrailty.from_params((100.0, 2.0), (400.0, 2.0), 0.5, 1.0) + model = JointFrailty.fit(**truth.random(60, end=250.0, random_state=2)) + return RepairOrReplace( + model, repair_cost=1.0, replacement_cost=10.0, failure_cost=2.0 + ) + + +def test_unit_decisions_draw_their_seed_from_the_global_rng(fleet): + ages = {0: 120.0, 1: 120.0} + out, drawn = unseeded(lambda: fleet.unit_decisions(ages, mc_samples=30), 6) + seeded = fleet.unit_decisions(ages, mc_samples=30, seed=drawn) + # repr, as a rule a unit cannot take has a cost rate of nan. + assert repr(out) == repr(seeded) + one, drawn = unseeded( + lambda: fleet.unit_decision(120.0, unit=0, mc_samples=30), 7 + ) + seeded = fleet.unit_decision(120.0, unit=0, mc_samples=30, seed=drawn) + assert repr(one) == repr(seeded) + + +def test_a_plan_request_draws_its_seed_from_the_global_rng(): + spec = { + "schema": _contract.SCHEMA, + "diagram": pump().to_dict(), + "analysis": "npv_distribution", + "inputs": {"horizon": 500.0}, + } + request, drawn = unseeded(lambda: _contract._checked(spec), 8) + assert request["inputs"]["seed"] == drawn diff --git a/repyability/tests/test_shock_nodes.py b/repyability/tests/test_shock_nodes.py new file mode 100644 index 00000000..33c94c54 --- /dev/null +++ b/repyability/tests/test_shock_nodes.py @@ -0,0 +1,354 @@ +"""Shocks that fail each member with a probability (`shock_nodes`): +against the alpha-factor group by rate for exponential members, closed +forms for members of other lives at their own ages, and the draws.""" + +from math import comb + +import numpy as np +import pytest +import surpyval as surv + +from repyability import ( + AlphaFactor, + BetaFactor, + CCFGroup, + NonRepairableRBD, + Shocks, + shock_nodes, +) + +X = np.array([0.0, 100.0, 3000.0, 20000.0]) + + +def parallel(names): + return [("s", n) for n in names] + [(n, "t") for n in names] + + +def aged(model, age, x): + return np.exp(-(model.Hf(age + x) - model.Hf(age))) + + +@pytest.mark.parametrize("p", [0.15, 0.4, 1.0]) +@pytest.mark.parametrize("lethal", [0.0, 7e-6]) +def test_exponential_members_are_an_alpha_factor_group_by_rate(p, lethal): + """A member fails at rate ``own + rate p`` (plus the lethal shocks'), + and the cause of each set of ``j`` members is the share ``rate p^j (1 + - p)^(m - j)`` of it: the alpha-factor model by rate, with ``alpha_j = + C(m - 1, j - 1)`` times that share (staggered testing).""" + own, rate, m = 1e-4, 3e-5, 3 + names = list("abc") + total = own + rate * p + lethal + share = {j: rate * p**j * (1 - p) ** (m - j) for j in range(1, m + 1)} + share[1] += own + share[m] += lethal + alphas = [comb(m - 1, j - 1) * share[j] / total for j in range(1, m + 1)] + assert sum(alphas) == pytest.approx(1.0, rel=1e-14) + group = NonRepairableRBD( + parallel(names), + {n: surv.Exponential.from_params([total]) for n in names}, + k={"t": 2}, + ccf_groups=[CCFGroup(names, AlphaFactor(alphas, basis="rate"))], + ) + edges, nodes = shock_nodes( + parallel(names), + {n: surv.Exponential.from_params([own]) for n in names}, + names, + rate, + p, + lethal_rate=lethal, + ) + written = NonRepairableRBD(edges, nodes, k={"t": 2}) + assert written.sf(X) == pytest.approx(group.sf(X), rel=1e-12, abs=0) + assert written.ff(X) == pytest.approx(group.ff(X), rel=1e-12, abs=0) + assert written.mean() == pytest.approx(group.mean(), rel=1e-9) + + +def test_lethal_shocks_alone_are_the_beta_factor_by_rate(): + own, lethal = 9e-5, 1e-5 + names = ["p1", "p2"] + edges, nodes = shock_nodes( + parallel(names), + {n: surv.Exponential.from_params([own]) for n in names}, + names, + rate=0.0, + lethal_rate=lethal, + ) + group = NonRepairableRBD( + parallel(names), + {n: surv.Exponential.from_params([own + lethal]) for n in names}, + ccf_groups=[ + CCFGroup(names, BetaFactor(lethal / (own + lethal), basis="rate")) + ], + ) + assert NonRepairableRBD(edges, nodes).sf(X) == pytest.approx( + group.sf(X), rel=1e-12, abs=0 + ) + # One cause: an exponential node after each member, the second a + # repeat of the first. + assert len(nodes) == 4 + + +def test_members_of_different_lives_and_ages_against_the_closed_form(): + """A parallel pair: the cause of both has not struck, and each member + has survived its own life from its age and the cause of it alone.""" + one = surv.Weibull.from_params([8000.0, 2.5]) + two = surv.LogNormal.from_params([9.0, 0.7]) + rate, p = 2e-5, 0.6 + names = ["p1", "p2"] + edges, nodes = shock_nodes( + parallel(names), {"p1": one, "p2": two}, names, rate, p + ) + rbd = NonRepairableRBD(edges, nodes) + both = np.exp(-rate * p * p * X) + alone = np.exp(-rate * p * (1 - p) * X) + for a1, a2 in ((0.0, 0.0), (6000.0, 1000.0)): + r1, r2 = aged(one, a1, X) * alone, aged(two, a2, X) * alone + closed = both * (1 - (1 - r1) * (1 - r2)) + assert rbd.sf_given_state(X, {"p1": a1, "p2": a2}) == pytest.approx( + closed, rel=1e-12, abs=0 + ) + assert rbd.sf(X) == pytest.approx( + rbd.sf_given_state(X, {}), rel=1e-15, abs=0 + ) + + +def test_two_of_three_against_every_combination_of_causes(): + """Sum over which of the seven causes have struck by ``x``.""" + life = surv.Weibull.from_params([8000.0, 2.5]) + rate, p, lethal = 3e-5, 0.3, 4e-6 + names, ages = list("abc"), {"a": 5000.0, "b": 2000.0, "c": 0.0} + edges, nodes = shock_nodes( + parallel(names), + {n: life for n in names}, + names, + rate, + p, + lethal_rate=lethal, + ) + rbd = NonRepairableRBD(edges, nodes, k={"t": 2}) + causes = [] + for mask in range(1, 8): + struck = {n for i, n in enumerate(names) if mask >> i & 1} + j = len(struck) + strikes = rate * p**j * (1 - p) ** (3 - j) + (lethal if j == 3 else 0) + causes.append((struck, strikes)) + own = {n: aged(life, ages[n], X) for n in names} + total = np.zeros_like(X) + for fired in range(2 ** len(causes)): + weight, down = np.ones_like(X), set() + for i, (struck, strikes) in enumerate(causes): + holds = np.exp(-strikes * X) + if fired >> i & 1: + weight, down = weight * (1 - holds), down | struck + else: + weight = weight * holds + up = [own[n] for n in names if n not in down] + if len(up) == 3: + a, b, c = up + works = a * b * c + a * b * (1 - c) + a * (1 - b) * c + works = works + (1 - a) * b * c + elif len(up) == 2: + works = up[0] * up[1] + else: + works = 0.0 + total = total + weight * works + assert rbd.sf_given_state(X, ages) == pytest.approx( + total, rel=1e-11, abs=0 + ) + + +def test_the_simulated_mean_covers_the_exact_one(): + life = surv.Weibull.from_params([8000.0, 2.5]) + names = list("abc") + edges, nodes = shock_nodes( + parallel(names), {n: life for n in names}, names, 3e-5, 0.3 + ) + rbd = NonRepairableRBD(edges, nodes, k={"t": 2}) + interval = rbd.mean_time_to_failure_interval(seed=0) + assert interval.lower <= rbd.mean() <= interval.upper + + +def test_members_in_different_branches_and_the_diagram_saved(): + """Each cause follows each of its members, wherever they are.""" + pump = surv.Weibull.from_params([8000.0, 2.5]) + valve = surv.Weibull.from_params([20000.0, 1.5]) + edges = [ + ("s", "p1"), + ("p1", "v1"), + ("v1", "t"), + ("s", "p2"), + ("p2", "v2"), + ("v2", "t"), + ] + models = {"p1": pump, "p2": pump, "v1": valve, "v2": valve} + rate, p = 2e-5, 0.5 + written, nodes = shock_nodes(edges, models, ["p1", "p2"], rate, p) + assert edges[0] == ("s", "p1") and set(models) == {"p1", "p2", "v1", "v2"} + rbd = NonRepairableRBD(written, nodes) + both = np.exp(-rate * p * p * X) + alone = np.exp(-rate * p * (1 - p) * X) + train = pump.sf(X) * valve.sf(X) * alone + # 1 - (1 - train)^2, written without the difference: at the last + # time a train survives with 1.5e-5, where that loses four digits. + closed = both * train * (2 - train) + assert rbd.sf(X) == pytest.approx(closed, rel=1e-12, abs=0) + again = NonRepairableRBD.from_dict(rbd.to_dict()) + assert again.sf(X) == pytest.approx(rbd.sf(X), rel=1e-15, abs=0) + # Two processes on one diagram, each with its own name. + more, nodes = shock_nodes(written, nodes, ["v1", "v2"], 1e-5, name="surge") + assert NonRepairableRBD(more, nodes).sf(X) == pytest.approx( + closed * np.exp(-1e-5 * X), rel=1e-12, abs=0 + ) + + +@pytest.mark.parametrize( + "arguments, message", + [ + ({"members": ["p1"]}, "2 to 10"), + ({"members": ["p1", "p1"]}, "twice"), + ({"members": ["p1", "zz"]}, "not one of the nodes"), + ({"rate": -1.0}, "rate must be"), + ({"rate": "1"}, "rate must be"), + ({"lethal_rate": float("inf")}, "lethal_rate must be"), + ({"p": 0.0}, "above 0 and at most 1"), + ({"p": 1.5}, "above 0 and at most 1"), + ({"p": True}, "above 0 and at most 1"), + ], +) +def test_what_cannot_be_written_is_refused(arguments, message): + life = surv.Weibull.from_params([8000.0, 2.5]) + given = {"members": ["p1", "p2"], "rate": 1e-5, **arguments} + with pytest.raises(ValueError, match=message): + shock_nodes(parallel(["p1", "p2"]), {"p1": life, "p2": life}, **given) + + +def test_a_name_in_use_and_a_repeat_as_a_member_are_refused(): + life = surv.Weibull.from_params([8000.0, 2.5]) + names = ["p1", "p2"] + edges, nodes = shock_nodes( + parallel(names), {n: life for n in names}, names, 1e-5 + ) + with pytest.raises(ValueError, match="name of its own"): + shock_nodes(edges, nodes, names, 1e-5) + with pytest.raises(ValueError, match="repeats node"): + shock_nodes(parallel(names), {"p1": life, "p2": "p1"}, names, 1e-5) + + +# The same shocks as a group's model: ``CCFGroup(members, Shocks(...))``. +def shocked_pair(): + one = surv.Weibull.from_params([8000.0, 2.5]) + two = surv.LogNormal.from_params([9.0, 0.7]) + names = ["p1", "p2"] + models = {"p1": one, "p2": two} + edges, nodes = shock_nodes( + parallel(names), models, names, 2e-5, 0.6, lethal_rate=1e-6 + ) + group = CCFGroup(names, Shocks(2e-5, 0.6, lethal_rate=1e-6)) + return ( + NonRepairableRBD(parallel(names), models, ccf_groups=[group]), + NonRepairableRBD(edges, nodes), + ) + + +def test_a_shocks_group_is_shock_nodes_to_the_last_bit(): + given, by_hand = shocked_pair() + state = {"p1": 6000.0, "p2": 1000.0} + assert list(given.nodes) == list(by_hand.nodes) + assert np.array_equal(given.sf(X), by_hand.sf(X)) + assert np.array_equal(given.ff(X), by_hand.ff(X)) + assert given.mean() == by_hand.mean() + assert given.bx_life(10) == by_hand.bx_life(10) + assert np.array_equal( + given.sf_given_state(X, state), by_hand.sf_given_state(X, state) + ) + assert given.remaining_life(0.9, state) == by_hand.remaining_life( + 0.9, state + ) + assert given.birnbaum_importance(2000.0) == by_hand.birnbaum_importance( + 2000.0 + ) + assert np.array_equal(given.random(50, seed=3), by_hand.random(50, seed=3)) + assert given.mean(method="simulate", seed=0) == by_hand.mean( + method="simulate", seed=0 + ) + assert given.analysis_routes() == by_hand.analysis_routes() + + +def test_a_shocks_group_is_saved_as_given(): + import json + + given, _ = shocked_pair() + saved = json.loads(json.dumps(given.to_dict())) + assert saved["ccf_groups"] == [ + { + "members": ["p1", "p2"], + "model": { + "kind": "shocks", + "rate": 2e-5, + "p": 0.6, + "lethal_rate": 1e-6, + }, + } + ] + assert len(saved["edges"]) == 4 + again = NonRepairableRBD.from_dict(saved) + assert np.array_equal(again.sf(X), given.sf(X)) + # A CCFGroup compares by identity: its members and model do not. + assert [(g.members, g.model) for g in again.shock_groups] == [ + (g.members, g.model) for g in given.shock_groups + ] + + +def test_two_shock_groups_and_a_group_of_another_model(): + life = surv.Exponential.from_params([1e-4]) + names = list("abcd") + edges = parallel(names) + models = {n: life for n in names} + rbd = NonRepairableRBD( + edges, + models, + ccf_groups=[ + CCFGroup(["a", "b"], Shocks(1e-5)), + CCFGroup(["c", "d"], BetaFactor(0.1, basis="rate")), + CCFGroup(["c", "d"], Shocks(2e-5, 0.5)), + ], + ) + written, nodes = shock_nodes( + edges, models, ["a", "b"], 1e-5, name="shock 1" + ) + written, nodes = shock_nodes( + written, nodes, ["c", "d"], 2e-5, 0.5, name="shock 2" + ) + by_hand = NonRepairableRBD( + written, + nodes, + ccf_groups=[CCFGroup(["c", "d"], BetaFactor(0.1, basis="rate"))], + ) + assert np.array_equal(rbd.sf(X), by_hand.sf(X)) + + +def test_the_shocks_model_checks_what_it_is_given(): + with pytest.raises(ValueError, match="rate above 0"): + Shocks(0.0) + with pytest.raises(ValueError, match="above 0 and at most 1"): + Shocks(1e-5, p=0.0) + with pytest.raises(ValueError, match="rate must be"): + Shocks(-1.0) + assert Shocks(1e-5, 0.5) == Shocks(1e-5, 0.5) + assert Shocks(1e-5, 0.5) != Shocks(1e-5, 0.6) + assert Shocks(3e-5, 0.5, 1e-6).causes(("a", "b")) == [ + (("a",), 7.5e-6), + (("b",), 7.5e-6), + (("a", "b"), 7.5e-6 + 1e-6), + ] + + +def test_a_fault_tree_refuses_a_shocks_group(): + from repyability import FaultTree + + with pytest.raises(ValueError, match="NonRepairableRBD"): + FaultTree( + {"top": ("AND", ["a", "b"])}, + {"a": 0.1, "b": 0.1}, + ccf_groups=[CCFGroup(["a", "b"], Shocks(1e-5))], + ) diff --git a/repyability/tests/test_shutdowns.py b/repyability/tests/test_shutdowns.py index 5009bd1f..3fc72492 100644 --- a/repyability/tests/test_shutdowns.py +++ b/repyability/tests/test_shutdowns.py @@ -308,13 +308,25 @@ def test_the_npv_discounts_each_shut_at_its_time(): # -- routes and engines ------------------------------------------------------- -def test_shuts_at_given_times_are_simulated(): +NO_LONG_RUN = ( + "Shutdown 'line' is at given times, which end, so the diagram has no " + "long run with it: ask for its values over a horizon " + "(expected_npv(horizon), expected_cost(T), mission_availability(T), " + "point_availability(t)), or give the shutdown a period for the long " + "run." +) + + +def test_shuts_at_given_times_have_no_long_run_and_are_simulated_too(): rbd = one(shutdown={"times": [20.0, 250.0], "duration": D, "cost": 1.0}) report = rbd.analysis_routes() assert report["mean_availability"].route == routes.REFUSED - assert "on a period" in report["mission_availability"].reason - with pytest.raises(NotImplementedError, match="on a period"): - rbd.mission_availability(100.0) + assert report["mean_availability"].reason == NO_LONG_RUN + assert report["expected_cost_rate"].reason == NO_LONG_RUN + with pytest.raises(NotImplementedError) as error: + rbd.mean_availability() + assert str(error.value) == NO_LONG_RUN + assert report["mission_availability"].route in ("exact", "numerical") run = rbd.availability(300.0, mc_samples=200, seed=1) assert run.shutdowns == 2 assert run.cost.by_category["shutdown"] == pytest.approx(2.0) @@ -323,6 +335,243 @@ def test_shuts_at_given_times_are_simulated(): assert run.mean_availability_interval().estimate < 1.0 - 2 * D / 300.0 +# -- outages at given times, over a horizon ----------------------------------- + + +def test_an_outage_holds_a_block_down_in_its_window_at_any_time(): + # The block's own process goes on through the outages (idle ageing): + # its own availability, but none inside a window. + times = [20.0, 250.0, 270.0] + rbd = one(shutdown={"times": times, "duration": D, "cost": 25.0}) + t = np.array([0.0, 19.0, 20.0, 29.9, 30.0, 100.0, 255.0, 265.0, 275.0]) + held = np.zeros(t.shape, dtype=bool) + for start in times: + held |= (t >= start) & (t < start + D) + np.testing.assert_allclose( + rbd.point_availability(t), np.where(held, 0.0, own(t)), atol=1e-9 + ) + # Each outage is charged at its start, and discounted from there. + rate = 2e-3 + cost = rbd.expected_cost(300.0, discount_rate=rate) + assert cost.by_category["shutdown"] == pytest.approx( + sum(25.0 * math.exp(-rate * start) for start in times), rel=1e-8 + ) + assert rbd.expected_events(260.0).shutdowns == 2 + + +@pytest.mark.parametrize( + "more", + [ + {}, + {"scope": ["a"]}, + {"scope": ["a", "b"], "idle_ageing": False}, + ], +) +def test_outages_at_a_period_s_times_are_the_shutdown_on_that_period(more): + def build(calendar): + return RepairableRBD( + [("s", "a"), ("a", "b"), ("b", "t")], + { + "a": { + "reliability": W([400, 2.0]), + "repairability": E([0.1]), + "repair_cost": 7.0, + "preventive": {"shutdown": "line", "cost": 3.0}, + }, + "b": { + "reliability": W([900, 1.5]), + "repairability": E([0.2]), + "repair_cost": 5.0, + }, + }, + shutdowns={ + "line": {"duration": 12.0, "cost": 100.0, **calendar, **more} + }, + downtime_cost_rate=2.0, + ) + + on_period = build({"period": 250.0}) + given = build({"times": [250.0, 500.0, 750.0, 1000.0]}) + t = np.linspace(0.0, 900.0, 181) + np.testing.assert_allclose( + given.point_availability(t), + on_period.point_availability(t), + rtol=0, + atol=1e-10, + ) + for T in (240.0, 262.0, 900.0): + assert given.expected_cost(T).mean == pytest.approx( + on_period.expected_cost(T).mean, rel=1e-10 + ) + mine = given.expected_npv(900.0, discount_rate=1e-3, value_rate=4.0) + theirs = on_period.expected_npv(900.0, discount_rate=1e-3, value_rate=4.0) + assert mine.npv == pytest.approx(theirs.npv, rel=1e-10) + events, others = given.expected_events(900.0), on_period.expected_events( + 900.0 + ) + assert events.node_preventive["a"] == pytest.approx( + others.node_preventive["a"], abs=1e-10 + ) + assert events.system_planned_downtime == pytest.approx( + others.system_planned_downtime, abs=1e-9 + ) + + +def test_one_outage_renewing_a_unit_is_its_replacement_there_and_the_shut(): + # The block renewed at the outage is the block replaced at that time, + # taking the outage's length; the outage adds its own cost, and holds + # the other block down for its length. + life, repair, T, d = W([300, 2.2]), E([0.05]), 180.0, 9.0 + other = {"reliability": E([1e-3]), "repairability": E([0.2])} + edges = [("s", "a"), ("a", "b"), ("b", "t")] + outage = RepairableRBD( + edges, + { + "a": { + "reliability": life, + "repairability": repair, + "repair_cost": 6.0, + "preventive": {"shutdown": "o", "cost": 40.0}, + }, + "b": other, + }, + shutdowns={"o": {"times": [T], "duration": d, "cost": 500.0}}, + ) + task = {"replace_at": [T], "duration": FIXED([d]), "cost": 40.0} + alone = RepairableRBD( + EDGES, + { + "a": { + "reliability": life, + "repairability": repair, + "repair_cost": 6.0, + "preventive": task, + } + }, + ) + t = np.array([50.0, 179.0, 180.0, 185.0, 188.9, 190.0, 260.0, 400.0]) + total = 1e-3 + 0.2 + b_up = 0.2 / total + 1e-3 / total * np.exp(-total * t) + held = (t >= T) & (t < T + d) + np.testing.assert_allclose( + outage.point_availability(t), + np.where(held, 0.0, alone.point_availability(t) * b_up), + atol=1e-9, + ) + rate = 1e-3 + mine = outage.expected_cost(400.0, discount_rate=rate) + theirs = alone.expected_cost(400.0, discount_rate=rate) + assert mine.by_component["a"] == pytest.approx(theirs.mean, rel=1e-10) + assert mine.by_category["shutdown"] == pytest.approx( + 500.0 * math.exp(-rate * T), rel=1e-8 + ) + assert outage.expected_events(400.0).shutdowns == 1 + + +def outages(): + """Three blocks, two outages lists: the line's (renewing a) and a + unit's own (renewing c, standing it still).""" + return RepairableRBD( + [("s", "a"), ("s", "b"), ("a", "c"), ("b", "c"), ("c", "t")], + { + "a": { + "reliability": W([300, 2.0]), + "repairability": E([0.08]), + "repair_cost": 60.0, + "preventive": {"shutdown": "line", "cost": 25.0}, + }, + "b": { + "reliability": W([250, 1.5]), + "repairability": E([0.1]), + "repair_cost": 40.0, + }, + "c": { + "reliability": W([900, 3.0]), + "repairability": E([0.15]), + "repair_cost": 200.0, + "preventive": {"shutdown": "unit", "cost": 80.0}, + }, + }, + shutdowns={ + "line": { + "times": [0.0, 140.0, 520.0], + "duration": 10.0, + "cost": 300.0, + }, + "unit": { + "times": [330.0], + "duration": 6.0, + "scope": ["c"], + "cost": 50.0, + "idle_ageing": False, + }, + }, + downtime_cost_rate=5.0, + ) + + +def test_outages_at_given_times_agree_with_the_simulation(): + rbd, T = outages(), 800.0 + run = rbd.availability(T, mc_samples=20_000, seed=7, **plain()) + interval = run.mean_availability_interval() + exact = rbd.mission_availability(T) + assert abs(interval.estimate - exact) <= Z * interval.standard_error + assert interval.standard_error < 5e-4 + cost = rbd.expected_cost(T) + assert abs(run.cost.sample_mean - cost.mean) <= Z * run.cost.sample_se + assert run.cost.sample_se < 0.005 * cost.mean + assert run.shutdowns == 4 == rbd.expected_events(T).shutdowns + # From a state, the outages are counted from now. + state = {"a": NodeState(age=200.0), "c": NodeState(alive=False)} + run = rbd.availability( + T, mc_samples=20_000, seed=8, state=state, **plain() + ) + interval = run.mean_availability_interval() + exact = rbd.mission_availability(T, state=state) + assert abs(interval.estimate - exact) <= Z * interval.standard_error + + +def test_what_the_exact_values_do_not_take_at_given_times_says_so(): + calendar = {"times": [20.0, 250.0], "duration": D} + tested = one({"inspection": {"shutdown": "line"}}, shutdown=calendar) + message = ( + "Component 'a' is tested at each shut of shutdown 'line', which is " + "at given times; the exact methods follow such a block at shuts on " + "a period (and a block renewed, or kept unless it is due, at every " + "shut at given times too). Estimate its values by simulation, with " + "availability() or cost()." + ) + with pytest.raises(NotImplementedError) as error: + tested.mission_availability(300.0) + assert str(error.value) == message + assert tested.analysis_routes()["expected_npv"].reason == message + kept = one( + { + "reliability": W([200, 2.0]), + "preventive": {"shutdown": "line", "older_than": 100.0}, + }, + shutdown=calendar, + ) + # A block kept unless it is due there is worked out stretch by + # stretch (see test_kept_at_given_times.py). + assert 0.0 < kept.mission_availability(300.0) < 1.0 + # A job that restores part-way is simulated. + restored = one( + { + "reliability": W([200, 2.0]), + "preventive": { + "shutdown": "line", + "restoration": {"model": "kijima1", "q": 0.5}, + }, + }, + shutdown=calendar, + ) + with pytest.raises(NotImplementedError, match="by simulation"): + restored.mission_availability(300.0) + run = restored.availability(300.0, mc_samples=50, seed=1) + assert run.shutdowns == 2 + + def test_what_does_not_take_shutdowns_refuses_them(): rbd = one() report = rbd.analysis_routes() diff --git a/repyability/tests/test_shutdowns_several.py b/repyability/tests/test_shutdowns_several.py new file mode 100644 index 00000000..63a37840 --- /dev/null +++ b/repyability/tests/test_shutdowns_several.py @@ -0,0 +1,292 @@ +"""A block renewed at several shutdowns (a list of names in its task's +``"shutdown"``): block replacement at every start of each, each renewal +taking its own shut's length (UC-59). + +The references are today's single shutdown (a list of one name is it), +one shutdown at the merged times (two shutdowns of one length are it), a +memoryless unit's two-state chain between renewals of their own lengths +written out here, and the simulation. +""" + +import json +import math + +import numpy as np +import pytest +import surpyval as surv + +from repyability import NodeState, RepairableRBD +from repyability.rbd import _compiled, _curves, _event_loop + +E = surv.Exponential.from_params +W = surv.Weibull.from_params +EDGES = [("s", "a"), ("a", "t")] +#: Standard errors a simulated estimate may be from the exact value. +Z = 4.0 + + +def one(life, shutdowns, names, repair=None, **task): + """One block renewed at the shutdowns ``names``, each holding it + alone off line.""" + return RepairableRBD( + EDGES, + { + "a": { + "reliability": life, + "repairability": repair or E([0.05]), + "repair_cost": 10.0, + "preventive": {"shutdown": names, "cost": 4.0, **task}, + } + }, + shutdowns=shutdowns, + downtime_cost_rate=2.0, + ) + + +#: A stop every 100 for 2 and an overhaul every 1000 for 20, from 550. +TWO = { + "stop": {"period": 100.0, "duration": 2.0}, + "overhaul": {"period": 1000.0, "offset": 550.0, "duration": 20.0}, +} + + +def plain(**more): + return dict(control_variate=False, conditional=False, **more) + + +# -- one shutdown ------------------------------------------------------------- + + +@pytest.mark.parametrize( + "shutdown", + [ + {"period": 300.0, "offset": 100.0, "duration": 5.0, "cost": 20.0}, + {"times": [120.0, 400.0, 610.0], "duration": 8.0, "cost": 20.0}, + ], +) +def test_a_list_of_one_shutdown_is_that_shutdown(shutdown): + life = W([300, 2.0]) + named = one(life, {"line": shutdown}, "line") + listed = one(life, {"line": shutdown}, ["line"]) + t = np.linspace(0.0, 900.0, 181) + np.testing.assert_allclose( + listed.point_availability(t), named.point_availability(t), atol=1e-10 + ) + for T in (260.0, 900.0): + assert listed.mission_availability(T) == pytest.approx( + named.mission_availability(T), abs=1e-10 + ) + assert listed.expected_cost(T).mean == pytest.approx( + named.expected_cost(T).mean, rel=1e-10 + ) + mine = listed.expected_npv(900.0, discount_rate=1e-3, value_rate=5.0) + theirs = named.expected_npv(900.0, discount_rate=1e-3, value_rate=5.0) + assert mine.npv == pytest.approx(theirs.npv, rel=1e-10) + + +# -- two shutdowns ------------------------------------------------------------ + + +def test_two_shutdowns_of_one_length_are_one_at_the_merged_times(): + life, d = W([300, 2.0]), 6.0 + shuts = { + "stop": {"period": 150.0, "duration": d, "cost": 7.0}, + "outage": {"times": [220.0, 500.0], "duration": d, "cost": 7.0}, + } + two = one(life, shuts, ["stop", "outage"]) + merged = sorted([150.0 * k for k in range(1, 7)] + [220.0, 500.0]) + single = one( + life, {"all": {"times": merged, "duration": d, "cost": 7.0}}, "all" + ) + t = np.linspace(0.0, 880.0, 177) + np.testing.assert_allclose( + two.point_availability(t), single.point_availability(t), atol=1e-10 + ) + for T in (300.0, 880.0): + assert two.mission_availability(T) == pytest.approx( + single.mission_availability(T), abs=1e-10 + ) + mine, theirs = two.expected_events(T), single.expected_events(T) + for key in ("node_failures", "node_preventive", "node_downtime"): + assert getattr(mine, key)["a"] == pytest.approx( + getattr(theirs, key)["a"], abs=1e-10 + ) + assert mine.shutdowns == theirs.shutdowns + mine = two.expected_npv(880.0, discount_rate=1e-3, value_rate=5.0) + theirs = single.expected_npv(880.0, discount_rate=1e-3, value_rate=5.0) + assert mine.npv == pytest.approx(theirs.npv, rel=1e-10) + + +def memoryless(t, renewals, lam, mu): + """The point availability of a unit of failure rate ``lam`` and repair + rate ``mu``, new at 0, renewed at each ``(time, length)`` of + ``renewals`` if it is up (back, as new, ``length`` later; one in a + repair carries on), and held off line in each ``[time, time + + length)``: a two-state chain between them.""" + total = lam + mu + + def from_up(s): + return mu / total + lam / total * np.exp(-total * s) + + def from_down(s): + return mu / total * (1.0 - np.exp(-total * s)) + + def value(parts, x): + return sum( + w * np.where(x >= s, from_up(x - s) if up else from_down(x - s), 0) + for w, s, up in parts + ) + + parts = [(1.0, 0.0, True)] + out = np.zeros_like(t) + held = np.zeros(t.shape, dtype=bool) + edges = [0.0] + [s for s, _ in renewals] + [math.inf] + for k, (start, end) in enumerate(zip(edges[:-1], edges[1:])): + inside = (t >= start) & (t < end) + out[inside] = value(parts, t[inside]) + if k == len(renewals): + break + length = renewals[k][1] + up = float(value(parts, np.array([end]))[0]) + assert all(s <= end for _, s, _ in parts), "a renewal past a gap" + parts = [(up, end + length, True), (1.0 - up, end, False)] + held |= (t >= end) & (t < end + length) + return np.where(held, 0.0, out) + + +def test_an_exponential_block_at_two_shutdowns_against_its_closed_form(): + lam, mu = 1 / 200.0, 1 / 20.0 + rbd = one(E([lam]), TWO, ["stop", "overhaul"], repair=E([mu])) + renewals = [(100.0 * k, 2.0) for k in range(1, 17)] + renewals = sorted(renewals + [(550.0, 20.0), (1550.0, 20.0)]) + # (Not within a grid step of the end of a renewal, where the curve + # bends between two points of its grid.) + t = np.array([0.0, 50.0, 99.9, 101.0, 103.0, 180.0, 549.9, 551.0, 571.0]) + t = np.concatenate([t, [600.0, 799.0, 1000.0, 1300.0, 1560.0, 1575.0]]) + expected = memoryless(t, renewals, lam, mu) + np.testing.assert_allclose(rbd.point_availability(t), expected, atol=2e-6) + # Each renewal, at its time, of a unit that is up just before. + up = [ + float(memoryless(np.array([s - 1e-9]), renewals, lam, mu)[0]) + for s, _ in renewals + if s < 1200.0 + ] + events = rbd.expected_events(1200.0) + assert events.node_preventive["a"] == pytest.approx(sum(up), abs=2e-5) + assert events.shutdowns == 12 + + +def test_the_simulation_agrees_from_new_and_from_a_state(): + rbd, T = one(W([300, 2.0]), TWO, ["stop", "overhaul"]), 1500.0 + plan = _event_loop._stream_plan(rbd, T, 0, False)[0] + assert _compiled.unsupported(rbd, plan, None, numba=True) == "shutdowns" + run = rbd.availability(T, mc_samples=20_000, seed=3, **plain()) + interval = run.mean_availability_interval() + exact = rbd.mission_availability(T) + assert abs(interval.estimate - exact) <= Z * interval.standard_error + assert interval.standard_error < 5e-4 + cost = rbd.expected_cost(T) + assert abs(run.cost.sample_mean - cost.mean) <= Z * run.cost.sample_se + state = {"a": NodeState(age=150.0)} + run = rbd.availability( + T, mc_samples=20_000, seed=4, state=state, **plain() + ) + interval = run.mean_availability_interval() + exact = rbd.mission_availability(T, state=state) + assert abs(interval.estimate - exact) <= Z * interval.standard_error + cost = rbd.expected_cost(T, state=state) + assert abs(run.cost.sample_mean - cost.mean) <= Z * run.cost.sample_se + + +def test_at_given_times_with_a_repair_going_on_agrees_with_the_simulation(): + shuts = { + "short": {"times": [80.0, 300.0, 520.0], "duration": 3.0}, + "long": {"times": [200.0, 410.0], "duration": 25.0, "cost": 50.0}, + } + rbd = one(W([250, 2.5]), shuts, ["short", "long"], repair=W([15, 1.5])) + state = {"a": NodeState(alive=False, down_for=4.0)} + T = 700.0 + run = rbd.availability( + T, mc_samples=20_000, seed=11, state=state, **plain() + ) + interval = run.mean_availability_interval() + exact = rbd.mission_availability(T, state=state) + assert abs(interval.estimate - exact) <= Z * interval.standard_error + cost = rbd.expected_cost(T, state=state) + assert abs(run.cost.sample_mean - cost.mean) <= Z * run.cost.sample_se + assert run.shutdowns == 5 == rbd.expected_events(T).shutdowns + + +# -- what is refused, and saving ---------------------------------------------- + + +def test_two_shutdowns_that_start_together_are_refused(): + shuts = { + "stop": {"period": 100.0, "duration": 2.0}, + "outage": {"times": [250.0, 400.0], "duration": 0.0}, + } + with pytest.raises(ValueError) as error: + one(W([300, 2.0]), shuts, ["stop", "outage"]) + assert str(error.value) == ( + "Component 'a' is renewed at shutdowns 'stop' and 'outage', which " + "both start at 400: which one's renewal is done there is not said. " + "Move one (its offset or times), or make them one shutdown." + ) + + +@pytest.mark.parametrize( + "task, what", + [ + ({"older_than": 100.0}, "older_than"), + ({"restore_to": 50.0}, "restore_to"), + ({"policy": "condition", "threshold": 0.1}, "threshold"), + ({"policy": "age"}, "policy 'age'"), + ], +) +def test_a_task_kept_unless_due_or_restoring_is_at_one_shutdown(task, what): + with pytest.raises(ValueError) as error: + one(W([300, 2.0]), TWO, ["stop", "overhaul"], **task) + assert str(error.value) == ( + "Component 'a' is renewed at several shutdowns ('stop', " + "'overhaul'), at every start of each (the 'block' policy); " + f"{what} is taken at one shutdown: give one shutdown, or leave it " + "out." + ) + + +def test_the_long_run_and_its_state_are_refused(): + rbd = one(W([300, 2.0]), TWO, ["stop", "overhaul"]) + message = ( + "Component 'a' is renewed at several shutdowns ('stop', " + "'overhaul'), whose renewals the long-run methods do not follow: " + "ask for its values over a horizon (expected_npv(horizon), " + "expected_cost(T), mission_availability(T), point_availability(t)), " + "or estimate the long run by simulation over a long horizon, with " + "availability() or cost()." + ) + with pytest.raises(NotImplementedError) as error: + rbd.mean_availability() + assert str(error.value) == message + routes = rbd.analysis_routes() + assert routes["expected_cost_rate"].reason == message + assert routes["replacement_cycle"].reason == message + assert routes["expected_npv"].route == "numerical" + route, how = _curves._node_over_time(rbd, "a") + assert route == "numerical" and "several shutdowns" in how + with pytest.raises(ValueError, match="no long-run state"): + rbd.mission_availability( + 100.0, state={"a": NodeState(stationary=True)} + ) + with pytest.raises(ValueError, match="which renewal it is in now"): + rbd.availability( + 100.0, + mc_samples=10, + state={"a": NodeState(alive=False, maintenance=True)}, + ) + + +def test_several_shutdowns_are_saved_and_loaded(): + rbd = one(W([300, 2.0]), TWO, ["stop", "overhaul"]) + back = RepairableRBD.from_dict(json.loads(json.dumps(rbd.to_dict()))) + assert back._preventive["a"].shutdown == ("stop", "overhaul") + assert back.mission_availability(900.0) == rbd.mission_availability(900.0) diff --git a/repyability/tests/test_small_probabilities.py b/repyability/tests/test_small_probabilities.py index 3c2af829..e2129e68 100644 --- a/repyability/tests/test_small_probabilities.py +++ b/repyability/tests/test_small_probabilities.py @@ -11,6 +11,7 @@ import numpy as np import pytest import surpyval as surv +from surpyval.univariate.regression import ProportionalOddsFitter from repyability import ( BetaFactor, @@ -241,7 +242,7 @@ def test_a_proportional_odds_node_along_a_schedule(): rng = np.random.default_rng(0) Z = rng.normal(size=(400, 1)) data = rng.weibull(1.8, size=400) * 80.0 * np.exp(-0.4 * Z[:, 0]) + 1e-3 - model = surv.ProportionalOddsFitter(surv.Weibull).fit(data, Z=Z) + model = ProportionalOddsFitter(surv.Weibull).fit(data, Z=Z) x = np.array([1e-6, 1e-3, 1.0, 50.0]) fixed = RegressionNode(model, covariates=[0.5]) varying = RegressionNode( diff --git a/repyability/tests/test_standby_cases.py b/repyability/tests/test_standby_cases.py index c09e8cd9..3d8b7085 100644 --- a/repyability/tests/test_standby_cases.py +++ b/repyability/tests/test_standby_cases.py @@ -141,10 +141,12 @@ def test_two_operating_with_a_spare_that_may_not_start(): def test_a_tiny_dormancy_is_exact_and_near_cold(): - # The hypoexponential stage rates are too close to separate: the chain - # takes it, and it is all but cold. + # The hypoexponential stage rates are all but equal: surpyval's + # Hypoexponential takes them from 0.29 (before, it refused, and the + # chain took them), and either way the answer is exact and all but + # cold. nearly = StandbyModel([UNIT] * 3, k=2, dormancy_factor=1e-12) - assert isinstance(nearly._sf_model, MarkovStandbySurvival) + assert model_route(nearly)[0] == "exact" cold = StandbyModel([UNIT] * 3, k=2) np.testing.assert_allclose(nearly.sf(T), cold.sf(T), rtol=1e-9) diff --git a/repyability/tests/test_switch_time_diagram.py b/repyability/tests/test_switch_time_diagram.py new file mode 100644 index 00000000..672917f9 --- /dev/null +++ b/repyability/tests/test_switch_time_diagram.py @@ -0,0 +1,202 @@ +"""The best time to switch blocks of a diagram from one way of running +them to another (``RepairableRBD.best_switch_time``), by simulation. + +A one-block diagram is the one unit ``best_switch_time`` works out +numerically, so its answer is checked against that one; a block that the +load does not touch, and that hardly fails, leaves the answer where the +loaded block's economics put it; and the search is seeded and its +intervals narrow with the runs. +""" + +import math + +import numpy as np +import pytest +import surpyval as surv + +from repyability import ( + RepairableRBD, + SimulatedSwitchTime, + best_switch_time, + operating_schedule_value, +) +from repyability.rbd import routes + +E = surv.Exponential.from_params +STEPS = surv.StepSchedule.from_changepoints +HORIZON = 200.0 +RATE = 0.001 +COST = 80.0 +# Run hot (load 1.5, earning 1.5 an hour) or cool (load 1, earning 1). +ROWS = [[1.5], [1.0]] +VALUES = [1.5, 1.0] + + +@pytest.fixture(scope="module") +def model(): + """A Weibull life that wears out (shape about 3) and lives about a + sixteenth as long at load 2 as at load 1.""" + 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 + return surv.WeibullPH.fit(x, Z=load[:, None]) + + +def _diagram(model, other=None): + components = { + "a": { + "reliability": model, + "repairability": E([1.0]), + "replace_cost": COST, + "covariates": STEPS([0.0], [[1.0]]), + } + } + edges = [("s", "a"), ("a", "t")] + if other is not None: + components["b"] = other + edges = [("s", "a"), ("a", "b"), ("b", "t")] + return RepairableRBD(edges, components) + + +def _search(rbd, **more): + options = dict(discount_rate=RATE, mc_samples=400, seed=11, scan=9) + options.update(more) + return rbd.best_switch_time({"a": ROWS}, VALUES, HORIZON, **options) + + +@pytest.fixture(scope="module") +def one_block(model): + return _search(_diagram(model)) + + +def test_one_block_agrees_with_the_one_unit_answer(model, one_block): + """Run hot while the unit is new, then cool: the numerical answer for + one unit switches at about 21 hours. The diagram of that unit finds + the same choice, each end's NPV within its interval, and the gain + over switching at once within the interval on the difference.""" + one = best_switch_time( + model, + ROWS, + VALUES, + HORIZON, + failure_cost=COST, + down_time=E([1.0]), + discount_rate=RATE, + tolerance=1e-4, + ) + got = one_block + assert isinstance(got, SimulatedSwitchTime) + assert one.choice == got.choice == "switch" + n = got.n_simulations + + def within(samples, want): + se = np.std(samples, ddof=1) / math.sqrt(n) + assert abs(samples.mean() - want) < 3.5 * se + + within(got.never_switch_samples, one.never_switch_npv) + within(got.switch_at_once_samples, one.switch_at_once_npv) + gain = got.difference_interval("switch at once", confidence=0.99) + assert gain.lower <= one.npv - one.switch_at_once_npv <= gain.upper + assert gain.lower > 0.0 + # The time found is as good, in the one-unit numbers, as the best to + # within the noise of the difference. + at_found = operating_schedule_value( + model, + [0.0, got.switch_time], + ROWS, + VALUES, + HORIZON, + failure_cost=COST, + down_time=E([1.0]), + discount_rate=RATE, + ) + assert one.npv - at_found.npv < 2.0 * gain.standard_error + # The scan audits the answer: every time valued, in order, ends + # included, its best the one returned. + assert got.times[0] == 0.0 and got.times[-1] == HORIZON + assert got.times == sorted(got.times) + assert got.npv == max(got.npvs) + assert got.npvs[got.times.index(got.switch_time)] == got.npv + + +def test_a_block_the_load_does_not_touch_leaves_the_answer(model, one_block): + """In series with a block that is not on the schedule and hardly + ever fails, the loaded block's runs are the same (its streams are + named as before), so the switch time is the one-block diagram's.""" + other = {"reliability": E([1e-6]), "repairability": E([10.0])} + got = _search(_diagram(model, other)) + assert got.switch_time == one_block.switch_time + assert got.choice == one_block.choice + assert got.npv == pytest.approx(one_block.npv, rel=1e-3) + + +def test_seeded_searches_repeat_and_narrow_with_more_runs(model): + rbd = _diagram(model) + few = _search(rbd, mc_samples=60, scan=3) + again = _search(rbd, mc_samples=60, scan=3) + assert few.times == again.times and few.npvs == again.npvs + np.testing.assert_array_equal(few.samples, again.samples) + more = _search(rbd, mc_samples=240, scan=3) + for against in ("never switch", "switch at once"): + narrow = more.difference_interval(against) + wide = few.difference_interval(against) + assert narrow.upper - narrow.lower < wide.upper - wide.lower + assert few.to_dict()["choice"] == few.choice + + +def test_value_rates_split_at_the_switch(model): + """With no costs and a block that never fails, the NPV is the value + alone: ``v1`` up to the switch and ``v2`` after, discounted.""" + rbd = RepairableRBD( + [("s", "a"), ("a", "t")], + { + "a": { + "reliability": model, + "repairability": E([1.0]), + "covariates": STEPS([0.0], [[1e-9]]), + } + }, + ) + # A load so light the unit outlives the horizon in every run. + got = rbd.best_switch_time( + {"a": [[-40.0], [-40.0]]}, + [2.0, 1.0], + HORIZON, + discount_rate=RATE, + mc_samples=20, + seed=1, + scan=3, + ) + assert got.choice == "never switch" + want = 2.0 * -math.expm1(-RATE * HORIZON) / RATE + assert got.npv == pytest.approx(want, rel=1e-12) + at_once = 1.0 * -math.expm1(-RATE * HORIZON) / RATE + assert got.switch_at_once_npv == pytest.approx(at_once, rel=1e-12) + + +def test_refusals_say_what_to_give(model): + plain = RepairableRBD( + [("s", "a"), ("a", "t")], + {"a": {"reliability": E([0.01]), "repairability": E([1.0])}}, + ) + with pytest.raises(routes.Refused, match="covariate schedule"): + plain.best_switch_time({"a": ROWS}, VALUES, HORIZON) + assert plain.analysis_routes()["best_switch_time"].route == ( + routes.REFUSED + ) + rbd = _diagram(model, {"reliability": E([0.01]), "repairability": E([1])}) + assert rbd.analysis_routes()["best_switch_time"].route == ( + routes.SIMULATED + ) + with pytest.raises(ValueError, match="'b' does not run on a covariate"): + rbd.best_switch_time({"b": ROWS}, VALUES, HORIZON) + with pytest.raises(ValueError, match="two rows"): + rbd.best_switch_time({"a": [[1.0]]}, VALUES, HORIZON) + with pytest.raises(ValueError, match="value_rates must be two"): + rbd.best_switch_time({"a": ROWS}, [1.0], HORIZON) + with pytest.raises(ValueError, match="covariates must be a dict"): + rbd.best_switch_time(ROWS, VALUES, HORIZON) + with pytest.raises(ValueError, match="scan"): + rbd.best_switch_time({"a": ROWS}, VALUES, HORIZON, scan=2) + with pytest.raises(ValueError, match="against"): + _search(rbd, mc_samples=5, scan=3).difference_interval("sometimes") diff --git a/repyability/tests/test_total_cost.py b/repyability/tests/test_total_cost.py index 2051acf6..7ee1bb23 100644 --- a/repyability/tests/test_total_cost.py +++ b/repyability/tests/test_total_cost.py @@ -221,7 +221,15 @@ def test_the_result_is_a_typed_mapping(): "method", "trains", "discount_rate", + "objective", + "value_rate", + "value", + "running_cost", + "npv", + "eac", + "basis", } + assert best.objective == "cost" and best.npv is None assert best.trains is None # none considered assert best.discount_rate == 0.0 assert best.total_cost == pytest.approx( diff --git a/repyability/tests/test_uncertainty_fitted_kinds.py b/repyability/tests/test_uncertainty_fitted_kinds.py index f875f958..6532c061 100644 --- a/repyability/tests/test_uncertainty_fitted_kinds.py +++ b/repyability/tests/test_uncertainty_fitted_kinds.py @@ -47,9 +47,7 @@ def generalised_renewal(): """A Kijima I process fitted to ten units' simulated histories (its restoration factor about 0.5, well inside its range).""" np.random.seed(3) - truth = surv.GeneralizedRenewal.fit_from_parameters( - [10.0, 2.0], 0.5, kijima="i" - ) + truth = surv.GeneralizedRenewal.from_params([10.0, 2.0], 0.5, kijima="i") data = truth.time_terminated_simulation_data(T=100, items=10) return surv.GeneralizedRenewal.fit(data.x, i=data.i, c=data.c, kijima="i") diff --git a/repyability/tests/test_unit_plan.py b/repyability/tests/test_unit_plan.py new file mode 100644 index 00000000..1fabc8c8 --- /dev/null +++ b/repyability/tests/test_unit_plan.py @@ -0,0 +1,351 @@ +"""A unit's maintenance plan (UC-63 of the maintenance README): specs and +plans state one node, and a diagram of plans is the diagram of specs.""" + +import json +import warnings + +import pytest +import surpyval as surv + +from repyability import RepairableRBD +from repyability.maintenance import ( + AgePolicy, + AtShutdown, + BlockPolicy, + ConditionPolicy, + ImperfectRepair, + Inspection, + Prices, + Restoration, + UnitPlan, + Upgrade, +) +from repyability.rbd import modular +from repyability.tests.test_catalogue import built +from repyability.tests.test_simulation_engines import identical, needs_numba + +#: The keys whose value at its default a plan leaves out of its spec. +_DEFAULTS = {"duration": "instant"} + + +def canonical(spec: dict, policy_default: str = "") -> dict: + """``spec`` with the keys at their defaults left out (None, an + ``"instant"`` duration, a task's policy where it is its default).""" + out = {} + for key, value in spec.items(): + if value is None or _DEFAULTS.get(key, object()) == value: + continue + if key in ("preventive", "inspection", "upgrade") and isinstance( + value, dict + ): + value = canonical(value) + if key == "preventive": + default = ( + "block" + if value.get("shutdown") is not None + or value.get("replace_at") is not None + else "age" + ) + if value.get("policy") == default: + value.pop("policy") + out[key] = value + return out + + +def same(a, b) -> bool: + """Whether ``a`` and ``b`` are one input: equal, or (a model built + afresh from one given, such as a fitted process's life) saved alike.""" + if a is b: + return True + if isinstance(a, dict) and isinstance(b, dict): + return set(a) == set(b) and all(same(a[k], b[k]) for k in a) + if hasattr(a, "to_dict") and type(a) is type(b): + return a.to_dict() == b.to_dict() + return bool(a == b) + + +def catalogue_specs(monkeypatch) -> list: + """Every spec dict a catalogue diagram is given, by diagram and node.""" + return [ + (f"{type(rbd).__name__} {i}, node {name!r}", component) + for i, (cls, rbd, components, _) in enumerate(built(monkeypatch)) + if cls is RepairableRBD + for name, component in components.items() + if isinstance(component, dict) and "reliability" in component + ] + + +def test_every_catalogue_spec_reads_into_a_plan_and_back(monkeypatch): + specs = catalogue_specs(monkeypatch) + assert len(specs) > 50 + for where, spec in specs: + plan = UnitPlan.from_spec(spec) + assert plan.spec() == canonical(spec), where + assert UnitPlan.from_spec(plan.spec()) == plan, where + + +def test_a_diagram_of_plans_is_the_diagram_of_specs(monkeypatch): + diagrams = [ + (rbd, components, options) + for cls, rbd, components, options in built(monkeypatch) + if cls is RepairableRBD + and any(isinstance(c, dict) for c in components.values()) + ] + monkeypatch.undo() + assert len(diagrams) > 30 + for rbd, components, options in diagrams: + plans = { + name: ( + UnitPlan.from_spec(c) + if isinstance(c, dict) and "reliability" in c + else c + ) + for name, c in components.items() + } + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + again = RepairableRBD(components=plans, **options) + for name, spec in rbd._init_args["components"].items(): + other = again._init_args["components"][name] + if isinstance(spec, dict): + spec, other = canonical(spec), canonical(other) + assert same(spec, other), name + if not isinstance(rbd._decomposition(), modular.GraphStructure): + # (A meshed one is built under a lowered step limit.) + with warnings.catch_warnings(): + # (A nested diagram's costs are warned of.) + warnings.simplefilter("ignore", UserWarning) + assert again.analysis_routes() == rbd.analysis_routes() + + +def pump_spec() -> dict: + return { + "reliability": surv.Weibull.from_params([1000.0, 2.5]), + "repairability": surv.Exponential.from_params([0.1]), + "repair_cost": 400.0, + "downtime_cost": 5.0, + "duty": 0.6, + "preventive": { + "policy": "age", + "interval": 4000.0, + "basis": "operating", + "cost": 20.0, + "duration": surv.ExactEventTime.from_params([4.0]), + }, + } + + +def pump_plan(spec: dict) -> UnitPlan: + return UnitPlan( + spec["reliability"], + spec["repairability"], + tasks=( + AgePolicy( + interval=4000.0, + cost=20.0, + duration=spec["preventive"]["duration"], + basis="operating", + ), + ), + prices=Prices(repair=400.0, downtime=5.0), + duty=0.6, + ) + + +def test_the_pump_of_the_use_case(): + spec = pump_spec() + plan = pump_plan(spec) + assert plan.spec() == canonical(spec) + assert UnitPlan.from_spec(spec) == plan + assert plan.task("preventive").basis == "operating" + assert plan.task("inspection") is None + + +def seeded_pair(engine: str): + spec = pump_spec() + edges = [("in", "pump"), ("pump", "valve"), ("valve", "out")] + valve = { + "reliability": surv.Exponential.from_params([1 / 3000.0]), + "repairability": surv.Exponential.from_params([0.2]), + "repair_cost": 50.0, + } + options = dict( + t_simulation=8000.0, + mc_samples=200, + seed=4, + engine=engine, + control_variate=False, + ) + of_specs = RepairableRBD(edges, {"pump": spec, "valve": valve}) + of_plans = RepairableRBD( + edges, {"pump": pump_plan(spec), "valve": UnitPlan.from_spec(valve)} + ) + return of_specs, of_plans, options + + +def test_seeded_runs_are_the_same_to_the_bit(): + of_specs, of_plans, options = seeded_pair("python") + identical( + of_specs.availability(**options), of_plans.availability(**options) + ) + identical(of_specs.cost(**options), of_plans.cost(**options)) + + +@needs_numba +def test_seeded_runs_are_the_same_on_the_compiled_engine(): + of_specs, of_plans, options = seeded_pair("numba") + identical( + of_specs.availability(**options), of_plans.availability(**options) + ) + python = seeded_pair("python") + identical( + python[1].availability(**python[2]), of_plans.availability(**options) + ) + + +def test_plans_read_back_from_a_diagram(): + spec = pump_spec() + rbd = RepairableRBD( + [("in", "pump"), ("pump", "out")], {"pump": pump_plan(spec)} + ) + assert rbd.plans == {"pump": pump_plan(spec)} + + +def test_a_plan_saves_and_loads(): + plan = UnitPlan( + surv.Weibull.from_params([500.0, 1.5]), + "instant", + tasks=( + BlockPolicy( + interval=200.0, + cost=3.0, + restoration=Restoration(q=0.4, model="kijima1"), + ), + ), + prices=Prices( + repair=10.0, replace=surv.LogNormal.from_params([1.5, 0.2]) + ), + imperfect_repair=ImperfectRepair(model="kijima2", q=0.5), + priority=2.0, + group="line", + ) + loaded = UnitPlan.from_dict(json.loads(json.dumps(plan.to_dict()))) + assert loaded.spec().keys() == plan.spec().keys() + assert loaded.task("preventive") == plan.task("preventive") + assert loaded.imperfect_repair == plan.imperfect_repair + assert loaded.prices.repair == 10.0 + assert loaded.prices.replace.params.tolist() == [1.5, 0.2] + # The diagram saves a plan node as its spec, which loads as the node. + rbd = RepairableRBD([("in", "a"), ("a", "out")], {"a": plan}) + assert RepairableRBD.from_dict(rbd.to_dict()).plans["a"].spec().keys() == ( + plan.spec().keys() + ) + + +@pytest.mark.parametrize( + "task, spec", + [ + (BlockPolicy(times=(10.0, 30.0)), {"replace_at": (10.0, 30.0)}), + ( + ConditionPolicy(interval=50.0, threshold=0.1, inspection_cost=1.0), + { + "policy": "condition", + "interval": 50.0, + "threshold": 0.1, + "inspection_cost": 1.0, + }, + ), + ( + AtShutdown(shutdown=["month", "year"], older_than=100.0), + {"shutdown": ["month", "year"], "older_than": 100.0}, + ), + ( + AtShutdown(shutdown="year", policy="condition", threshold=0.2), + {"policy": "condition", "shutdown": "year", "threshold": 0.2}, + ), + ( + AgePolicy(interval=100.0, restoration=Restoration(to_age=20.0)), + {"interval": 100.0, "restore_to": 20.0}, + ), + ( + AgePolicy( + interval=100.0, + restoration=Restoration( + q=1.1, replace_every=3, replacement_cost=9.0 + ), + ), + { + "interval": 100.0, + "restoration": {"model": "kijima2", "q": 1.1}, + "replace_every": 3, + "replacement_cost": 9.0, + }, + ), + ], +) +def test_each_task_is_its_spec(task, spec): + kind = "preventive" + plan = UnitPlan("life", "instant", tasks=(task,)) + assert plan.spec()[kind] == spec + assert UnitPlan.from_spec(plan.spec()) == plan + + +def test_inspection_and_upgrade_are_their_specs(): + plan = UnitPlan( + "life", + "instant", + tasks=( + Inspection( + interval=720.0, + offset=100.0, + coverage=0.9, + full_test=2160.0, + cost=5.0, + ), + Upgrade(at=250.0, life="new life", cost=50.0), + ), + ) + assert plan.spec()["inspection"] == { + "interval": 720.0, + "offset": 100.0, + "coverage": 0.9, + "full_test": 2160.0, + "cost": 5.0, + } + assert plan.spec()["upgrade"] == { + "at": 250.0, + "reliability": "new life", + "cost": 50.0, + } + assert UnitPlan.from_spec(plan.spec()) == plan + + +def test_refusals_say_what_to_do(): + with pytest.raises(ValueError, match=r"AtShutdown\(shutdown=\[\.\.\.\]\)"): + UnitPlan( + "life", + "instant", + tasks=(AgePolicy(interval=1.0), BlockPolicy(interval=2.0)), + ) + with pytest.raises(TypeError, match="must be one of AgePolicy"): + UnitPlan("life", "instant", tasks=({"interval": 1.0},)) + with pytest.raises(ValueError, match="needs the unit's life"): + UnitPlan(None) + with pytest.raises(ValueError, match="one of q .* to_age .* process"): + Restoration(q=0.5, to_age=10.0) + with pytest.raises(ValueError, match=r"\['intervall'\].*spelling"): + UnitPlan.from_spec( + {"reliability": "life", "preventive": {"intervall": 3.0}} + ) + with pytest.raises(ValueError, match=r"\['repair_costs'\]"): + UnitPlan.from_spec({"reliability": "life", "repair_costs": 3.0}) + with pytest.raises(TypeError, match="prices are a Prices"): + UnitPlan("life", prices=3.0) + # A plan is checked by the diagram as its spec is, naming the node. + plan = UnitPlan( + surv.Weibull.from_params([500.0, 1.5]), + "instant", + tasks=(AgePolicy(interval=-1.0),), + ) + with pytest.raises(ValueError, match="Component 'a': the preventive"): + RepairableRBD([("in", "a"), ("a", "out")], {"a": plan}) diff --git a/repyability/tests/test_units.py b/repyability/tests/test_units.py index 39d0e274..d9f70a03 100644 --- a/repyability/tests/test_units.py +++ b/repyability/tests/test_units.py @@ -176,9 +176,15 @@ def test_every_scaled_distribution_is_checked(): assert set(PARAMETERS) == set(_SCALED) +@pytest.mark.parametrize("own", [True, False]) @pytest.mark.parametrize("name", sorted(PARAMETERS)) -def test_a_life_on_the_calendar(name): - # Operating a fraction d of the time, R_c(t) = R(d t). +def test_a_life_on_the_calendar(name, own, monkeypatch): + # Operating a fraction d of the time, R_c(t) = R(d t): by the model's + # own rescaling where surpyval has it, else by _SCALED (surpyval 0.28). + if not own: + monkeypatch.delattr(surv.Parametric, "rescale_time", raising=False) + elif not hasattr(surv.Parametric, "rescale_time"): + pytest.skip("this surpyval does not rescale a model's time") model = getattr(surv, name).from_params(PARAMETERS[name]) d, t = 0.3, np.array([5.0, 40.0, 90.0, 150.0]) moved = on_calendar("a", model, d) @@ -193,6 +199,22 @@ def test_a_life_on_the_calendar(name): ) +def test_a_mixture_on_the_calendar(): + # Any model that rescales itself takes a duty, not only those _SCALED + # moves. + mixture = surv.MixtureModel.from_params( + surv.Weibull, [[100.0, 2.0], [400.0, 1.5]], [0.3, 0.7] + ) + if not hasattr(mixture, "rescale_time"): + pytest.skip("this surpyval does not rescale a mixture's time") + d, t = 0.3, np.array([5.0, 40.0, 90.0, 150.0]) + np.testing.assert_allclose( + np.ravel(on_calendar("a", mixture, d).sf(t / d)), + np.ravel(mixture.sf(t)), + rtol=1e-12, + ) + + def duty_rbd(life, duty, **more): spec = {"reliability": life, "repairability": E([0.5]), **more} if duty is not None: diff --git a/repyability/tests/test_upgrade_long_run.py b/repyability/tests/test_upgrade_long_run.py new file mode 100644 index 00000000..60bc1e89 --- /dev/null +++ b/repyability/tests/test_upgrade_long_run.py @@ -0,0 +1,118 @@ +"""The long run of a diagram with an upgrade: once upgraded, each +upgraded component has its new life for ever, so the long-run methods +give the values of the diagram built with that life (the time before +the upgrade, and its capital cost, ignored).""" + +import numpy as np +import pytest +import surpyval as surv + +from repyability import RepairableRBD +from repyability.rbd import routes + +E = surv.Exponential.from_params +W = surv.Weibull.from_params +EDGES = [("s", "a"), ("a", "b"), ("b", "t")] +OLD, NEW = W([300.0, 2.0]), W([500.0, 2.5]) + + +def diagram(a_life, upgraded=False, block=True): + a = { + "reliability": a_life, + "repairability": E([0.05]), + "repair_cost": 40.0, + } + if block: + a["preventive"] = {"policy": "block", "interval": 200.0, "cost": 5.0} + if upgraded: + a["upgrade"] = {"at": 1000.0, "reliability": NEW, "cost": 900.0} + b = {"reliability": E([1e-3]), "repairability": E([0.1])} + return RepairableRBD(EDGES, {"a": a, "b": b}, downtime_cost_rate=3.0) + + +LONG_RUN = [ + ("mean_availability", ()), + ("mean_unavailability", ()), + ("expected_cost_rate", ()), + ("system_failure_frequency", ()), + ("mean_time_between_failures", ()), + ("mean_up_time", ()), + ("mean_down_time", ()), + ("node_availability", ()), + ("birnbaum_importance", ()), + ("risk_achievement_worth", ()), + ("replacement_cycle", ("a",)), +] + + +@pytest.mark.parametrize("block", [True, False]) +@pytest.mark.parametrize("name, args", LONG_RUN) +def test_the_long_run_is_the_diagram_built_with_the_new_life( + name, args, block +): + if name == "replacement_cycle" and not block: + pytest.skip("a cycle is block replacement's") + upgraded = diagram(OLD, upgraded=True, block=block) + built = diagram(NEW, block=block) + ours = getattr(upgraded, name)(*args) + theirs = getattr(built, name)(*args) + if isinstance(ours, dict): + assert ours.keys() == theirs.keys() + for key in ours: + assert ours[key] == pytest.approx(theirs[key], rel=1e-12) + elif isinstance(ours, float): + assert ours == pytest.approx(theirs, rel=1e-12) + else: + a, b = ours.to_dict(), theirs.to_dict() + assert a.keys() == b.keys() + for key in a: + np.testing.assert_allclose(a[key], b[key], rtol=1e-12) + assert upgraded.analysis_routes()[name].route == ( + built.analysis_routes()[name].route + ) + + +def test_a_memoryless_unit_upgraded_in_closed_form(): + lam, new, mu = 0.01, 0.002, 0.5 + rbd = RepairableRBD( + [("s", "a"), ("a", "t")], + { + "a": { + "reliability": E([lam]), + "repairability": E([mu]), + "upgrade": {"at": 50.0, "reliability": E([new])}, + } + }, + ) + assert rbd.mean_availability() == pytest.approx(mu / (new + mu), 1e-12) + assert rbd.system_failure_frequency() == pytest.approx( + new * mu / (new + mu), 1e-12 + ) + + +def test_the_routes_say_the_long_run_is_once_upgraded(): + rbd = diagram(OLD, upgraded=True) + report = rbd.analysis_routes() + route = report["mean_availability"] + assert route.route in (routes.EXACT, routes.NUMERICAL) + assert route.reason.startswith( + "The long run once upgraded (each upgraded component with its new " + "life, the time before its upgrade ignored): " + ) + # Over a horizon the upgrade is followed as before. + assert report["expected_npv"].route == routes.NUMERICAL + assert report["total_cost"].route == routes.REFUSED + with pytest.raises(NotImplementedError, match="once upgraded"): + rbd.total_cost(100.0) + + +def test_values_over_time_still_follow_the_upgrade(): + """Asked at times, an importance measure follows the diagram with its + upgrade, not the diagram after it.""" + rbd, built = diagram(OLD, upgraded=True), diagram(NEW) + early = rbd.birnbaum_importance(x=np.array([100.0]))["b"] + after = built.birnbaum_importance(x=np.array([100.0]))["b"] + before = diagram(OLD).birnbaum_importance(x=np.array([100.0]))["b"] + # Before the upgrade, the diagram is the one with the old life. + np.testing.assert_allclose(early, before, rtol=1e-10) + assert not np.allclose(early, after, rtol=1e-6) diff --git a/repyability/tests/test_upgrade_maintenance.py b/repyability/tests/test_upgrade_maintenance.py new file mode 100644 index 00000000..a86143cb --- /dev/null +++ b/repyability/tests/test_upgrade_maintenance.py @@ -0,0 +1,194 @@ +"""Block replacement on an upgraded component (UC-60): replaced every +interval with the life in service, and at the upgrade's time as at a +block time, the units from the upgrade on of the new life. + +The references are block replacement alone (an upgrade to the same life +at a block time is nothing more), a plan of replacements at the merged +times (an upgrade to the same life between block times is one more +replacement), a memoryless unit's two-state chain between replacements +whose rate changes at the upgrade, and the simulation. +""" + +import math + +import numpy as np +import pytest +import surpyval as surv + +from repyability import NodeState, RepairableRBD + +E = surv.Exponential.from_params +W = surv.Weibull.from_params +FIXED = surv.ExactEventTime.from_params +EDGES = [("s", "a"), ("a", "t")] +LIFE = W([300, 2.0]) +TASK = {"policy": "block", "interval": 150.0, "cost": 10.0} +Z = 4.0 + + +def one(life=LIFE, repair=None, **more): + return RepairableRBD( + EDGES, + { + "a": { + "reliability": life, + "repairability": E([0.05]) if repair is None else repair, + "repair_cost": 6.0, + **more, + } + }, + ) + + +def agree(mine, theirs, T, atol=1e-10, npv=True): + t = np.linspace(0.0, T, 101) + np.testing.assert_allclose( + mine.point_availability(t), theirs.point_availability(t), atol=atol + ) + a, b = mine.expected_events(T), theirs.expected_events(T) + for key in ("node_failures", "node_preventive"): + assert getattr(a, key)["a"] == pytest.approx( + getattr(b, key)["a"], abs=atol + ) + if not npv: + return + assert mine.expected_npv( + T, discount_rate=1e-3, value_rate=3.0 + ).npv == pytest.approx( + theirs.expected_npv(T, discount_rate=1e-3, value_rate=3.0).npv, + rel=1e-10, + ) + + +@pytest.mark.parametrize("duration", [None, FIXED([3.0])]) +def test_an_upgrade_to_the_same_life_at_a_block_time_is_block_replacement( + duration, +): + task = TASK if duration is None else {**TASK, "duration": duration} + upgraded = one(preventive=task, upgrade={"at": 450.0, "reliability": LIFE}) + # Its curve and events are block replacement's; its NPV is integrated + # on a plan's stretches, as the same plan of block times is. + agree(upgraded, one(preventive=task), 1000.0, npv=False) + plan = {key: value for key, value in task.items() if key != "interval"} + plan["replace_at"] = [150.0 * k for k in range(1, 7)] + plan.pop("policy") + agree(upgraded, one(preventive=plan), 1000.0) + + +def test_between_block_times_it_is_one_more_replacement(): + task = {**TASK, "duration": FIXED([3.0])} + upgraded = one(preventive=task, upgrade={"at": 400.0, "reliability": LIFE}) + times = sorted([150.0 * k for k in range(1, 8)] + [400.0]) + plan = one( + preventive={ + "replace_at": times, + "cost": 10.0, + "duration": FIXED([3.0]), + } + ) + agree(upgraded, plan, 1000.0) + + +def chain(t, renewals, rate_at, mu, d): + """A memoryless unit, new at 0, repaired at rate ``mu``, replaced in + ``d`` at each of ``renewals`` if it is up (a unit in a repair + carries on), failing at ``rate_at(s)`` in the stretch from ``s``: + in each stretch, the units in a repair at its start follow the + chain from down, and those replaced the chain from up once back.""" + + def chain_at(rate, s, up): + total = rate + mu + return mu / total + (up - mu / total) * np.exp(-total * s) + + out = np.zeros_like(t) + edges = [0.0] + list(renewals) + [math.inf] + replaced, wait = 1.0, 0.0 # new at 0: as replaced, back at once + + def value(rate, s): + back = np.where( + s >= wait, replaced * chain_at(rate, np.maximum(s - wait, 0), 1), 0 + ) + return (1.0 - replaced) * chain_at(rate, s, 0.0) + back + + for begin, end in zip(edges[:-1], edges[1:]): + rate = rate_at(begin) + inside = (t >= begin) & (t < end) + out[inside] = value(rate, t[inside] - begin) + if not math.isfinite(end): + break + replaced, wait = float(value(rate, np.array(end - begin))), d + return out + + +def test_a_memoryless_unit_against_its_chain(): + lam, new, mu, d, at = 1 / 200.0, 1 / 800.0, 1 / 10.0, 4.0, 400.0 + rbd = one( + E([lam]), + E([mu]), + preventive={**TASK, "duration": FIXED([d])}, + upgrade={"at": at, "reliability": E([new])}, + ) + renewals = sorted([150.0 * k for k in range(1, 7)] + [at]) + t = np.array([0.0, 100.0, 149.9, 151.0, 160.0, 399.9, 401.0]) + t = np.concatenate([t, [420.0, 500.0, 601.0, 700.0, 899.0]]) + + def rate_at(s): + return lam if s < at else new + + np.testing.assert_allclose( + rbd.point_availability(t), + chain(t, renewals, rate_at, mu, d), + atol=2e-6, + ) + + +def test_the_simulation_agrees_from_new_and_from_a_state(): + rbd = one( + preventive={**TASK, "duration": FIXED([3.0])}, + upgrade={"at": 400.0, "reliability": W([900, 2.0]), "cost": 50.0}, + ) + T = 1000.0 + for seed, state in ((1, None), (2, {"a": NodeState(age=100.0)})): + run = rbd.availability( + T, + mc_samples=20_000, + seed=seed, + state=state, + control_variate=False, + conditional=False, + ) + interval = run.mean_availability_interval() + exact = rbd.mission_availability(T, state=state) + assert abs(interval.estimate - exact) <= Z * interval.standard_error + cost = rbd.expected_cost(T, state=state) + assert abs(run.cost.sample_mean - cost.mean) <= ( + Z * run.cost.sample_se + ) + + +@pytest.mark.parametrize( + "more", + [ + {"preventive": {"policy": "age", "interval": 100.0}}, + {"preventive": {**TASK, "replace_at": [100.0], "interval": None}}, + ], +) +def test_other_tasks_on_an_upgraded_part_are_refused(more): + with pytest.raises(ValueError) as error: + one(upgrade={"at": 400.0, "reliability": LIFE}, **more) + assert str(error.value) == ( + "Component 'a' has an upgrade and a preventive task other than " + "block replacement on its own interval ('policy': 'block'), which " + "are not taken together yet: give it block replacement, or one or " + "the other." + ) + + +def test_its_calendar_is_counted_from_now(): + rbd = one(preventive=TASK, upgrade={"at": 400.0, "reliability": LIFE}) + with pytest.raises(ValueError, match="leave its since_scheduled out"): + rbd.mission_availability( + 500.0, state={"a": NodeState(age=10.0, since_scheduled=10.0)} + ) + with pytest.raises(NotImplementedError, match="no long run"): + rbd.total_cost(500.0) diff --git a/repyability/tests/test_upgrade_retire_salvage.py b/repyability/tests/test_upgrade_retire_salvage.py new file mode 100644 index 00000000..5194ffab --- /dev/null +++ b/repyability/tests/test_upgrade_retire_salvage.py @@ -0,0 +1,507 @@ +"""A plan's mid-life and end-of-life actions: an upgrade that gives a +component another life from a time, at a capital cost; retiring the +system before the horizon; and a salvage value at the end. + +The references are a plain replacement at the upgrade's time (the same +life, at no cost); closed forms (memoryless units between and after the +upgrade, a unit that fails once at most, the age of a memoryless unit in +service); and the same valuation over a shorter horizon. +""" + +import json +import math + +import numpy as np +import pytest +import surpyval as surv + +from repyability import NodeState, RepairableRBD + +E = surv.Exponential.from_params +W = surv.Weibull.from_params +FIXED = surv.ExactEventTime.from_params +EDGES = [("s", "a"), ("a", "t")] +LAM, MU = 1 / 200.0, 1 / 20.0 + + +def one(life=None, repair=None, **more): + """A system of one component.""" + spec = { + "reliability": E([LAM]) if life is None else life, + "repairability": E([MU]) if repair is None else repair, + **more, + } + return RepairableRBD(EDGES, {"a": spec}) + + +def chain(t, up, lam, mu): + """A two-state unit's probability of being up ``t`` after it was up + with probability ``up``.""" + total = lam + mu + return mu / total + (up - mu / total) * np.exp(-total * t) + + +# -- an upgrade --------------------------------------------------------------- + + +@pytest.mark.parametrize("repair", [E([MU]), "instant", FIXED([15.0])]) +def test_an_upgrade_to_the_same_life_at_no_cost_is_a_replacement(repair): + life = W([300, 2.0]) + upgraded = one( + life, + repair, + upgrade={"at": 200.0, "reliability": life}, + repair_cost=6.0, + ) + replaced = one( + life, repair, preventive={"replace_at": [200.0]}, repair_cost=6.0 + ) + t = np.linspace(0.0, 900.0, 91) + np.testing.assert_allclose( + upgraded.point_availability(t), + replaced.point_availability(t), + rtol=0, + atol=1e-10, + ) + for T in (150.0, 200.0, 900.0): + mine, theirs = upgraded.expected_events(T), replaced.expected_events(T) + assert mine.node_failures["a"] == pytest.approx( + theirs.node_failures["a"], abs=1e-10 + ) + assert upgraded.expected_cost(T).mean == pytest.approx( + replaced.expected_cost(T).mean, abs=1e-9 + ) + assert "capital" in upgraded.expected_cost(900.0).by_category + assert upgraded.expected_cost(900.0).by_category["capital"] == 0.0 + + +def test_a_memoryless_unit_upgraded_to_a_better_one(): + # Up to the upgrade a two-state chain at the old rate; from it, at + # the new rate from where the old one left it (a unit up is replaced + # by one as good as any other of the new life; one in a repair comes + # back with the new life). + better, at = 1 / 800.0, 300.0 + rbd = one( + upgrade={"at": at, "reliability": E([better]), "cost": 5000.0}, + repair_cost=10.0, + ) + t = np.array([0.0, 50.0, 299.0, 300.0, 301.0, 320.0, 400.0, 1000.0]) + at_upgrade = chain(at, 1.0, LAM, MU) + expected = np.where( + t < at, + chain(t, 1.0, LAM, MU), + chain(np.maximum(t - at, 0.0), at_upgrade, better, MU), + ) + np.testing.assert_allclose(rbd.point_availability(t), expected, atol=2e-6) + + def uptime(length, up, lam): + total = lam + MU + return MU / total * length + (up - MU / total) * ( + -np.expm1(-total * length) / total + ) + + failures = LAM * uptime(at, 1.0, LAM) + better * uptime( + 700.0, at_upgrade, better + ) + assert rbd.expected_events(1000.0).node_failures["a"] == pytest.approx( + failures, abs=2e-6 + ) + # The capital cost is charged at the upgrade, whatever the unit's + # state, and discounted from there. + rate = 1e-3 + cost = rbd.expected_cost(1000.0, discount_rate=rate) + assert cost.by_category["capital"] == pytest.approx( + 5000.0 * math.exp(-rate * at), rel=1e-8 + ) + assert rbd.expected_cost(1000.0).mean == pytest.approx( + 5000.0 + 10.0 * failures, rel=1e-6 + ) + assert rbd.expected_cost(250.0).by_category["capital"] == 0.0 + value = rbd.expected_npv(1000.0, discount_rate=rate, periods=4) + # (But for a rounding of the discounting integral in a later period.) + rows = [ + r + for r in value.cash_flows + if r["category"] == "capital" and r["undiscounted"] + ] + assert [(r["period"], r["component"]) for r in rows] == [(2, "a")] + assert rows[0]["undiscounted"] == pytest.approx(-5000.0, rel=1e-8) + assert value.cost_by_category["capital"] == pytest.approx( + 5000.0 * math.exp(-rate * at), rel=1e-8 + ) + + +def test_a_weibull_unit_that_fails_once_upgraded_in_closed_form(): + # Its repairs outlast the horizon: up before the upgrade if its first + # life is, and after it if that life reached the upgrade and the new + # unit has lasted since. + old, new, at = W([300, 2.2]), W([900, 3.0]), 180.0 + rbd = one(old, FIXED([10_000.0]), upgrade={"at": at, "reliability": new}) + t = np.array([0.0, 60.0, 179.0, 180.0, 181.0, 300.0, 520.0]) + expected = np.where( + t < at, old.sf(t), old.sf(at) * new.sf(np.maximum(t - at, 0.0)) + ) + np.testing.assert_allclose(rbd.point_availability(t), expected, atol=2e-6) + assert rbd.expected_events(520.0).node_failures["a"] == pytest.approx( + float(old.ff(at) + old.sf(at) * new.ff(520.0 - at)), abs=2e-6 + ) + + +def test_an_upgrade_from_a_state_is_counted_from_now(): + better, at = 1 / 800.0, 300.0 + rbd = one(upgrade={"at": at, "reliability": E([better])}) + t = np.array([10.0, 299.0, 301.0, 400.0, 1000.0]) + # In a repair at 0: down, back at the repair rate. + state = {"a": NodeState(alive=False, down_for=3.0)} + at_upgrade = chain(at, 0.0, LAM, MU) + expected = np.where( + t < at, + chain(t, 0.0, LAM, MU), + chain(np.maximum(t - at, 0.0), at_upgrade, better, MU), + ) + np.testing.assert_allclose( + rbd.point_availability(t, state=state), expected, atol=2e-6 + ) + with pytest.raises(ValueError) as error: + rbd.point_availability(t, state={"a": "stationary"}) + assert str(error.value) == ( + "Component 'a' is upgraded at a time, so it has no long-run state: " + "give its age now (NodeState(age=...)), or leave it out (new)." + ) + + +def test_an_upgrade_is_saved_with_the_diagram(): + rbd = one( + upgrade={"at": 300.0, "reliability": W([900, 2.5]), "cost": 70.0}, + repair_cost=2.0, + ) + again = RepairableRBD.from_dict(json.loads(json.dumps(rbd.to_dict()))) + assert again._upgrades["a"].at == 300.0 + assert again._upgrades["a"].cost == 70.0 + t = np.linspace(0.0, 900.0, 19) + np.testing.assert_allclose( + again.point_availability(t), rbd.point_availability(t), atol=1e-12 + ) + assert again.expected_cost(900.0).mean == pytest.approx( + rbd.expected_cost(900.0).mean, rel=1e-12 + ) + + +NO_LONG_RUN = ( + "Component 'a' is upgraded at 300 (its units have another life from " + "then), so the diagram has no long run with it: ask for its values " + "over a horizon (expected_npv(horizon), expected_cost(T), " + "mission_availability(T), point_availability(t)); the long-run " + "methods (mean_availability(), expected_cost_rate() and the others) " + "give the long run once upgraded." +) + + +def test_what_an_upgrade_is_not_taken_with_says_what_to_run(): + rbd = one( + upgrade={"at": 300.0, "reliability": E([1e-3]), "cost": 1.0}, + repair_cost=1.0, + ) + routes = rbd.analysis_routes() + for call, name, message in ( + (lambda: rbd.total_cost(100.0), "total_cost", NO_LONG_RUN), + ): + with pytest.raises(NotImplementedError) as error: + call() + assert str(error.value) == message + assert (routes[name].route, routes[name].reason) == ( + "refused", + message, + ) + for name in ("point_availability", "expected_cost", "expected_npv"): + assert routes[name].route == "numerical" + for name in ("availability", "cost", "npv_distribution", "compare_npv"): + assert routes[name].route == "simulated" + with pytest.raises(NotImplementedError, match="expected_events"): + rbd.spares_demand(100.0) + + +@pytest.mark.parametrize( + "more, message", + [ + ( + {"upgrade": {"reliability": E([1e-3])}}, + "Component 'a': an upgrade needs 'at': the time from which its " + "units have the new life (at), and that life (reliability).", + ), + ( + {"upgrade": {"at": 0.0, "reliability": E([1e-3])}}, + "Component 'a': the upgrade's time (at) must be a positive, " + "finite number, in the diagram's time from 0, got 0.0.", + ), + ( + {"upgrade": {"at": 5.0, "reliability": E([1e-3]), "when": 1}}, + "Component 'a': unknown upgrade key(s) ['when']; it takes at, " + "reliability, cost.", + ), + ( + { + "upgrade": {"at": 5.0, "reliability": E([1e-3])}, + "preventive": {"interval": 50.0}, + }, + "Component 'a' has an upgrade and a preventive task other " + "than block replacement on its own interval ('policy': " + "'block'), which are not taken together yet: give it block " + "replacement, or one or the other.", + ), + ( + {"upgrade": {"at": 5.0, "reliability": 100.0}}, + "Component 'a': the upgrade's reliability must be a lifetime " + "model (such as a fitted surpyval distribution), got 100.0.", + ), + ], +) +def test_an_upgrade_s_spec_is_checked(more, message): + with pytest.raises(ValueError) as error: + one(**more) + assert str(error.value) == message + + +# -- retirement --------------------------------------------------------------- + + +def priced(): + return one(repair_cost=6.0, acquisition_cost=900.0) + + +def test_retiring_at_the_horizon_changes_nothing(): + rbd, options = priced(), dict( + discount_rate=1e-3, value_rate=3.0, periods=4 + ) + plain = rbd.expected_npv(1000.0, **options) + retired = rbd.expected_npv(1000.0, retire_at=1000.0, **options) + assert retired.npv == plain.npv + assert retired.cash_flows == plain.cash_flows + assert retired.eac == plain.eac + assert plain.retire_at is None and plain.salvage == 0.0 + + +def test_retiring_early_is_the_valuation_to_the_retirement(): + rbd, rate = priced(), 1e-3 + retired = rbd.expected_npv( + 1000.0, discount_rate=rate, value_rate=3.0, periods=4, retire_at=600.0 + ) + short = rbd.expected_npv(600.0, discount_rate=rate, value_rate=3.0) + assert retired.npv == pytest.approx(short.npv, rel=1e-9) + assert retired.value == pytest.approx(short.value, rel=1e-9) + assert retired.cost == pytest.approx(short.cost, rel=1e-9) + assert retired.eac == pytest.approx(short.eac, rel=1e-9) + assert retired.retire_at == 600.0 + # Nothing is earned or spent after the retirement: its period is the + # last with anything in it. + assert max(r["period"] for r in retired.cash_flows) == 3 + assert retired.period_ends == [250.0, 500.0, 750.0, 1000.0] + assert sum(r["present_value"] for r in retired.cash_flows) == ( + pytest.approx(retired.npv, rel=1e-12) + ) + + +@pytest.mark.parametrize("retire_at", [1000.5, 0.0, -1.0, "600"]) +def test_a_retirement_is_within_the_horizon(retire_at): + with pytest.raises(ValueError, match="retire_at"): + priced().expected_npv(1000.0, retire_at=retire_at) + + +# -- salvage ------------------------------------------------------------------ + + +def test_a_constant_salvage_is_credited_at_the_end_and_discounted(): + rbd, rate = priced(), 1e-3 + plain = rbd.expected_npv(1000.0, discount_rate=rate, value_rate=3.0) + for salvage, total in ( + (400.0, 400.0), + ({"a": 250.0, None: 150.0}, 400.0), + (-80.0, -80.0), # a cost of disposal + ): + result = rbd.expected_npv( + 1000.0, discount_rate=rate, value_rate=3.0, salvage=salvage + ) + worth = total * math.exp(-rate * 1000.0) + assert result.salvage == pytest.approx(worth, rel=1e-12) + assert result.undiscounted_salvage == pytest.approx(total, rel=1e-12) + assert result.npv == pytest.approx(plain.npv + worth, rel=1e-12) + assert result.cost == plain.cost + assert result.undiscounted_npv == pytest.approx( + plain.undiscounted_npv + total, rel=1e-12 + ) + rows = [r for r in result.cash_flows if r["category"] == "salvage"] + assert [r["component"] for r in rows] == [None] + assert rows[0]["present_value"] == pytest.approx(worth, rel=1e-12) + # At a retirement, it is credited then. + retired = rbd.expected_npv( + 1000.0, + discount_rate=rate, + value_rate=3.0, + periods=4, + retire_at=600.0, + salvage=400.0, + ) + assert retired.salvage == pytest.approx( + 400.0 * math.exp(-rate * 600.0), rel=1e-12 + ) + (row,) = [r for r in retired.cash_flows if r["category"] == "salvage"] + assert row["period"] == 3 + + +@pytest.mark.parametrize("repair", ["instant", "exponential"]) +def test_a_salvage_by_age_of_a_memoryless_unit_in_closed_form(repair): + # The unit in service at T has its age a with density + # R(a) m(T - a), m the rate at which units are put in, and the age T + # if it never failed; it is worth V exp(-k a) while it is up. + V, k, T = 1000.0, 2e-3, 1000.0 + c = LAM + k + + def worth(age): + return V * np.exp(-k * age) + + if repair == "instant": + rbd = one(repair="instant", repair_cost=1.0) + expected = V * (math.exp(-c * T) + LAM * -math.expm1(-c * T) / c) + else: + rbd = one(repair_cost=1.0) + total = LAM + MU + # Units are put in at the rate MU P(down): MU LAM / total + # (1 - exp(-total u)). + put_in = ( + MU + * LAM + / total + * ( + -math.expm1(-c * T) / c + - math.exp(-total * T) + * math.expm1((total - c) * T) + / (total - c) + ) + ) + expected = V * (math.exp(-c * T) + put_in) + result = rbd.expected_npv(T, discount_rate=1e-3, salvage={"a": worth}) + assert result.undiscounted_salvage == pytest.approx(expected, rel=1e-6) + assert result.salvage == pytest.approx( + expected * math.exp(-1e-3 * T), rel=1e-6 + ) + # A constant function of age is the constant, while the unit is up. + flat = rbd.expected_npv(T, salvage={"a": lambda age: 0.0 * age + V}) + assert flat.undiscounted_salvage == pytest.approx( + V * float(rbd.point_availability(T)), rel=1e-6 + ) + + +def test_a_salvage_by_age_is_a_plain_component_s(): + def worth(age): + return 100.0 - 0.0 * age + + replaced = one( + W([300, 2.0]), preventive={"interval": 100.0}, repair_cost=1.0 + ) + with pytest.raises(NotImplementedError) as error: + replaced.expected_npv(500.0, salvage={"a": worth}) + assert str(error.value) == ( + "Component 'a': a salvage by age needs the age of the unit in " + "service at the end, which is worked out for a plain component " + "from new (no maintenance, upgrade, tests, imperfect repair, " + "standby, group, shutdown, crews to wait for or state at 0): give " + "its salvage as a number." + ) + assert replaced.expected_npv(500.0, salvage={"a": 100.0}).salvage == 100.0 + rbd = priced() + with pytest.raises(NotImplementedError, match="give its salvage"): + rbd.expected_npv( + 500.0, salvage={"a": worth}, state={"a": NodeState(age=5.0)} + ) + with pytest.raises(ValueError, match="system's salvage must be a number"): + rbd.expected_npv(500.0, salvage=worth) + with pytest.raises(ValueError, match="finite number"): + rbd.expected_npv(500.0, salvage={"a": math.inf}) + with pytest.raises(ValueError, match="'b'"): + rbd.expected_npv(500.0, salvage={"b": 1.0}) + with pytest.raises(ValueError, match="array of ages"): + rbd.expected_npv(500.0, salvage={"a": lambda age: 1.0}) + + +# -- together ----------------------------------------------------------------- + + +def test_is_the_upgrade_worth_it_and_when_to_retire(): + # A worn pump earning 40 an hour: upgraded at 2,000 h for 30,000 it + # fails a quarter as often; retired at 6,000 h it is sold for 8,000. + def pump(**more): + return one(E([1 / 500.0]), E([1 / 50.0]), repair_cost=2_000.0, **more) + + rate, horizon = math.log(1.08) / 8760.0, 8000.0 + kept = pump().expected_npv(horizon, discount_rate=rate, value_rate=40.0) + upgraded = pump( + upgrade={ + "at": 2000.0, + "reliability": E([1 / 2000.0]), + "cost": 30_000.0, + } + ).expected_npv(horizon, discount_rate=rate, value_rate=40.0) + + # By hand: the availability and failure rate either side of the + # upgrade are the two-state chains', which have all but settled. + def worth(lam, start, stop, up): + total = lam + 1 / 50.0 + steady = (1 / 50.0) / total + # integral of exp(-rate t) A(t) over [start, stop] + flat = ( + steady * (math.exp(-rate * start) - math.exp(-rate * stop)) / rate + ) + swing = ( + (up - steady) + * math.exp(-rate * start) + * -math.expm1(-(total + rate) * (stop - start)) + / (total + rate) + ) + return flat + swing + + old = worth(1 / 500.0, 0.0, horizon, 1.0) + assert kept.npv == pytest.approx((40.0 - 2000.0 / 500.0) * old, rel=1e-6) + before = worth(1 / 500.0, 0.0, 2000.0, 1.0) + at_upgrade = chain(2000.0, 1.0, 1 / 500.0, 1 / 50.0) + after = worth(1 / 2000.0, 2000.0, horizon, at_upgrade) + by_hand = ( + (40.0 - 2000.0 / 500.0) * before + + (40.0 - 2000.0 / 2000.0) * after + - 30_000.0 * math.exp(-rate * 2000.0) + ) + assert upgraded.npv == pytest.approx(by_hand, rel=1e-6) + assert upgraded.npv > kept.npv + retired = pump().expected_npv( + horizon, + discount_rate=rate, + value_rate=40.0, + retire_at=6000.0, + salvage=8_000.0, + ) + by_hand = (40.0 - 2000.0 / 500.0) * worth( + 1 / 500.0, 0.0, 6000.0, 1.0 + ) + 8_000.0 * math.exp(-rate * 6000.0) + assert retired.npv == pytest.approx(by_hand, rel=1e-6) + + +def test_an_upgrade_s_time_is_a_lever(): + rbd = one( + upgrade={"at": 300.0, "reliability": E([1 / 800.0]), "cost": 9.0}, + repair_cost=1.0, + ) + (lever,) = [x for x in rbd.levers() if x.name == "upgrade.at"] + assert (lever.key, lever.value, lever.bounds) == ( + "a", + 300.0, + (0, math.inf), + ) + later = rbd.with_levers({("a", "upgrade.at"): 400.0}) + assert later._upgrades["a"].at == 400.0 + window, step = 1000.0, 0.5 + found = rbd.parameter_sensitivity(window=window)["a"]["upgrade.at"] + high = rbd.with_levers({("a", "upgrade.at"): 300.0 + step}) + low = rbd.with_levers({("a", "upgrade.at"): 300.0 - step}) + slope = ( + high.mission_availability(window) - low.mission_availability(window) + ) / (2.0 * step) + assert found == pytest.approx(slope, rel=0.02, abs=1e-9) diff --git a/repyability/tests/test_upgrade_simulated.py b/repyability/tests/test_upgrade_simulated.py new file mode 100644 index 00000000..22bad505 --- /dev/null +++ b/repyability/tests/test_upgrade_simulated.py @@ -0,0 +1,157 @@ +"""An upgraded component simulated (UC-52): a life that starts at or +after the upgrade's time is the upgrade's, from the same uniform as the +old life would have taken it, and the capital cost is charged then. + +The references are a plain replacement at the upgrade's time (an +upgrade to the same life at no cost is one, draw for draw), memoryless +units either side of the upgrade in closed form, and the numerical +values over a horizon (`mission_availability`, `expected_cost`, +`expected_npv`). +""" + +import math + +import numpy as np +import pytest +import surpyval as surv + +from repyability import NodeState, RepairableRBD +from repyability.rbd import _compiled, _event_loop +from repyability.tests import catalogue + +E = surv.Exponential.from_params +W = surv.Weibull.from_params +EDGES = [("s", "a"), ("a", "t")] +#: Standard errors a simulated estimate may be from the exact value. +Z = 4.0 + + +def one(life, repair=None, **more): + return RepairableRBD( + EDGES, + { + "a": { + "reliability": life, + "repairability": E([0.05]) if repair is None else repair, + "repair_cost": 6.0, + **more, + } + }, + ) + + +def plain(**more): + return dict(control_variate=False, conditional=False, **more) + + +@pytest.mark.parametrize("repair", [None, "instant"]) +def test_an_upgrade_to_the_same_life_at_no_cost_is_a_replacement(repair): + life = W([300, 2.0]) + upgraded = one(life, repair, upgrade={"at": 200.0, "reliability": life}) + replaced = one(life, repair, preventive={"replace_at": [200.0]}) + for state in (None, {"a": NodeState(age=120.0)}): + mine = upgraded.availability( + 900.0, mc_samples=2000, seed=5, state=state, **plain() + ) + theirs = replaced.availability( + 900.0, mc_samples=2000, seed=5, state=state, **plain() + ) + assert ( + mine.mean_availability_interval().estimate + == theirs.mean_availability_interval().estimate + ) + np.testing.assert_array_equal(mine.cost.samples, theirs.cost.samples) + + +def test_memoryless_units_either_side_of_the_upgrade(): + # Before the upgrade a two-state chain at rate lam; a unit up at it is + # replaced in no time (memoryless, nothing changes), and from it the + # chain is at the new rate from where it was. + lam, new, mu, at, T = 1 / 100.0, 1 / 400.0, 1 / 10.0, 300.0, 800.0 + + def mean_up(rate, up, length): + total = rate + mu + steady = mu / total + return ( + steady * length + + (up - steady) * -math.expm1(-total * length) / total + ) + + def up_at(rate, up, s): + total = rate + mu + return mu / total + (up - mu / total) * math.exp(-total * s) + + expected = ( + mean_up(lam, 1.0, at) + mean_up(new, up_at(lam, 1.0, at), T - at) + ) / T + rbd = one( + E([lam]), + E([mu]), + upgrade={"at": at, "reliability": E([new]), "cost": 25.0}, + ) + assert rbd.mission_availability(T) == pytest.approx(expected, abs=2e-6) + run = rbd.availability(T, mc_samples=20_000, seed=21, **plain()) + interval = run.mean_availability_interval() + assert abs(interval.estimate - expected) <= Z * interval.standard_error + # The capital cost in every simulation that reaches it, none before. + assert run.cost.by_category["capital"] == pytest.approx(25.0) + short = rbd.availability(at, mc_samples=200, seed=21, **plain()) + assert short.cost.by_category["capital"] == 0.0 + + +def test_the_simulation_agrees_with_the_numerical_values(): + rbd = catalogue.repairable_kinds()["upgraded at a time"] + T, rate = 1000.0, 1e-3 + run = rbd.availability(T, mc_samples=20_000, seed=3, **plain()) + interval = run.mean_availability_interval() + exact = rbd.mission_availability(T) + assert abs(interval.estimate - exact) <= Z * interval.standard_error + cost = rbd.expected_cost(T) + assert abs(run.cost.sample_mean - cost.mean) <= Z * run.cost.sample_se + assert cost.by_category["capital"] == pytest.approx(50.0) + # From a state: the unit in service ages towards the upgrade. + state = {"a": NodeState(age=200.0)} + run = rbd.availability( + T, mc_samples=20_000, seed=4, state=state, **plain() + ) + interval = run.mean_availability_interval() + exact = rbd.mission_availability(T, state=state) + assert abs(interval.estimate - exact) <= Z * interval.standard_error + # The NPV's spread, and its mean against the expected NPV. + spread = rbd.npv_distribution( + T, discount_rate=rate, value_rate=2.0, mc_samples=20_000, seed=9 + ) + expected = rbd.expected_npv(T, discount_rate=rate, value_rate=2.0) + se = float(np.std(spread.samples, ddof=1)) / math.sqrt(spread.samples.size) + assert np.std(spread.samples) > 0.0 + assert abs(spread.mean - expected.npv) <= Z * se + + +def test_an_upgrade_is_compared_run_by_run_with_keeping_the_old_life(): + life = W([300, 2.0]) + kept = one(life) + upgraded = one( + life, upgrade={"at": 200.0, "reliability": W([900, 2.0]), "cost": 40.0} + ) + T, rate = 1500.0, 1e-3 + comparison = upgraded.compare_npv( + kept, T, discount_rate=rate, value_rate=3.0, mc_samples=10_000, seed=2 + ) + expected = ( + upgraded.expected_npv(T, discount_rate=rate, value_rate=3.0).npv + - kept.expected_npv(T, discount_rate=rate, value_rate=3.0).npv + ) + interval = comparison.interval + assert abs(comparison.mean - expected) <= Z * interval.standard_error + # Matched runs (the old and the new life from the same uniforms) pin + # the difference down better than independent ones (0.51 against + # 0.94 here). + assert interval.standard_error < comparison.independent_standard_error + + +def test_the_compiled_engine_leaves_an_upgrade_to_python(): + rbd = catalogue.repairable_kinds()["upgraded at a time"] + plan = _event_loop._stream_plan(rbd, 100.0, 0, False)[0] + assert _compiled.unsupported(rbd, plan, None, numba=True) == "an upgrade" + route = rbd.analysis_routes()["availability"] + assert route.engine == "python" diff --git a/repyability/tests/test_value_module.py b/repyability/tests/test_value_module.py new file mode 100644 index 00000000..cf544289 --- /dev/null +++ b/repyability/tests/test_value_module.py @@ -0,0 +1,165 @@ +"""The money module (``repyability.value``): one convention for every +present value, converted from a yearly rate in one place, and the one +definition of each money helper the diagrams, the maintenance module and +the schedule module use.""" + +import math +from datetime import date +from fractions import Fraction + +import numpy as np +import pytest + +from repyability import ValueSchedule +from repyability.maintenance import _horizon +from repyability.rbd import _common, _npv, _pricing, _tally +from repyability.rbd import value_schedule as old_value_schedule +from repyability.schedule import _discount +from repyability.value import _escalation, _flows, _rates +from repyability.value._categories import CATEGORIES + + +def test_each_helper_has_one_definition(): + # The old homes hand out the money module's objects, not copies. + assert _common._discount_rate is _rates.discount_rate + assert _common._horizons is _rates.horizons + assert _common._present_horizon is _rates.present_horizon + assert _horizon._rate is _rates.continuous + assert _horizon._equivalent is _rates.equivalent + for name in ( + "yearly", + "net", + "continuous", + "per_unit", + "factor", + "factor_on", + "years_from", + "equivalent_annual", + "perpetuity", + "DAYS_A_YEAR", + "HOURS_A_YEAR", + ): + assert getattr(_discount, name) is getattr(_rates, name) + assert _pricing.Ledger is _flows.Ledger + assert _pricing.row is _flows.row + assert _pricing.sort_rows is _flows.sort_rows + assert _pricing.discounted_span is _rates.discounted_span + assert _tally._CATEGORIES is CATEGORIES + assert _npv._inflation is _escalation.inflation + assert old_value_schedule.ValueSchedule is ValueSchedule + + +def test_the_categories_keep_their_order(): + # Their places index the engines' arrays and seeded costs. + assert CATEGORIES == ( + "repair", + "replace", + "preventive", + "inspection", + "component_downtime", + "system_downtime", + "setup", + "shutdown", + "crews", + "capital", + ) + assert list(_flows.ORDER) == ["acquisition", *CATEGORIES, "value"] + + +def test_a_yearly_rate_is_converted_in_one_place(): + assert _rates.continuous(0.07) == math.log1p(0.07) + # Per hour, a year being 365.25 days. + assert _rates.HOURS_A_YEAR == 8766.0 + assert _rates.per_unit(0.07, 1.0) == math.log1p(0.07) / 8766.0 + assert _rates.per_unit(0.07, 24.0) == pytest.approx( + math.log1p(0.07) / 365.25, rel=1e-15 + ) + # Discounting continuously at the converted rate is the yearly + # convention: (1 + i) ** -y. + for years in (0.5, 1.0, 3.0, 10.0): + assert _rates.factor(0.07, years) == pytest.approx( + 1.07**-years, rel=1e-14 + ) + days = (date(2027, 11, 21) - date(2026, 11, 21)).days + assert _rates.factor_on( + 0.07, date(2026, 11, 21), date(2027, 11, 21) + ) == pytest.approx(1.07 ** -(days / 365.25), rel=1e-14) + + +def test_annuities_and_perpetuities_against_closed_forms(): + r = 0.01 + # A unit rate over 50 units: (1 - e^{-50 r}) / r. + out = _rates.present_horizon(np.array([50.0, np.inf]), r) + assert out[0] == pytest.approx(-math.expm1(-0.5) / r, rel=1e-15) + assert out[1] == 1.0 / r + # Undiscounted, the horizon itself. + assert _rates.present_horizon(np.array([7.0]), 0.0)[0] == 7.0 + # The steady cost worth a present value inverts the annuity. + npc = float(out[0]) + assert _rates.equivalent(npc, r, 50.0) == pytest.approx(1.0, rel=1e-14) + assert _rates.equivalent(300.0, 0.0, 2.0) == 150.0 + # One a year from year 1, for ever, at 7%: 1 / 0.07. + assert _rates.perpetuity(0.07, 1.0, 1.0) == pytest.approx( + 1 / 0.07, rel=1e-13 + ) + # A unit rate from a to b: (e^{-ra} - e^{-rb}) / r. + span = _rates.discounted_span(10.0, 30.0, r) + assert span == pytest.approx( + (math.exp(-0.1) - math.exp(-0.3)) / r, rel=1e-14 + ) + assert _rates.discounted_span(10.0, 30.0, 0.0) == 20.0 + + +def test_net_rate_of_escalating_costs(): + # (1 + i) / (1 + g) - 1, exactly as fractions. + expected = Fraction(107, 100) / Fraction(103, 100) - 1 + assert _rates.net(0.07, 0.03) == pytest.approx(float(expected), 1e-15) + assert _rates.net(0.07, None) == 0.07 + with pytest.raises(ValueError, match="give a discount= too"): + _rates.net(None, 0.03) + + +def test_escalation_and_inflation_checks(): + growths = _escalation.escalation(("pump",), {"repair": 0.01, "pump": 2}) + assert growths == {"repair": 0.01, "pump": 2.0} + assert _escalation.growth(growths, 0.5, "pump", "repair") == 2.5 + assert _escalation.growth(growths, 0.5, "valve", "repair") == 0.51 + assert _escalation.growth(growths, 0.5, "value") == 0.5 + with pytest.raises(ValueError, match="which is no component"): + _escalation.escalation(("pump",), {"valve": 0.01}) + with pytest.raises(ValueError, match="must be a dict"): + _escalation.escalation(("pump",), 0.01) + assert _escalation.inflation(None, "nominal") == 0.0 + assert _escalation.inflation(0.02, "real") == 0.02 + with pytest.raises(ValueError, match='inflation is for rates="real"'): + _escalation.inflation(0.02, "nominal") + + +def test_the_ledger_discounts_events_and_spans(): + r = 0.1 + ledger = _flows.Ledger(np.array([1.0, 2.0]), r, size=2) + ledger.events([0, 1, 1], [0.5, 0.5, 1.5], 10.0, "repair", "pump") + ledger.spans([0], [0.5], [1.5], 4.0, "value", None) + totals = ledger.totals() + present, nominal = totals[("repair", "pump")] + assert present[0] == pytest.approx(10 * math.exp(-0.05), rel=1e-15) + assert present[1] == pytest.approx( + 10 * (math.exp(-0.05) + math.exp(-0.15)), rel=1e-15 + ) + assert list(nominal) == [10.0, 20.0] + value, _ = totals[("value", None)] + assert value[0] == pytest.approx( + 4 * (math.exp(-0.05) - math.exp(-0.15)) / r, rel=1e-14 + ) + rows = ledger.rows(0) + # A cell is kept for every history once any history has an amount in + # it: history 0 has none in period 2's repairs. + assert [(row["period"], row["category"]) for row in rows] == [ + (1, "repair"), + (1, "value"), + (2, "repair"), + (2, "value"), + ] + assert rows[2]["present_value"] == 0.0 + # Costs are negative in the table, value positive. + assert rows[0]["present_value"] < 0 < rows[1]["present_value"] diff --git a/repyability/tests/test_value_plan.py b/repyability/tests/test_value_plan.py new file mode 100644 index 00000000..95210090 --- /dev/null +++ b/repyability/tests/test_value_plan.py @@ -0,0 +1,261 @@ +"""``value_plan``: an NPV question asked and answered as JSON documents. + +Each answer is checked against the method called directly, sent through +strict JSON, valued again from the request it echoes (the same answer, +number for number), and validated against the shipped schema (where +``jsonschema`` is installed). +""" + +import json + +import pytest +import surpyval as surv + +from repyability import ( + NodeState, + RepairableRBD, + Timeline, + ValueSchedule, + npv_schema, + value_plan, +) +from repyability.rbd._contract import _strict +from repyability.rbd.results import plain + +E = surv.Exponential.from_params +W = surv.Weibull.from_params +FIXED = surv.ExactEventTime.from_params +EDGES = [("s", "a"), ("a", "b"), ("b", "t")] + + +def line(a=None, **options): + return RepairableRBD( + EDGES, + { + "a": { + "reliability": W([300, 2.0]), + "repairability": E([0.05]), + "repair_cost": 6.0, + **(a or {}), + }, + "b": { + "reliability": E([1e-3]), + "repairability": E([0.1]), + "repair_cost": 3.0, + }, + }, + downtime_cost_rate=1.0, + **options, + ) + + +def ask(rbd, analysis, inputs, **more): + return { + "schema": 1, + "diagram": rbd.to_dict(), + "analysis": analysis, + "inputs": inputs, + **more, + } + + +def answered(request) -> dict: + """The answer, through strict JSON, valued again from its request, + and against the schema.""" + answer = value_plan(json.loads(json.dumps(request))) + text = json.dumps(answer, allow_nan=False) + assert value_plan(json.loads(text)["request"]) == answer + try: + import jsonschema + except ImportError: + return answer + schema = npv_schema() + jsonschema.validate(request, {**schema, "$ref": "#/$defs/request"}) + jsonschema.validate(answer, {**schema, "$ref": "#/$defs/answer"}) + return answer + + +def test_an_expected_npv_with_every_input_is_the_method_s(): + rbd = line({"preventive": {"policy": "block", "interval": 150.0}}) + inputs = { + "horizon": 900.0, + "discount_rate": 1e-3, + "value_rate": {"times": [0.0, 400.0], "rates": [2.0, 2.5]}, + "periods": 3, + "escalation": {"repair": 2e-4, "a": 1e-4}, + "rates": "real", + "inflation": 3e-4, + "rate_sensitivity": True, + "salvage": {"a": 20.0}, + "state": {"a": {"age": 50.0}}, + } + answer = answered(ask(rbd, "expected_npv", inputs)) + direct = rbd.expected_npv( + 900.0, + discount_rate=1e-3, + value_rate=ValueSchedule([0.0, 400.0], [2.0, 2.5]), + periods=3, + escalation={"repair": 2e-4, "a": 1e-4}, + rates="real", + inflation=3e-4, + rate_sensitivity=True, + salvage={"a": 20.0}, + state={"a": NodeState(age=50.0)}, + ) + assert answer["result"]["npv"] == direct.npv + assert answer["route"]["route"] == "numerical" + assert answer["units"] == {"time": None, "money": "cost units"} + + +def test_a_part_at_several_shutdowns_and_an_upgrade_are_valued(): + shut = line( + {"preventive": {"shutdown": ["stop", "outage"], "cost": 2.0}}, + shutdowns={ + "stop": {"period": 100.0, "duration": 1.0, "scope": ["a"]}, + "outage": {"times": [250.0], "duration": 10.0, "cost": 30.0}, + }, + ) + answer = answered(ask(shut, "expected_npv", {"horizon": 600.0})) + assert answer["result"]["npv"] == shut.expected_npv(600.0).npv + upgraded = line( + { + "preventive": {"policy": "block", "interval": 200.0}, + "upgrade": {"at": 300.0, "reliability": W([900, 2.0]), "cost": 9}, + } + ) + answer = answered( + ask( + upgraded, + "compare_npv", + {"horizon": 800.0, "value_rate": 2.0, "mc_samples": 500}, + other=line().to_dict(), + ) + ) + # A seed was drawn, and the request keeps it. + seed = answer["request"]["inputs"]["seed"] + direct = upgraded.compare_npv( + line(), 800.0, value_rate=2.0, mc_samples=500, seed=seed + ) + assert answer["result"]["mean"] == direct.mean + + +def test_a_spread_and_a_plan_against_what_happened(): + task = {"policy": "age", "interval": 200.0, "cost": 4.0} + rbd = line({"preventive": {**task, "duration": FIXED([2.0])}}) + spread = answered( + ask( + rbd, + "npv_distribution", + { + "horizon": 500.0, + "value_rate": 2.0, + "mc_samples": 300, + "seed": 4, + }, + ) + ) + direct = rbd.npv_distribution( + 500.0, value_rate=2.0, mc_samples=300, seed=4 + ) + assert spread["result"]["mean"] == direct.mean + logs = { + "a": Timeline([120.0, 130.0], 200.0), + "b": Timeline([], 200.0), + } + actual = answered( + ask( + rbd, + "plan_vs_actual", + { + "timelines": {k: v.to_dict() for k, v in logs.items()}, + "now": 200.0, + "horizon": 600.0, + "discount_rate": 1e-3, + }, + ) + ) + direct = rbd.plan_vs_actual(logs, 200.0, 600.0, discount_rate=1e-3) + assert actual["result"] == _strict(plain(direct)) + uncertain = answered( + ask( + rbd, + "expected_npv_uncertainty", + {"horizon": 500.0, "value_rate": 2.0, "n_draws": 20, "seed": 1}, + ) + ) + # Models given by their parameters have no uncertainty to draw from + # (and a JSON request cannot give one): refused, saying what to give. + assert uncertain["refused"]["reason"].startswith( + "No component's model is a surpyval fit" + ) + + +def test_a_refusal_is_an_answer_that_says_what_to_run(): + rbd = line( + {"preventive": {"policy": "age", "interval": 200.0, "cost": 4.0}}, + shutdowns={ + "outage": { + "times": [150.0], + "duration": 5.0, + "opportunistic": {"a": 50.0}, + } + }, + ) + answer = answered(ask(rbd, "expected_npv", {"horizon": 400.0})) + assert "result" not in answer + assert "by simulation" in answer["refused"]["reason"] + assert answer["route"]["route"] == "refused" + assert answer["refused"]["routes"]["expected_npv"] == "refused" + + +@pytest.mark.parametrize( + "change, message", + [ + ({"when": 1}, "unknown key(s) ['when']"), + ({"schema": 2}, "schema must be 1"), + ({"analysis": "mean_availability"}, "analysis must be one of"), + ({"inputs": {"horizon": 9.0, "speed": 1}}, "no input(s) ['speed']"), + ({"inputs": {"horizon": 9.0, "state": {"z": {}}}}, "'z' is not a"), + ({"other": {}}, "only compare_npv takes 'other'"), + ], +) +def test_a_request_is_checked_by_name(change, message): + request = {**ask(line(), "expected_npv", {"horizon": 9.0}), **change} + with pytest.raises(ValueError) as error: + value_plan(request) + assert message in str(error.value) + assert str(error.value).startswith("value_plan: ") + + +def test_the_schema_ships_with_the_package(): + schema = npv_schema() + assert set(schema["$defs"]) >= {"request", "answer"} + analyses = schema["$defs"]["analysis"]["enum"] + from repyability.rbd._contract import ANALYSES + + assert tuple(analyses) == ANALYSES + + +def test_a_unit_s_plan_is_valued_as_its_one_node_diagram(): + import surpyval as surv + + from repyability.maintenance import AgePolicy, Prices, UnitPlan + + plan = UnitPlan( + surv.Weibull.from_params([400.0, 2.0]), + surv.Exponential.from_params([0.5]), + tasks=(AgePolicy(interval=250.0, cost=2.0),), + prices=Prices(repair=5.0, acquisition=20.0), + salvage=3.0, + ) + inputs = {"horizon": 300.0, "discount_rate": 1e-3, "periods": 3} + answer = answered( + { + "schema": 1, + "diagram": plan.to_dict(), + "analysis": "expected_npv", + "inputs": inputs, + } + ) + expected = plan.expected_npv(300.0, discount_rate=1e-3, periods=3) + assert answer["result"]["npv"] == expected.npv diff --git a/repyability/tests/test_window_report.py b/repyability/tests/test_window_report.py index 5b1759e1..86a60af9 100644 --- a/repyability/tests/test_window_report.py +++ b/repyability/tests/test_window_report.py @@ -244,3 +244,105 @@ def test_the_same_seed_gives_the_same_answer(): a = bearing().cost_by_window(width=100.0, count=3, mc_samples=200, seed=5) b = bearing().cost_by_window(width=100.0, count=3, mc_samples=200, seed=5) np.testing.assert_array_equal(a.samples, b.samples) + + +def compressor_and_filters(): + """A compressor feeding two filters in parallel, each run two thirds + of the time, with lost output priced: a user's case, whose unseeded + windows cost less than nothing in some simulations.""" + sigma = 0.5 + comp = { + "reliability": W([6000.0, 2.5]), + "repairability": surv.LogNormal.from_params( + [np.log(24.0) - sigma**2 / 2, sigma] + ), + "repair_cost": 15000.0, + "duty": 2 / 3, + } + filt = { + "reliability": E([1 / 4000.0]), + "repairability": E([1 / 12.0]), + "duty": 2 / 3, + } + return RepairableRBD( + [("s", "c"), ("c", "fA"), ("c", "fB"), ("fA", "t"), ("fB", "t")], + {"c": comp, "fA": dict(filt), "fB": dict(filt)}, + downtime_cost_rate=2000.0, + ) + + +def unseeded(call, k): + """``call()`` with numpy's global RNG seeded with ``k`` (restored + after), and the seed an unseeded call draws from it.""" + from repyability.rbd._streams import shared_seed + + kept = np.random.get_state() + try: + np.random.seed(k) + drawn = shared_seed(None) + np.random.seed(k) + return call(), drawn + finally: + np.random.set_state(kept) + + +def test_an_unseeded_call_cuts_one_set_of_histories(): + # Each window's run drew its own histories when no seed was given, so + # a window's cost (a run to its end less a run to its start) was + # often below 0: about 3,700 of 26,000 here, the least -309,000. + rbd = compressor_and_filters() + ends = [216.0, 960.0, 1704.0, 2376.0, 3120.0, 3840.0] + out, drawn = unseeded(lambda: rbd.cost_by_window(ends, mc_samples=500), 11) + assert out.samples.min() >= 0.0 + # The seeded call of the seed drawn: the same histories. + seeded = rbd.cost_by_window(ends, mc_samples=500, seed=drawn) + np.testing.assert_array_equal(out.samples, seeded.samples) + run = rbd.cost( + ends[-1], + mc_samples=500, + seed=drawn, + control_variate=False, + conditional=False, + ) + np.testing.assert_allclose(out.samples.sum(axis=0), run.samples) + + +def test_an_unseeded_forecast_is_a_seeded_one(): + from repyability.schedule import ( + CalendarContext, + DutyPlan, + Shifts, + UsageForecast, + events_by_period, + ) + + frame = UsageForecast.calendar("2027-01-01", "2027-04-01") + shifts = DutyPlan(Shifts("Mon-Fri", "06:00", "22:00")).forecast( + "2027-01-01", "2027-04-01" + ) + spec = { + "reliability": W([300.0, 2.0]), + "repairability": E([0.125]), + "repair_cost": 100.0, + } + rbd = RepairableRBD([("s", "a"), ("a", "t")], {"a": spec}) + + def months(seed=None): + return events_by_period( + rbd, + CalendarContext(frame, {"a": shifts}), + cost=True, + discount=0.07, + mc_samples=300, + seed=seed, + ) + + out, drawn = unseeded(months, 4) + assert out.cost.samples.min() >= 0.0 + assert np.all(out.expected_npv >= 0.0) + seeded = months(drawn) + np.testing.assert_array_equal(out.cost.samples, seeded.cost.samples) + np.testing.assert_array_equal(out.expected_npv, seeded.expected_npv) + np.testing.assert_array_equal( + out.events.node_failures["a"], seeded.events.node_failures["a"] + ) diff --git a/repyability/utils/deprecation.py b/repyability/utils/deprecation.py index 4748030d..b7abc83f 100644 --- a/repyability/utils/deprecation.py +++ b/repyability/utils/deprecation.py @@ -1,14 +1,27 @@ """Deprecated names, arguments and calls. -A deprecation gives one minor release's notice: what 0.19 deprecates goes -in 0.20 (``NEXT_REMOVAL``). Each warns with a ``FutureWarning``, which +A deprecation gives one minor release's notice: what 0.20 deprecates goes +in 0.21 (``NEXT_REMOVAL``), and what 0.21 deprecates in 0.22 +(``REMOVED_IN_0_22``). Each warns with a ``FutureWarning``, which Python always shows, as the notice is short: an argument renamed (``renamed``; an attribute, ``renamed_attribute``), a result's value called that is now a property (``called``), arguments a method ignores -(``ignored``), or a function that moved to surpyval (``moved``). 0.19 -deprecates nothing. - -0.18 deprecated nothing, so 0.19 removes nothing. +(``ignored``), or a function that moved to surpyval (``moved``). + +0.20 deprecates, for removal in 0.21 (``NEXT_REMOVAL``), a price on an +opportunity (``price_on_part``: ``Opportunity(name, cost, ...)``, +``Shutdown(replace_cost=)``, ``Shutdowns(any_day=)``, +``Calendar(failure=, anytime=)``; the prices come with the part), and +the names ``Calendar``, ``Shutdown``, ``Shutdowns``, +``NonRepairable.optimal_calendar_policy`` and ``calendar_policy_cost`` +(``replaced``), for ``Opportunities``, ``Opportunity``, +``optimal_opportunity_policy`` and ``opportunity_policy_cost``; and a +choice made for the caller that it should make itself (``refuses_from``: +``method="auto"`` sampling a calendar too long to work out exactly, which +0.21 refuses, naming a ready ``horizon=`` and ``method="sampling"``). + +0.19 deprecated nothing, so 0.20 removes nothing. 0.18 deprecated +nothing, so 0.19 removed nothing. What 0.17 deprecated went in 0.18: ``repyability.demonstration``'s nine functions and ``DemonstrationPlan``, for ``surpyval.test_planning``'s. 0.16 deprecated nothing, nor did 0.15, so 0.16 and 0.17 removed nothing. @@ -37,8 +50,11 @@ from repyability.utils.wrappers import outside_level -#: The release that removes what 0.19 deprecates. -NEXT_REMOVAL = "0.20" +#: The release that removes what 0.20 deprecates: one minor release's +#: notice from the release that first warns of it. +NEXT_REMOVAL = "0.21" +#: The release that removes what 0.21 deprecates. +REMOVED_IN_0_22 = "0.22" def _called_warning(name: str, removal: str) -> None: @@ -155,6 +171,48 @@ def moved(old: str, new: str, why: str, removal: str = NEXT_REMOVAL) -> None: ) +def replaced( + old: str, new: str, why: str, removal: str = NEXT_REMOVAL +) -> None: + """Warn that ``old`` (a class, or a method as ``"Class.method"``) is + deprecated for ``new``, for the reason ``why``: removed in + ``removal`` (``NEXT_REMOVAL`` by default).""" + warnings.warn( + f"{old} is deprecated: use {new}, as {why}. {old} will be removed " + f"in {removal}.", + FutureWarning, + stacklevel=outside_level(), + ) + + +def price_on_part(how: str, removal: str = NEXT_REMOVAL) -> None: + """Warn that ``how`` (``"Opportunity(name, cost, ...)"``) puts a price + on an opportunity or a collection of them, which the part now + carries: deprecated, refused in ``removal`` (``NEXT_REMOVAL`` by + default).""" + warnings.warn( + f"{how} puts a price on the opportunities, which is deprecated: an " + "opportunity applies to every part, so the price comes with the " + "part (NonRepairable's planned_cost on any day, unplanned_cost at a " + "failure, opportunity_cost at an opportunity, and " + "opportunity_costs={name: price} for one opportunity). It is used " + f"as the part's price for now; {removal} will refuse it.", + FutureWarning, + stacklevel=outside_level(), + ) + + +def refuses_from(what: str, instead: str, removal: str = NEXT_REMOVAL): + """Warn that ``what`` (a choice the call made for the caller, as it + has until now) is deprecated: from ``removal`` (``NEXT_REMOVAL`` by + default) the call refuses, and the caller gives ``instead``.""" + warnings.warn( + f"{what} From {removal} this refuses: {instead}", + FutureWarning, + stacklevel=outside_level(), + ) + + def renamed_attribute( owner: str, old: str, new: str, why: str, removal: str = NEXT_REMOVAL ) -> None: @@ -182,23 +240,44 @@ def renamed_attribute( _COUNTS = frozenset({"mc_samples", "max_samples"}) +#: The names of a simulation's count that a method drawing parameters +#: (``n_draws``) is given by mistake. +_SIMULATION_COUNTS = _REMOVED | _COUNTS + + def refuses_removed_names(function): """``function``, refusing the simulation-count names 0.12 removed with the names that took their place, where Python would say only that the keyword was unexpected; ``function`` itself where it takes - neither ``mc_samples`` nor ``max_samples``.""" + neither ``mc_samples`` nor ``max_samples``. + + A method that takes ``n_draws`` but not ``mc_samples`` (the + ``*_uncertainty`` methods, which draw the uncertain models' + parameters and work each draw out without simulating it) refuses + ``mc_samples`` and the removed names, naming ``n_draws``: the two + names count different things, so ``n_draws`` is kept (#105's + ``mc_samples`` counts simulations).""" if getattr(function, "refuses_removed_names", False): return function try: taken = set(inspect.signature(function).parameters) except (TypeError, ValueError): return function - if not taken & _COUNTS: + draws = "n_draws" in taken and not taken & _COUNTS + if not taken & _COUNTS and not draws: return function name = function.__qualname__.removesuffix(".__init__") @functools.wraps(function) def checked(*args, **kwargs): + if draws and not _SIMULATION_COUNTS.isdisjoint(kwargs): + old = next(k for k in kwargs if k in _SIMULATION_COUNTS) + raise TypeError( + f"{name}() got an unexpected keyword argument {old!r}: it " + "takes n_draws=, the number of draws of the uncertain " + "models' parameters, each draw worked out without " + "simulating it (mc_samples counts simulations)." + ) if kwargs and not _REMOVED.isdisjoint(kwargs): for old in kwargs: if old in _REMOVED and old not in taken: diff --git a/repyability/value/__init__.py b/repyability/value/__init__.py new file mode 100644 index 00000000..cb422954 --- /dev/null +++ b/repyability/value/__init__.py @@ -0,0 +1,19 @@ +"""Money: one home for how RePyability values what it computes. + +Both routes use it: a diagram's valuations (``RepairableRBD``'s +``expected_npv``, ``npv_distribution``, ``plan_vs_actual``, its discounted +costs) and the single part's and the calendar's (``repyability.maintenance`` +and ``repyability.schedule``). + +- ``_rates``: discounting, with the one convention (continuous, at a rate + per unit of the clock the money falls on) and the one place a yearly + rate is converted to it. +- ``_escalation``: growth rates by stream, and inflation for real rates. +- ``value_schedule``: ``ValueSchedule``, a value earned in steps. +- ``_categories``: the cost categories. +- ``_flows``: the cash-flow table (``Ledger``) and its rows. +""" + +from repyability.value.value_schedule import ValueSchedule + +__all__ = ["ValueSchedule"] diff --git a/repyability/value/_categories.py b/repyability/value/_categories.py new file mode 100644 index 00000000..75c72159 --- /dev/null +++ b/repyability/value/_categories.py @@ -0,0 +1,20 @@ +"""The cost categories every priced result is split into.""" + +#: The cost categories, in the order ``CostResult.by_category`` lists them. +CATEGORIES = ( + "repair", + "replace", + "preventive", + "inspection", + "component_downtime", + "system_downtime", + "setup", + # Appended: the categories' places index the engines' + # arrays and seeded costs, so a new one goes at the end. + "shutdown", + # The repair crews' salaries: no engine charges them (they are the + # same in every simulation), the tally does (``charge_crews``). + "crews", + # An upgrade's capital cost, at its time: worked out, not simulated. + "capital", +) diff --git a/repyability/value/_escalation.py b/repyability/value/_escalation.py new file mode 100644 index 00000000..f8fabad5 --- /dev/null +++ b/repyability/value/_escalation.py @@ -0,0 +1,80 @@ +"""Escalation: how the amounts of a valuation grow with time. + +A diagram's valuation takes a continuous growth rate per unit of its +models' time for each stream it names (a cost category, a component, +``"value"`` or ``"salvage"``), and, in real terms, an inflation added to +the discount rate and to every growth. A calendar's valuation takes one +effective yearly rate for every cost (``_rates.net``). +""" + +import math +from typing import Any, Collection, Dict + +from repyability.utils import checks +from repyability.value._categories import CATEGORIES + +#: The streams ``escalation`` names besides the cost categories and the +#: components. +STREAMS = ("value", "salvage") + + +def escalation(components: Collection, escalation) -> Dict[Any, float]: + """``escalation`` checked, for a valuation of ``components``: a dict + of a growth rate (a continuous rate per unit time, of either sign) by + cost category, component, ``"value"`` or ``"salvage"``.""" + if escalation is None: + return {} + if not isinstance(escalation, dict): + raise ValueError( + "escalation must be a dict of a growth rate per unit time by " + "cost category, component, 'value' or 'salvage' (e.g. " + f"{{'repair': 0.03 / 8760}}); got {escalation!r}." + ) + out: Dict[Any, float] = {} + for key, rate in escalation.items(): + if not (key in components or key in CATEGORIES or key in STREAMS): + raise ValueError( + f"escalation names {key!r}, which is no component, cost " + f"category ({', '.join(CATEGORIES)}), 'value' or " + "'salvage'." + ) + number = checks.number_or_nan(rate) + if not math.isfinite(number): + raise ValueError( + f"The escalation of {key!r} must be a finite growth rate " + "per unit time of the models (continuous; 3% a year with " + f"models in hours is math.log(1.03) / 8760); got {rate!r}." + ) + out[key] = number + return out + + +def inflation(inflation, rates: str) -> float: + """The continuous inflation per unit time added to every rate: with + ``rates="real"``, ``inflation`` (0 when not given); refused with + ``"nominal"``, whose rates have it already.""" + checks.one_of("rates", rates, ("nominal", "real")) + if inflation is None: + return 0.0 + if rates == "nominal": + raise ValueError( + 'inflation is for rates="real": nominal rates and growths ' + 'have it in them already. Give rates="real" with real ' + "rates, or leave inflation out." + ) + number = checks.number_or_nan(inflation) + if not math.isfinite(number): + raise ValueError( + "inflation must be a finite continuous rate per unit time of " + f"the models; got {inflation!r}." + ) + return number + + +def growth(growths: Dict[Any, float], lift: float, *keys) -> float: + """The growth of a stream, by the first of ``keys`` in ``growths`` + (as ``escalation`` gave them), with the inflation ``lift`` added.""" + for key in keys: + if key in growths: + return growths[key] + lift + return lift diff --git a/repyability/value/_flows.py b/repyability/value/_flows.py new file mode 100644 index 00000000..de6cfcd1 --- /dev/null +++ b/repyability/value/_flows.py @@ -0,0 +1,158 @@ +"""The cash-flow table: amounts priced at their times (events) or over +spans, discounted continuously, by period, category and component, for +one history or many.""" + +from typing import Any, Dict, List, Tuple + +import numpy as np + +from repyability.value._categories import CATEGORIES +from repyability.value._rates import discounted_span + +ORDER = { + name: i + for i, name in enumerate(("acquisition",) + CATEGORIES + ("value",)) +} + + +class Ledger: + """Amounts by (period, category, component), present and + undiscounted, as costs (positive) or value, for each of ``size`` + histories.""" + + def __init__(self, ends: np.ndarray, rate: float, size: int = 1): + self.ends = np.asarray(ends, float) + self.starts = np.concatenate(([0.0], self.ends[:-1])) + self.rate = rate + self.size = size + self.cells: Dict[tuple, Tuple[np.ndarray, np.ndarray]] = {} + + def _add(self, k, category, component, history, present, nominal): + cell = self.cells.setdefault( + (int(k), category, component), + (np.zeros(self.size), np.zeros(self.size)), + ) + cell[0][:] += np.bincount(history, present, minlength=self.size) + cell[1][:] += np.bincount(history, nominal, minlength=self.size) + + def events( + self, + history, + times, + price: float, + category, + component, + growth: float = 0.0, + ): + """``price`` charged at each of ``times``, in its history, grown + to then at ``growth`` (``price * exp(growth t)``).""" + times = np.asarray(times, float) + if not price or not times.size: + return + history = np.asarray(history, np.int64) + periods = np.searchsorted(self.ends, times, side="right") + periods = np.minimum(periods, len(self.ends) - 1) + present = price * np.exp(-(self.rate - growth) * times) + nominal = ( + price * np.exp(growth * times) + if growth + else np.full(times.size, float(price)) + ) + for k in np.unique(periods): + mask = periods == k + self._add( + k, + category, + component, + history[mask], + present[mask], + nominal[mask], + ) + + def spans( + self, + history, + starts, + stops, + per_time: float, + category, + component, + growth: float = 0.0, + ): + """``per_time`` over each span from ``starts`` to ``stops``, in its + history, grown at ``growth`` (``per_time * exp(growth t)``).""" + starts = np.asarray(starts, float) + if not per_time or not starts.size: + return + history = np.asarray(history, np.int64) + stops = np.asarray(stops, float) + for k, (lo, hi) in enumerate(zip(self.starts, self.ends)): + a = np.maximum(starts, lo) + b = np.minimum(stops, hi) + inside = b > a + if not np.any(inside): + continue + a, b = a[inside], b[inside] + self._add( + k, + category, + component, + history[inside], + per_time * discounted_span(a, b, self.rate - growth), + per_time * discounted_span(a, b, -growth), + ) + + def totals(self) -> Dict[tuple, Tuple[np.ndarray, np.ndarray]]: + """``{(category, component): (present, undiscounted)}`` over every + period, an amount per history, as costs (positive) or value.""" + out: Dict[tuple, Tuple[np.ndarray, np.ndarray]] = {} + for (_, category, component), (present, nominal) in self.cells.items(): + cell = out.setdefault( + (category, component), + (np.zeros(self.size), np.zeros(self.size)), + ) + cell[0][:] += present + cell[1][:] += nominal + return out + + def rows(self, i: int = 0) -> List[Dict[str, Any]]: + """History ``i``'s cash flows: a row per period, category and + component, signed (costs negative).""" + out = [] + for (k, category, component), (present, nominal) in self.cells.items(): + sign = 1.0 if category == "value" else -1.0 + out.append( + row( + k + 1, + self.starts[k], + self.ends[k], + category, + component, + sign * present[i], + sign * nominal[i], + ) + ) + return sort_rows(out) + + +def row(period, start, end, category, component, present, nominal) -> dict: + return { + "period": int(period), + "start": float(start), + "end": float(end), + "category": category, + "component": component, + "present_value": float(present), + "undiscounted": float(nominal), + } + + +def sort_rows(rows: List[dict]) -> List[dict]: + return sorted( + rows, + key=lambda r: ( + r["period"], + ORDER.get(r["category"], len(ORDER)), + str(r["component"]), + ), + ) diff --git a/repyability/value/_rates.py b/repyability/value/_rates.py new file mode 100644 index 00000000..36cf0f71 --- /dev/null +++ b/repyability/value/_rates.py @@ -0,0 +1,222 @@ +"""Discounting: one convention for every present value in RePyability. + +Money is discounted **continuously** at a rate per unit of the clock it +falls on: an amount ``t`` units on is worth ``exp(-r t)`` of itself. The +diagrams' methods take ``r`` per unit of their models' time +(``discount_rate``). The calendar's methods take an **effective yearly +rate** ``i`` (``discount=0.07`` is 7% a year), which is ``ln(1 + i)`` a +year (``continuous``) and ``ln(1 + i) * unit_hours / HOURS_A_YEAR`` per +unit of a model's time on the calendar (``per_unit``), a year being 365.25 +days. The conversion between the two is made here, and nowhere else. + +- ``discount_rate``: a continuous rate per unit time, checked. +- ``yearly``: a yearly rate, checked. +- ``continuous``, ``per_unit``: a yearly rate as a continuous one. +- ``factor``, ``factor_on``, ``years_from``: what an amount later (years + on, or on a date) is worth now. +- ``discounted_span``: a unit amount per unit time over a span, now. +- ``present_horizon``, ``horizons``: a unit cost rate over horizons. +- ``equivalent``, ``equivalent_annual``: the steady cost worth a present + value; ``perpetuity``: an amount every gap for ever. +- ``net``: the yearly rate of costs that escalate at a yearly rate. +""" + +from __future__ import annotations + +import math +import warnings +from datetime import date +from typing import Callable, List, Optional + +import numpy as np + +from repyability.utils.checks import is_number, real_array +from repyability.utils.wrappers import outside_level + +#: The days in a year, for a yearly rate on dates. +DAYS_A_YEAR = 365.25 + + +#: The hours in a year. +HOURS_A_YEAR = 24.0 * DAYS_A_YEAR + + +def discount_rate(discount_rate) -> float: + """``discount_rate`` as a float: a ValueError unless it is a finite, + non-negative number (#184).""" + number = isinstance( + discount_rate, (int, float, np.integer, np.floating) + ) and not isinstance(discount_rate, bool) + rate = float(discount_rate) if number else float("nan") + if not (np.isfinite(rate) and rate >= 0.0): + raise ValueError( + "discount_rate must be a finite, non-negative number (a " + "continuous rate per unit time of the component models), got " + f"{discount_rate!r}." + ) + return rate + + +def yearly(discount, *, required: bool = False) -> Optional[float]: + """``discount=`` checked: a yearly rate from 0 (None when not given, + unless ``required``).""" + if discount is None and not required: + return None + if not (is_number(discount) and 0.0 <= float(discount) < 10.0): + raise ValueError( + "discount must be a yearly rate such as 0.07 (7%), at least " + f"0; got {discount!r}." + ) + return float(discount) + + +def net(discount, escalation) -> Optional[float]: + """The yearly rate the present values are taken at when every cost + escalates at the effective yearly ``escalation`` (0.03 for 3% a + year): an amount ``y`` years on is its price today times ``(1 + + escalation) ** y``, worth ``((1 + escalation) / (1 + discount)) ** + y`` of that price now, which is ``(1 + net) ** -y``. ``discount`` as + ``yearly`` gave it; with no escalation, it.""" + if escalation is None: + return discount + if discount is None: + raise ValueError( + "escalation= grows the costs in their present values: give a " + "discount= too (0 for none)." + ) + if not (is_number(escalation) and -1.0 < float(escalation) < 10.0): + raise ValueError( + "escalation must be a yearly rate such as 0.03 (3% a year), " + f"more than -1; got {escalation!r}." + ) + return (1.0 + discount) / (1.0 + float(escalation)) - 1.0 + + +def continuous(discount: float) -> float: + """The yearly rate as a continuous one a year: ``ln(1 + discount)``.""" + return math.log1p(float(discount)) + + +def per_unit(discount: float, unit_hours: float) -> float: + """The yearly rate as a continuous one per unit of a model's time on + the calendar, the unit being ``unit_hours`` long: what a method in + model time takes as its ``discount_rate``.""" + return continuous(discount) * unit_hours / HOURS_A_YEAR + + +def factor(discount: float, years): + """What an amount ``years`` on is worth now: ``(1 + discount) ** + -years``. A number or an array.""" + return np.exp(-continuous(discount) * np.asarray(years, float)) + + +def years_from(start: date, day: date) -> float: + """The years from ``start`` to ``day``, both whole dates.""" + return (day - start).days / DAYS_A_YEAR + + +def factor_on(discount: float, start: date, day: date) -> float: + """What an amount on ``day`` is worth on ``start``.""" + return float(factor(discount, years_from(start, day))) + + +def discounted_span(a, b, rate: float): + """The integral of ``exp(-rate t)`` from ``a`` to ``b``.""" + a, b = np.asarray(a, float), np.asarray(b, float) + if not rate: + return b - a + return np.exp(-rate * a) * -np.expm1(-rate * (b - a)) / rate + + +def horizons(horizon, rate: float) -> np.ndarray: + """``horizon``, a number or an array of them, as an array of + non-negative floats: finite, unless costs are discounted at ``rate`` + (#231), where an endless horizon is worth ``1 / rate`` of a steady + cost rate. Else a ValueError.""" + try: + values = real_array(horizon, "horizon") + except (TypeError, ValueError): + values = np.array(np.nan) + if values.size and np.all(values >= 0.0) and np.all(values < np.inf): + return values + if values.size and np.all(values >= 0.0): + if rate > 0.0: + return values + raise ValueError( + "horizon must be finite without a discount_rate: an undiscounted " + f"cost over an endless horizon is endless; got {horizon!r}." + ) + raise ValueError( + "horizon must be a finite, non-negative number (or an array of " + f"them; inf with a discount_rate), got {horizon!r}." + ) + + +#: A discount rate times the shortest of the components' mean lives +#: beyond which their failures' costs are discounted to almost nothing +#: (``exp(-20)``, 2e-9), and times a horizon beyond which the whole time +#: scale is: a rate given per year with the models in hours, say (#231). +#: A long horizon is no mistake in itself. +DISCOUNTED_AWAY = 20.0 + + +HORIZON_AWAY = 1000.0 + + +def present_horizon( + horizons: np.ndarray, + rate: float, + lives: Callable[[], List[float]] = list, +) -> np.ndarray: + """What a unit cost rate over ``[0, horizon)`` is worth at the start, + discounted continuously at ``rate`` per unit time (#184): ``(1 - + exp(-rate * horizon)) / rate``, the horizon itself undiscounted, and + ``1 / rate`` for an endless one; for each of ``horizons``. Warns where + the rate discounts the costs away (#231): times the shortest of the + components' mean ``lives`` more than ``DISCOUNTED_AWAY``, or times a + horizon more than ``HORIZON_AWAY``.""" + if rate == 0.0: + return horizons + known = [life for life in lives() if 0.0 < life < math.inf] + finite = horizons[np.isfinite(horizons)] + span, what = 0.0, "" + if known and rate * min(known) > DISCOUNTED_AWAY: + span, what = min(known), "the components' shortest mean life" + elif finite.size and rate * float(finite.max()) > HORIZON_AWAY: + span, what = float(finite.max()), "the horizon" + if what: + warnings.warn( + f"discount_rate {rate:g} discounts the costs at {what} " + f"({span:g}) by a factor of exp(-{rate * span:.3g}), to " + "almost nothing: it is a continuous rate per unit time of the " + "component models. For an annual rate i with models in hours, " + "give math.log(1 + i) / 8760 (7% a year: " + f"{math.log(1.07) / 8760:.3g} an hour).", + stacklevel=outside_level(), + ) + return -np.expm1(-rate * horizons) / rate + + +def equivalent(npc: float, rate: float, length: float) -> float: + """The steady cost a unit of time over ``length`` worth ``npc`` at the + continuous ``rate`` (``npc / length`` at 0).""" + if rate > 0.0 or (rate < 0.0 and math.isfinite(length)): + # (Below 0, a net rate of costs that grow faster than the + # discount, over a finite length.) + return rate * npc / -math.expm1(-rate * length) + return npc / length + + +def equivalent_annual(npv: float, discount: float, years: float) -> float: + """The steady cost a year over ``years`` (``math.inf`` for ever) worth + ``npv`` now: the equivalent annual cost (``npv / years`` at no + discount).""" + return equivalent(float(npv), continuous(discount), float(years)) + + +def perpetuity(discount: float, first_years: float, gap_years: float) -> float: + """What one unit of money at ``first_years`` and every ``gap_years`` + after it, for ever, is worth now: ``v ** first / (1 - v ** gap)`` + with ``v = 1 / (1 + discount)``.""" + rate = continuous(discount) + return math.exp(-rate * first_years) / -math.expm1(-rate * gap_years) diff --git a/repyability/value/_risk.py b/repyability/value/_risk.py new file mode 100644 index 00000000..eea073c8 --- /dev/null +++ b/repyability/value/_risk.py @@ -0,0 +1,107 @@ +"""Risk measures on priced outcomes: how bad a bad run is. + +An outcome here is a loss per run (a downtime in hours or its cost, a +cost), larger being worse. ``quantile`` is the value-at-risk at a level +(the smallest outcome with at least that share of the runs at or below +it), ``tail_mean`` the mean of the worst share beyond it (the CVaR), and +each has an upper confidence bound, so that a design is said to keep a +bad run under a limit only when the bound is under it: + +- the quantile's bound is an order statistic, by the binomial method + (distribution-free and exact for a continuous outcome): the ``k``-th + smallest of ``n`` runs is above the ``level`` quantile with chance + ``P(Binomial(n, level) <= k - 1)``, and ``k`` is the smallest making that + at least ``confidence``; +- the tail mean's bound is the normal one, from the standard error of + the tail mean (the variance of ``max(X - q, 0) / (1 - level)``, which + is the tail mean's influence beyond the quantile), so it is + approximate, and says so. +""" + +import math +from dataclasses import dataclass + +import numpy as np + +#: The risk measures a target takes. +MEASURES = ("var", "cvar") + + +def quantile(ordered: np.ndarray, level: float) -> float: + """The ``level`` quantile of the sorted outcomes ``ordered``: the + smallest with at least a share ``level`` of them at or below it (the + ``ceil(level n)``-th, at least the first).""" + k = max(1, math.ceil(round(level * ordered.size, 9))) + return float(ordered[k - 1]) + + +def quantile_bound(ordered: np.ndarray, level: float, confidence: float): + """An upper confidence bound on the ``level`` quantile of the + outcomes, at ``confidence``: an order statistic (the binomial method), + ``inf`` when the runs are too few to give one.""" + from scipy.stats import binom + + n = ordered.size + k = int(binom.ppf(confidence, n, level)) + 1 + while k > 1 and binom.cdf(k - 2, n, level) >= confidence: + k -= 1 + while k <= n and binom.cdf(k - 1, n, level) < confidence: + k += 1 + return float(ordered[k - 1]) if k <= n else math.inf + + +def tail_mean(ordered: np.ndarray, level: float) -> float: + """The mean of the worst share ``1 - level`` of the outcomes (at + least one run): the conditional value-at-risk.""" + worst = max(1, math.ceil(round((1.0 - level) * ordered.size, 9))) + return float(ordered[-worst:].mean()) + + +def tail_mean_bound(ordered: np.ndarray, level: float, confidence: float): + """An approximate upper confidence bound on the tail mean: the + estimate plus the normal quantile at ``confidence`` times its + standard error (see the module's notes).""" + from scipy.stats import norm + + n = ordered.size + q = quantile(ordered, level) + excess = np.maximum(ordered - q, 0.0) / (1.0 - level) + se = float(excess.std(ddof=1)) / math.sqrt(n) if n > 1 else math.inf + return tail_mean(ordered, level) + float(norm.ppf(confidence)) * se + + +@dataclass(frozen=True) +class Risk: + """A risk measure of some outcomes: the ``estimate`` (the quantile, + or the tail mean, at ``level``), its upper ``bound`` at ``confidence`` + and how the bound is found (``bound_method``).""" + + measure: str + level: float + estimate: float + bound: float + confidence: float + bound_method: str + + +def risk(outcomes, level: float, measure: str, confidence: float) -> Risk: + """``measure`` (``"var"`` or ``"cvar"``) of ``outcomes`` at + ``level``, with its upper bound at ``confidence``.""" + ordered = np.sort(np.asarray(outcomes, float)) + if measure == "var": + return Risk( + measure, + level, + quantile(ordered, level), + quantile_bound(ordered, level, confidence), + confidence, + "order statistic (binomial method, exact)", + ) + return Risk( + measure, + level, + tail_mean(ordered, level), + tail_mean_bound(ordered, level, confidence), + confidence, + "normal (approximate)", + ) diff --git a/repyability/value/value_schedule.py b/repyability/value/value_schedule.py new file mode 100644 index 00000000..2d31ac8b --- /dev/null +++ b/repyability/value/value_schedule.py @@ -0,0 +1,181 @@ +"""What a system earns while it works, by stretches of model time: the +``value_rate`` of ``RepairableRBD.expected_npv`` as steps (UC-57 of the +maintenance README).""" + +import math +from typing import Any, Dict, Tuple + +import numpy as np + +from repyability.utils import checks + + +class ValueSchedule: + """The value a system earns per unit time while it works, in steps + of model time: ``rates[k]`` from ``times[k]`` to ``times[k + 1]`` + (the last for the rest of the horizon). Plain data, so a valuation + made with it can be saved and made again: a function of time is not + taken. + + A steady growth of the value (a price that rises) is + ``expected_npv``'s ``escalation={"value": g}``, which applies to a + schedule as to a single rate. + + Parameters + ---------- + times : array_like + Where each step starts, in the models' unit, increasing, the + first 0. + rates : array_like + The value per unit time while the system works in each step, at + least 0, one for each of ``times``. + + Raises + ------ + ValueError + If ``times`` do not start at 0 and increase, or ``rates`` are not + one finite number of at least 0 for each. + + Examples + -------- + A plant that earns 10 an hour for its first year and 12 after: + + >>> from repyability import ValueSchedule + >>> value = ValueSchedule([0.0, 8760.0], [10.0, 12.0]) + >>> value.rate_at([0.0, 9000.0]).tolist() + [10.0, 12.0] + >>> ValueSchedule.from_dict(value.to_dict()) == value + True + """ + + def __init__(self, times, rates): + if callable(times) or callable(rates): + raise TypeError( + "A ValueSchedule is steps of plain numbers, so that a " + "valuation can be saved and made again: give the times " + "the rates change and the rate from each, " + "ValueSchedule(times, rates)." + ) + starts = checks.real_array(times, "times").ravel().astype(float) + values = checks.real_array(rates, "rates").ravel().astype(float) + if not ( + starts.size + and starts[0] == 0.0 + and np.all(np.isfinite(starts)) + and np.all(np.diff(starts) > 0.0) + ): + raise ValueError( + "A ValueSchedule's times are where its steps start: " + f"increasing, the first 0; got {times!r}." + ) + if values.shape != starts.shape or not ( + np.all(np.isfinite(values)) and np.all(values >= 0.0) + ): + raise ValueError( + "A ValueSchedule's rates are the value per unit time in " + "each step: a finite number of at least 0 for each of its " + f"{starts.size} times; got {rates!r}." + ) + self._times: Tuple[float, ...] = tuple(starts.tolist()) + self._rates: Tuple[float, ...] = tuple(values.tolist()) + + @property + def times(self) -> Tuple[float, ...]: + """Where each step starts.""" + return self._times + + @property + def rates(self) -> Tuple[float, ...]: + """The value per unit time while the system works in each step.""" + return self._rates + + def rate_at(self, t) -> np.ndarray: + """The rate at times ``t`` (each step's from its start). + + Parameters + ---------- + t : array_like + Times, at least 0. + + Returns + ------- + numpy.ndarray + The rate at each. + """ + x = np.asarray(t, dtype=float) + k = np.searchsorted(np.asarray(self._times), x, side="right") - 1 + return np.asarray(self._rates)[np.maximum(k, 0)] + + def steps(self, stop: float) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: + """The steps that start before ``stop``. + + Parameters + ---------- + stop : float + Where the steps are cut: the end of the time valued. + + Returns + ------- + tuple + The steps' starts, ends (the last ``stop``) and rates, as + arrays. + """ + times = np.asarray(self._times) + keep = times < stop + starts = times[keep] + ends = np.append(starts[1:], stop) + return starts, ends, np.asarray(self._rates)[keep] + + def to_dict(self) -> Dict[str, Any]: + """The schedule as plain data, for ``json.dumps``. + + Returns + ------- + dict + ``{"times": [...], "rates": [...]}``. + """ + return {"times": list(self._times), "rates": list(self._rates)} + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "ValueSchedule": + """The schedule ``to_dict`` gave. + + Parameters + ---------- + data : dict + ``{"times": [...], "rates": [...]}``. + + Returns + ------- + ValueSchedule + """ + return cls(data["times"], data["rates"]) + + def __eq__(self, other) -> bool: + if not isinstance(other, ValueSchedule): + return NotImplemented + return self._times == other._times and self._rates == other._rates + + def __hash__(self) -> int: + return hash((self._times, self._rates)) + + def __repr__(self) -> str: + return ( + f"ValueSchedule(times={list(self._times)}, " + f"rates={list(self._rates)})" + ) + + +def value_of(value_rate) -> Any: + """``expected_npv``'s ``value_rate`` checked: a number of at least 0, + or a ``ValueSchedule``.""" + if isinstance(value_rate, ValueSchedule): + return value_rate + number = checks.number_or_nan(value_rate) + if not (math.isfinite(number) and number >= 0.0): + raise ValueError( + "value_rate must be a finite number, at least 0 (the value " + "earned per unit time while the system works), or a " + f"ValueSchedule of steps; got {value_rate!r}." + ) + return number diff --git a/scripts/bdd_benchmark.py b/scripts/bdd_benchmark.py new file mode 100644 index 00000000..34921c0c --- /dev/null +++ b/scripts/bdd_benchmark.py @@ -0,0 +1,233 @@ +"""Measure what a meshed core's decision diagram costs to build +(``repyability/rbd/bdd.py``): for grids, layered meshes (a chain of +bridges made wider) and random acyclic diagrams of growing width, the +frontier cost (``bdd._cost``) of each order ``bdd.order`` chooses from, +and for the search the states it interns, the steps of the plan it makes, +its time, its peak memory and whether it passed ``bdd.STEP_LIMIT``. + + python scripts/bdd_benchmark.py # the table + python scripts/bdd_benchmark.py --quick # the small diagrams only + python scripts/bdd_benchmark.py --limit 100_000_000 + +The peak is ``tracemalloc``'s over the Python search (whose states are +Python's own objects), which makes it several times slower; the time is of +a run without it. With numba installed the compiled search is timed too: +its memory is not Python's, so its peak is read from the growth of the +process's resident memory (which only ever grows: a lower bound after the +first large diagram). A measurement, not a test: nothing here is asserted. +""" + +import argparse +import resource +import time +import tracemalloc +from typing import Callable, Dict, List, Tuple + +import numpy as np + +from repyability import RBD +from repyability.rbd import _compiled, bdd +from repyability.rbd.modular import decompose + + +def grid(rows: int, cols: int) -> list: + """``rows`` lines of ``cols`` nodes, each node also feeding the one + below it.""" + edges = [("s", (r, 0)) for r in range(rows)] + edges += [((r, cols - 1), "t") for r in range(rows)] + for r in range(rows): + for c in range(cols): + if c + 1 < cols: + edges.append(((r, c), (r, c + 1))) + if r + 1 < rows: + edges.append(((r, c), (r + 1, c))) + return edges + + +def mesh(width: int, layers: int) -> list: + """``layers`` layers of ``width`` nodes, each node feeding the nodes + beside its place in the next layer: a chain of bridges, made wider.""" + edges = [("s", (0, j)) for j in range(width)] + edges += [((layers - 1, j), "t") for j in range(width)] + for i in range(layers - 1): + for j in range(width): + for d in (-1, 0, 1): + if 0 <= j + d < width: + edges.append(((i, j), (i + 1, j + d))) + return edges + + +def random_dag(n: int, p: float, seed: int = 1) -> list: + """``n`` nodes, each joined to each later one with probability + ``p``.""" + rng = np.random.default_rng(seed) + edges: set = { + (i, j) for i in range(n) for j in range(i + 1, n) if rng.random() < p + } + for i in range(n): + if not any(a == i for a, _ in edges): + edges.add((i, "t")) + if not any(b == i for _, b in edges): + edges.add(("s", i)) + return sorted(edges, key=str) + + +def diagrams(quick: bool) -> List[Tuple[str, list]]: + out = [ + ("grid 6x12", grid(6, 12)), + ("grid 10x20", grid(10, 20)), + ("mesh 6x12", mesh(6, 12)), + ("mesh 8x12", mesh(8, 12)), + ("random 35, 0.2", random_dag(35, 0.2)), + ("random 45, 0.2", random_dag(45, 0.2)), + ] + if not quick: + out += [ + ("grid 14x14", grid(14, 14)), + ("grid 18x18", grid(18, 18)), + ("mesh 10x12", mesh(10, 12)), + ("mesh 12x12", mesh(12, 12)), + ("mesh 14x12", mesh(14, 12)), + ("random 60, 0.2", random_dag(60, 0.2)), + ("random 70, 0.2", random_dag(70, 0.2)), + ("random 80, 0.2", random_dag(80, 0.2)), + ("random 60, 0.4", random_dag(60, 0.4)), + ] + return out + + +class _Core(Exception): + """Carries the core ``bdd.build`` was about to be given.""" + + +def core_of(edges: list) -> tuple: + """The core of the diagram of ``edges``, as ``bdd.build``'s arguments + but for the order: ``(vertices, pred, succ, k, source, sink, + variable)``.""" + real = bdd.build + + def stop(*args): + raise _Core(args) + + bdd.build = stop + try: + decompose(RBD(edges).G, "s", "t", core="bdd") + except _Core as found: + return found.args[0] + finally: + bdd.build = real + raise ValueError("The diagram has no core.") + + +def orders(core: tuple) -> Dict[str, list]: + """Each order ``bdd.order`` chooses from, by name.""" + sequence, pred, succ, _, source, sink, _ = core + vertices = sorted(sequence) + return { + name: candidate(vertices, pred, succ, source, sink) + for name, candidate in bdd.CANDIDATES.items() + } + + +def searched(core: tuple, limit: int) -> dict: + """The Python search of a core: its states, the plan's steps, its + time, its peak memory, and whether it passed ``limit``.""" + interned: List[dict] = [] + real = bdd.search + + def spy(*args): + interned.append(args[22]) + return real(*args) + + out: dict = {} + kept = bdd.STEP_LIMIT, bdd.COMPILED + bdd.STEP_LIMIT, bdd.COMPILED, bdd.search = limit, False, spy + try: + for traced in (False, True): + if traced: + tracemalloc.start() + began = time.perf_counter() + try: + steps = len(bdd.build(*core)[0]) + out["too large"] = False + except bdd.TooLarge: + steps = None + out["too large"] = True + if traced: + out["peak MB"] = tracemalloc.get_traced_memory()[1] / 2**20 + tracemalloc.stop() + else: + out["seconds"] = time.perf_counter() - began + out["plan steps"] = steps + out["states"] = len(interned[-1]) + finally: + bdd.STEP_LIMIT, bdd.COMPILED = kept + bdd.search = real + return out + + +def compiled(core: tuple, limit: int) -> dict: + """The compiled search of a core: its time (compiled already) and the + growth of the process's resident memory.""" + kept = bdd.STEP_LIMIT, bdd.COMPILED + bdd.STEP_LIMIT, bdd.COMPILED = limit, True + + def run() -> None: + try: + bdd.build(*core) + except bdd.TooLarge: + pass + + try: + before = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss + began = time.perf_counter() + run() + seconds = time.perf_counter() - began + after = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss + finally: + bdd.STEP_LIMIT, bdd.COMPILED = kept + return {"seconds": seconds, "grown MB": (after - before) / 2**10} + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--quick", action="store_true") + parser.add_argument("--limit", type=int, default=bdd.STEP_LIMIT) + options = parser.parse_args() + numba = _compiled.available() + if numba: + compiled(core_of(grid(3, 4)), options.limit) # compile it first + names = list(bdd.CANDIDATES) + head = ["diagram", "nodes", "edges"] + head += [f"log2 cost, {name}" for name in names] + head += ["order", "states", "plan steps", "seconds", "peak MB", "limit"] + if numba: + head += ["compiled seconds", "compiled grown MB"] + print("| " + " | ".join(head) + " |") + print("|" + "---|" * len(head)) + for label, edges in diagrams(options.quick): + core = core_of(edges) + sequence, pred, succ, _, source, sink, _ = core + cost: Callable = lambda o: bdd._cost(o, pred, succ, source, sink) + candidates = orders(core) + chosen = min(names, key=lambda name: cost(candidates[name])) + assert candidates[chosen] == list(sequence) + got = searched(core, options.limit) + row = [label, str(len(sequence)), str(len(edges))] + row += [f"{np.log2(cost(candidates[name])):.1f}" for name in names] + row += [ + chosen, + f"{got['states']:,}", + "-" if got["too large"] else f"{got['plan steps']:,}", + f"{got['seconds']:.2f}", + f"{got['peak MB']:.1f}", + "passed" if got["too large"] else "", + ] + if numba: + fast = compiled(core, options.limit) + row += [f"{fast['seconds']:.2f}", f"{fast['grown MB']:.0f}"] + print("| " + " | ".join(row) + " |", flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/calendar_policy_chart.py b/scripts/calendar_policy_chart.py index 0102c26a..2bfc5d19 100644 --- a/scripts/calendar_policy_chart.py +++ b/scripts/calendar_policy_chart.py @@ -17,7 +17,7 @@ import matplotlib.pyplot as plt # noqa: E402 import surpyval as surv # noqa: E402 -from repyability import Calendar, NonRepairable, Opportunity # noqa: E402 +from repyability import NonRepairable, Opportunities, Opportunity # noqa: E402 OUT = ( Path(__file__).resolve().parent.parent @@ -36,17 +36,20 @@ def main() -> None: - bearing = NonRepairable(surv.Weibull.from_params([1000.0, 2.5])) - plant = Calendar( + bearing = NonRepairable( + surv.Weibull.from_params([1000.0, 2.5]), + planned_cost=4.0, + unplanned_cost=20.0, + opportunity_costs={"weekly": 3.0, "quarterly": 2.0, "annual": 1.0}, + ) + plant = Opportunities( [ - Opportunity("weekly", 3.0, period=7.0), - Opportunity("quarterly", 2.0, period=91.0), - Opportunity("annual", 1.0, period=364.0), - ], - failure=20.0, - anytime=4.0, + Opportunity("weekly", period=7.0), + Opportunity("quarterly", period=91.0), + Opportunity("annual", period=364.0), + ] ) - policy = bearing.optimal_calendar_policy(plant) + policy = bearing.optimal_opportunity_policy(plant) figure, axes = plt.subplots(figsize=(8, 4.2), dpi=100) figure.patch.set_facecolor(SURFACE) axes.set_facecolor(SURFACE) diff --git a/scripts/downtime_bound_coverage.py b/scripts/downtime_bound_coverage.py new file mode 100644 index 00000000..851c80d8 --- /dev/null +++ b/scripts/downtime_bound_coverage.py @@ -0,0 +1,64 @@ +"""Study: does the bad-year downtime bound cover at its stated rate? + +UC-68 of the maintenance README. ``least_spend_for_downtime`` keeps a +design only when an upper confidence bound on its downtime's quantile is +under the limit. This study checks that bound end to end: for a pump with +exponential lives (mean 1,000 h) and repairs (mean 50 h) over 8,760 h, +whose downtime's 95th percentile is exact (766.3532 h, by uniformisation: +``repyability/tests/test_downtime_risk.py``'s ``downtime_cdf``), it runs +the diagram's evaluation with seeds 1 to ``REPEATS`` and counts how often +the 95% bound is at or above the exact percentile. + +The design was fixed before any result was seen: 1,000 repeats of 500 +runs, seeds 1 to 1,000, level 0.95, confidence 0.95. The order-statistic +bound is distribution-free, so its coverage is at least 0.95 up to the +ties of a discrete outcome (none here: downtime has an atom at 0 only, +far below the percentile). Pass: the coverage's 99% binomial interval +reaches 0.95. Run at consolidation, with one process: + + PYTHONPATH=. python scripts/downtime_bound_coverage.py +""" + +import math + +import numpy as np +import surpyval as surv +from scipy import stats + +from repyability import RepairableRBD + +EXACT = 766.3532060243101 # the 95th percentile, by uniformisation +REPEATS = 1000 +RUNS = 500 +LEVEL = CONFIDENCE = 0.95 + + +def main() -> None: + E = surv.Exponential.from_params + pump = RepairableRBD( + [("s", "p"), ("p", "t")], + {"p": {"reliability": E([1e-3]), "repairability": E([0.02])}}, + ) + covered = 0 + for seed in range(1, REPEATS + 1): + found = pump.least_spend_for_downtime( + 8760.0, + 1e9, + level=LEVEL, + confidence=CONFIDENCE, + mc_samples=RUNS, + seed=seed, + ) + covered += found.design.bound >= EXACT + low, high = stats.binomtest(covered, REPEATS).proportion_ci(0.99) + share = covered / REPEATS + print( + f"coverage {share:.4f} ({covered} of {REPEATS}), 99% interval " + f"[{low:.4f}, {high:.4f}]; stated {CONFIDENCE}" + ) + print("PASS" if high >= CONFIDENCE else "FAIL") + assert math.isfinite(share) and np.isfinite(low) + + +if __name__ == "__main__": + main()