diff --git a/CHANGELOG.md b/CHANGELOG.md index c6be18c..224e2c8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -709,6 +709,30 @@ release between minors that only adds (0.19.1). ### Changed +- 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 diff --git a/CLAUDE.md b/CLAUDE.md index ad8c427..50ff7e3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -489,7 +489,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 diff --git a/docs/guide/costs.md b/docs/guide/costs.md index e24d775..ce05c2f 100644 --- a/docs/guide/costs.md +++ b/docs/guide/costs.md @@ -26,6 +26,21 @@ Costs are optional keys of a component's dict, plus one system-level rate: | 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 import surpyval as surv diff --git a/repyability/fault_tree.py b/repyability/fault_tree.py index d9b937a..cfdbf67 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/rbd/_degradation.py b/repyability/rbd/_degradation.py index f9ffab9..8f3d282 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/_spec.py b/repyability/rbd/_spec.py index 5694cd8..7d0ee4b 100644 --- a/repyability/rbd/_spec.py +++ b/repyability/rbd/_spec.py @@ -895,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"), @@ -1198,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) @@ -1261,6 +1249,38 @@ 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 diff --git a/repyability/rbd/ccf.py b/repyability/rbd/ccf.py index 3685304..89d52b8 100644 --- a/repyability/rbd/ccf.py +++ b/repyability/rbd/ccf.py @@ -337,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 @@ -1170,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(), diff --git a/repyability/rbd/joint_node.py b/repyability/rbd/joint_node.py index 3df5e78..1ac7e0a 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,8 +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.)""" + """surpyval's ``JointModel`` and ``DynamicPrediction``, or ``()`` + while surpyval's joint models are not imported. (The latter has no + public home in surpyval yet, so it comes from its module.) + + 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 import JointModel from surpyval.univariate.joint import DynamicPrediction @@ -55,8 +64,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/repairable_rbd.py b/repyability/rbd/repairable_rbd.py index 84950f2..62a181e 100644 --- a/repyability/rbd/repairable_rbd.py +++ b/repyability/rbd/repairable_rbd.py @@ -196,7 +196,11 @@ 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 @@ -227,7 +231,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 @@ -292,7 +298,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 diff --git a/repyability/tests/test_first_build.py b/repyability/tests/test_first_build.py new file mode 100644 index 0000000..ce909ee --- /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_refused_inputs.py b/repyability/tests/test_refused_inputs.py index 4a181c2..8027fb5 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/utils/deprecation.py b/repyability/utils/deprecation.py index 4dc2566..639cd8b 100644 --- a/repyability/utils/deprecation.py +++ b/repyability/utils/deprecation.py @@ -239,23 +239,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: