From c4a7363fdbef3a515b918871774ab74535fd10be Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 09:16:33 +0000 Subject: [PATCH] Take the site's Opportunities as a diagram's shutdowns RepairableRBD(shutdowns=) takes an Opportunities record in model time: each Opportunity is a shutdown of its name (period and offset or dates, duration, takes_down as the scope), with Opportunity(idle_ageing=, opportunistic=) and Opportunities(shut_costs=) for what only a diagram uses. The record is read as the dicts it stands for, which the diagram keeps and saves, so its values and seeded runs are the dicts'. Shuts on real dates go through Opportunities.on_diagram; a ShutdownPolicy is refused, naming the record to give. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L6RpnXB87vwhYETeh7ihtA --- CHANGELOG.md | 13 ++ docs/guide/system-maintenance.md | 23 +++ repyability/maintenance/README.md | 3 +- repyability/maintenance/_calendar.py | 76 +++++++- repyability/maintenance/_opportunities.py | 89 ++++++++- repyability/rbd/_shutdowns.py | 23 ++- repyability/rbd/repairable_rbd.py | 16 +- .../tests/test_opportunities_on_diagram.py | 181 ++++++++++++++++++ 8 files changed, 414 insertions(+), 10 deletions(-) create mode 100644 repyability/tests/test_opportunities_on_diagram.py diff --git a/CHANGELOG.md b/CHANGELOG.md index b24621e..4ab0ed6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,19 @@ release between minors that only adds (0.19.1). ### Added +- 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 diff --git a/docs/guide/system-maintenance.md b/docs/guide/system-maintenance.md index 8aaac7c..3e2b881 100644 --- a/docs/guide/system-maintenance.md +++ b/docs/guide/system-maintenance.md @@ -1282,6 +1282,29 @@ and carries on from where it was. | `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}, +) +line = RepairableRBD(edges, components, 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 diff --git a/repyability/maintenance/README.md b/repyability/maintenance/README.md index 734ed75..3ba33ab 100644 --- a/repyability/maintenance/README.md +++ b/repyability/maintenance/README.md @@ -40,7 +40,6 @@ Architecture): | 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: -- a site's shutdowns are both the diagram's `shutdowns=` dicts and `Opportunities`/`ShutdownPolicy`; - 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. @@ -69,7 +68,7 @@ Not yet single: | 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-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=)` | diff --git a/repyability/maintenance/_calendar.py b/repyability/maintenance/_calendar.py index eacc82c..228e18f 100644 --- a/repyability/maintenance/_calendar.py +++ b/repyability/maintenance/_calendar.py @@ -136,7 +136,18 @@ class Opportunity: 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. + 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 @@ -174,6 +185,8 @@ class Opportunity: duration: Optional[float] = None at: Any = None takes_down: Optional[Tuple[str, ...]] = None + idle_ageing: bool = True + opportunistic: Any = None def __init__( self, @@ -190,6 +203,8 @@ def __init__( 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). @@ -235,6 +250,8 @@ def __init__( ("duration", duration), ("at", at), ("takes_down", takes_down), + ("idle_ageing", idle_ageing), + ("opportunistic", opportunistic), ): object.__setattr__(self, key, value) self._check() @@ -247,6 +264,8 @@ def __repr__(self) -> str: 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)})" @@ -303,6 +322,44 @@ def _check(self) -> None: 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"): @@ -691,6 +748,14 @@ def to_dict(self) -> dict: ) 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 @@ -740,6 +805,15 @@ def from_dict(cls, data: dict) -> "Opportunity": ) 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 diff --git a/repyability/maintenance/_opportunities.py b/repyability/maintenance/_opportunities.py index 0b57275..96ed56e 100644 --- a/repyability/maintenance/_opportunities.py +++ b/repyability/maintenance/_opportunities.py @@ -251,6 +251,11 @@ class Opportunities: 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 -------- @@ -273,7 +278,14 @@ class Opportunities: True """ - def __init__(self, opportunities=(), *, any_day=True, time_zone=None): + 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)): @@ -326,6 +338,7 @@ def __init__(self, opportunities=(), *, any_day=True, time_zone=None): ) 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 @@ -511,6 +524,8 @@ def to_dict(self) -> dict: 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 @@ -540,7 +555,7 @@ def from_dict(cls, data: dict) -> "Opportunities": "These Opportunities were saved by a newer RePyability " f"(version {data['version']}): upgrade to read them." ) - return cls._legacy( + 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"), @@ -548,6 +563,76 @@ def from_dict(cls, data: dict) -> "Opportunities": 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: diff --git a/repyability/rbd/_shutdowns.py b/repyability/rbd/_shutdowns.py index d5fd2fd..f8b25d2 100644 --- a/repyability/rbd/_shutdowns.py +++ b/repyability/rbd/_shutdowns.py @@ -70,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, @@ -79,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())) diff --git a/repyability/rbd/repairable_rbd.py b/repyability/rbd/repairable_rbd.py index e3ba9d2..64a0d9a 100644 --- a/repyability/rbd/repairable_rbd.py +++ b/repyability/rbd/repairable_rbd.py @@ -532,11 +532,18 @@ 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 @@ -832,7 +839,7 @@ 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, ): @@ -893,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), diff --git a/repyability/tests/test_opportunities_on_diagram.py b/repyability/tests/test_opportunities_on_diagram.py new file mode 100644 index 0000000..761d61a --- /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"])] + ), + )