Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 8 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 15 additions & 0 deletions docs/guide/costs.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions repyability/fault_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.

Expand Down
10 changes: 9 additions & 1 deletion repyability/rbd/_degradation.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"""

import math
import sys

import numpy as np
from scipy.special import gammainc, gammaincinv, log_ndtr, ndtr
Expand All @@ -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())


Expand Down
56 changes: 38 additions & 18 deletions repyability/rbd/_spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
24 changes: 17 additions & 7 deletions repyability/rbd/ccf.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(),
Expand Down
17 changes: 13 additions & 4 deletions repyability/rbd/joint_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
``NodeState`` age (see ``NonRepairableRBD.sf_given_state``).
"""

import sys
from typing import Any, Optional

import numpy as np
Expand All @@ -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

Expand All @@ -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

Expand Down
13 changes: 10 additions & 3 deletions repyability/rbd/repairable_rbd.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
40 changes: 40 additions & 0 deletions repyability/tests/test_first_build.py
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading