ictdesigntools 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,120 @@
1
+ """Subnet calculations for IPv4 and IPv6, built on the stdlib ``ipaddress`` module."""
2
+
3
+ import ipaddress
4
+ from dataclasses import dataclass
5
+
6
+ type Interface = ipaddress.IPv4Interface | ipaddress.IPv6Interface
7
+
8
+
9
+ class SubnetError(ValueError):
10
+ """Raised when the input cannot be parsed as an address or network."""
11
+
12
+
13
+ @dataclass(frozen=True, slots=True)
14
+ class SubnetResult:
15
+ query: str
16
+ version: int
17
+ address: str
18
+ network: str
19
+ prefixlen: int
20
+ netmask: str
21
+ hostmask: str
22
+ broadcast: str | None
23
+ first_host: str
24
+ last_host: str
25
+ total_addresses: int
26
+ usable_hosts: int
27
+ address_type: str
28
+ reverse_zone: str
29
+ address_binary: str | None
30
+ netmask_binary: str | None
31
+ compressed: str | None
32
+ exploded: str | None
33
+
34
+
35
+ def parse(query: str) -> Interface:
36
+ """Parse ``10.0.0.1/24``, ``10.0.0.1 255.255.255.0``, ``2001:db8::/32`` and similar.
37
+
38
+ An address without a prefix is treated as a single host (/32 or /128).
39
+ """
40
+ text = " ".join(query.split())
41
+ if not text:
42
+ raise SubnetError("Enter an IP address or network.")
43
+ parts = text.replace(" /", "/").replace("/ ", "/").split(" ")
44
+ if len(parts) > 2:
45
+ raise SubnetError("Use the form address/prefix, e.g. 192.168.1.10/24.")
46
+ text = "/".join(parts)
47
+ try:
48
+ return ipaddress.ip_interface(text)
49
+ except ValueError as exc:
50
+ raise SubnetError(f"“{query.strip()}” is not a valid IP address or network.") from exc
51
+
52
+
53
+ def _address_type(addr: ipaddress.IPv4Address | ipaddress.IPv6Address) -> str:
54
+ # Order matters: the more specific categories come first.
55
+ checks = [
56
+ ("is_loopback", "Loopback"),
57
+ ("is_link_local", "Link-local"),
58
+ ("is_multicast", "Multicast"),
59
+ ("is_unspecified", "Unspecified"),
60
+ ("is_reserved", "Reserved"),
61
+ ("is_private", "Private"),
62
+ ("is_global", "Public"),
63
+ ]
64
+ for attr, label in checks:
65
+ if getattr(addr, attr, False):
66
+ return label
67
+ return "Special-purpose"
68
+
69
+
70
+ def _binary(addr: ipaddress.IPv4Address) -> str:
71
+ bits = f"{int(addr):032b}"
72
+ return ".".join(bits[i : i + 8] for i in range(0, 32, 8))
73
+
74
+
75
+ def _reverse_zone(net: ipaddress.IPv4Network | ipaddress.IPv6Network) -> str:
76
+ """Smallest reverse-DNS zone that covers the whole network."""
77
+ labels = net.network_address.reverse_pointer.split(".")
78
+ if net.version == 4:
79
+ # labels: [d, c, b, a, "in-addr", "arpa"]; keep whole octets inside the prefix.
80
+ keep = net.prefixlen // 8
81
+ return ".".join(labels[4 - keep :]) if keep else "in-addr.arpa"
82
+ keep = net.prefixlen // 4 # one label per nibble
83
+ return ".".join(labels[32 - keep :]) if keep else "ip6.arpa"
84
+
85
+
86
+ def calculate(query: str) -> SubnetResult:
87
+ iface = parse(query)
88
+ net = iface.network
89
+ total = net.num_addresses
90
+
91
+ if net.version == 4 and net.prefixlen < 31:
92
+ first, last = net.network_address + 1, net.broadcast_address - 1
93
+ usable = total - 2
94
+ else:
95
+ # /31 point-to-point (RFC 3021), /32 host routes, and all IPv6 prefixes
96
+ # have no reserved network/broadcast addresses.
97
+ first, last = net.network_address, net.broadcast_address
98
+ usable = total
99
+
100
+ is_v4 = net.version == 4
101
+ return SubnetResult(
102
+ query=query.strip(),
103
+ version=net.version,
104
+ address=str(iface.ip),
105
+ network=str(net),
106
+ prefixlen=net.prefixlen,
107
+ netmask=str(net.netmask),
108
+ hostmask=str(net.hostmask),
109
+ broadcast=str(net.broadcast_address) if is_v4 else None,
110
+ first_host=str(first),
111
+ last_host=str(last),
112
+ total_addresses=total,
113
+ usable_hosts=usable,
114
+ address_type=_address_type(iface.ip),
115
+ reverse_zone=_reverse_zone(net),
116
+ address_binary=_binary(iface.ip) if is_v4 else None,
117
+ netmask_binary=_binary(net.netmask) if is_v4 else None,
118
+ compressed=None if is_v4 else iface.ip.compressed,
119
+ exploded=None if is_v4 else iface.ip.exploded,
120
+ )
@@ -0,0 +1,7 @@
1
+ """Optical fibre links, in metric units following ITU-T.
2
+
3
+ * ``fiber``: fibre performance classes (IEC), ITU-T fibre Recommendations, WDM bands, cables
4
+ * ``budget``: optical loss and power budgets (ITU-T G.957, G.959.1, G.984.2, G.Sup39)
5
+
6
+ Every quantity carries its unit in its name: ``_nm``, ``_km``, ``_db``, ``_dbm``, ``_db_per_km``.
7
+ """
@@ -0,0 +1,487 @@
1
+ """Optical loss budget and optical power budget, using ITU-T terminology.
2
+
3
+ Terms follow ITU-T G.957 / G.959.1 / G.984.2 and the system-design guidance in G.Sup39:
4
+
5
+ * Reference points: **S** (just after the transmitter's optical connector) and **R** (just
6
+ before the receiver's); the *optical path* is everything between them.
7
+ * **Mean launched power** (``P_min`` .. ``P_max``) at S, **receiver sensitivity** (``S_rx``, the
8
+ minimum mean received power) and **receiver overload** (``P_ovl``, the maximum) at R.
9
+ * **Attenuation** of the optical path, in dB. The *attenuation range* a system supports is
10
+ ``A_min = P_max - P_ovl`` to ``A_max = P_min - S_rx - P_pen - M``, with ``P_pen`` the maximum
11
+ optical path penalty and ``M`` a margin.
12
+ * **Link (path) attenuation**, the worst-case sum for a planned link (G.Sup39):
13
+ ``A = alpha * L + n_s * a_s + n_c * a_c + A_other + M_c`` with ``alpha`` the fibre
14
+ attenuation coefficient (dB/km), ``L`` the length, ``a_s`` / ``a_c`` the mean splice and
15
+ connector attenuations, and ``M_c`` the cable margin.
16
+
17
+ The defaults below are planning values, not figures from a Recommendation: take the numbers
18
+ that apply to your fibre, components and equipment from their datasheets. The equipment-class
19
+ presets are typical figures for GPON classes B+ and C+ (ITU-T G.984.2) and for common Ethernet
20
+ optics (vendor datasheets); check each against the module actually used.
21
+ """
22
+
23
+ import math
24
+ from dataclasses import dataclass
25
+
26
+
27
+ class OpticalError(ValueError):
28
+ """Raised when optical budget inputs are out of range or inconsistent."""
29
+
30
+
31
+ def check(value: float, what: str, low: float, high: float) -> float:
32
+ """Return ``value`` if it is a finite number from ``low`` to ``high``, else raise."""
33
+ if not math.isfinite(value) or not low <= value <= high:
34
+ raise OpticalError(f"{what.capitalize()} must be between {low:g} and {high:g}.")
35
+ return value
36
+
37
+
38
+ def g(value: float) -> str:
39
+ return f"{round(value, 4):g}"
40
+
41
+
42
+ # --- optical loss budget -----------------------------------------------------------------------
43
+
44
+ # Planning attenuation coefficients for single-mode fibre (ITU-T G.652.D class), dB/km. Cable
45
+ # maxima in vendor datasheets run about 0.36-0.40 at 1310 nm and 0.22-0.28 at 1550 nm.
46
+ WAVELENGTHS = {
47
+ 1310: ("1310 nm (O-band)", 0.40),
48
+ 1490: ("1490 nm", 0.30),
49
+ 1550: ("1550 nm (C-band)", 0.28),
50
+ 1625: ("1625 nm (L-band)", 0.30),
51
+ }
52
+ CONNECTOR_LOSS = 0.50 # dB per mated connector pair
53
+ SPLICE_LOSS = 0.10 # dB per fusion splice
54
+ DEFAULT_MARGIN = 3.0 # dB cable margin M_c
55
+ # Typical maximum insertion loss of planar (PLC) splitters, dB.
56
+ SPLITTERS = {
57
+ "none": 0.0,
58
+ "1x2": 4.0,
59
+ "1x4": 7.4,
60
+ "1x8": 10.7,
61
+ "1x16": 14.0,
62
+ "1x32": 17.4,
63
+ "1x64": 21.0,
64
+ }
65
+
66
+
67
+ @dataclass(frozen=True, slots=True)
68
+ class LossInput:
69
+ """A planned link. ``None`` coefficients and losses take the planning values above."""
70
+
71
+ wavelength_nm: int
72
+ length_km: float = 0.0
73
+ attenuation_db_per_km: float | None = None
74
+ connector_count: int = 0
75
+ connector_loss_db: float | None = None
76
+ splice_count: int = 0
77
+ splice_loss_db: float | None = None
78
+ splitter: str = "none"
79
+ other_loss_db: float = 0.0
80
+ margin_db: float = DEFAULT_MARGIN
81
+ budget_db: float | None = None # attenuation available from the power budget, if known
82
+
83
+ def __post_init__(self):
84
+ if self.wavelength_nm not in WAVELENGTHS:
85
+ raise OpticalError(
86
+ f"“{self.wavelength_nm}” is not a supported wavelength "
87
+ f"(use {', '.join(map(str, WAVELENGTHS))})."
88
+ )
89
+ if self.splitter not in SPLITTERS:
90
+ raise OpticalError(
91
+ f"“{self.splitter}” is not a supported splitter (use {', '.join(SPLITTERS)})."
92
+ )
93
+ check(self.length_km, "fibre length (km)", 0, 500)
94
+ if self.attenuation_db_per_km is not None:
95
+ check(self.attenuation_db_per_km, "attenuation coefficient (dB/km)", 0.01, 5)
96
+ check(self.connector_count, "connector count", 0, 200)
97
+ if self.connector_loss_db is not None:
98
+ check(self.connector_loss_db, "connector loss (dB)", 0, 5)
99
+ check(self.splice_count, "splice count", 0, 2000)
100
+ if self.splice_loss_db is not None:
101
+ check(self.splice_loss_db, "splice loss (dB)", 0, 5)
102
+ check(self.other_loss_db, "other loss (dB)", 0, 100)
103
+ check(self.margin_db, "margin (dB)", 0, 30)
104
+ if self.budget_db is not None:
105
+ check(self.budget_db, "available budget (dB)", 0.1, 100)
106
+
107
+
108
+ @dataclass(frozen=True, slots=True)
109
+ class LossItem:
110
+ key: str # "fibre", "connectors", "splices", "splitter", "other"
111
+ label: str
112
+ quantity: str
113
+ unit: str
114
+ loss_db: float
115
+
116
+
117
+ @dataclass(frozen=True, slots=True)
118
+ class LossResult:
119
+ inp: LossInput
120
+ items: tuple[LossItem, ...]
121
+ attenuation_db_per_km: float
122
+
123
+ tool_name = "Optical loss budget calculator"
124
+
125
+ @property
126
+ def title(self) -> str:
127
+ return f"{WAVELENGTHS[self.inp.wavelength_nm][0]} link, {g(self.inp.length_km)} km"
128
+
129
+ @property
130
+ def nominal_db(self) -> float:
131
+ """Attenuation of the optical path before margin."""
132
+ return sum(item.loss_db for item in self.items)
133
+
134
+ @property
135
+ def margin_db(self) -> float:
136
+ return self.inp.margin_db
137
+
138
+ @property
139
+ def total_db(self) -> float:
140
+ """Link attenuation, including the cable margin."""
141
+ return self.nominal_db + self.margin_db
142
+
143
+ @property
144
+ def budget_db(self) -> float | None:
145
+ return self.inp.budget_db
146
+
147
+ @property
148
+ def passes(self) -> bool:
149
+ return self.budget_db is None or self.total_db <= self.budget_db + 1e-9
150
+
151
+ @property
152
+ def remaining_db(self) -> float | None:
153
+ return None if self.budget_db is None else self.budget_db - self.total_db
154
+
155
+ @property
156
+ def used_pct(self) -> float | None:
157
+ return None if self.budget_db is None else self.total_db / self.budget_db * 100
158
+
159
+ @property
160
+ def formula(self) -> str:
161
+ i = self.inp
162
+ connector = i.connector_loss_db if i.connector_loss_db is not None else CONNECTOR_LOSS
163
+ splice = i.splice_loss_db if i.splice_loss_db is not None else SPLICE_LOSS
164
+ return (
165
+ f"A = α·L + n_s·a_s + n_c·a_c + A_other + M_c = "
166
+ f"{g(self.attenuation_db_per_km)}×{g(i.length_km)} + "
167
+ f"{i.splice_count}×{g(splice)} + "
168
+ f"{i.connector_count}×{g(connector)} + "
169
+ f"{g(SPLITTERS[i.splitter] + i.other_loss_db)} + {g(i.margin_db)} = "
170
+ f"{self.total_db:.2f} dB"
171
+ )
172
+
173
+ @property
174
+ def note(self) -> str:
175
+ return (
176
+ "Terms follow ITU-T G.957/G.959.1 and G.Sup39: the optical path runs from reference "
177
+ "point S to R, and its attenuation is the fibre attenuation (coefficient × length) "
178
+ "plus splice, connector and other component attenuation, plus a cable margin. "
179
+ "Attenuation coefficient, connector, splice and splitter figures are planning "
180
+ "values; replace them with the figures from your fibre, component and equipment "
181
+ "datasheets and the standard you are designing to."
182
+ )
183
+
184
+
185
+ def calculate_loss(inp: LossInput) -> LossResult:
186
+ alpha = (
187
+ inp.attenuation_db_per_km
188
+ if inp.attenuation_db_per_km is not None
189
+ else WAVELENGTHS[inp.wavelength_nm][1]
190
+ )
191
+ conn = inp.connector_loss_db if inp.connector_loss_db is not None else CONNECTOR_LOSS
192
+ splice = inp.splice_loss_db if inp.splice_loss_db is not None else SPLICE_LOSS
193
+ items = [
194
+ LossItem(
195
+ "fibre", "Fibre", f"{g(inp.length_km)} km", f"{g(alpha)} dB/km", alpha * inp.length_km
196
+ ),
197
+ LossItem(
198
+ "connectors",
199
+ "Connectors (mated pairs)",
200
+ str(inp.connector_count),
201
+ f"{g(conn)} dB",
202
+ conn * inp.connector_count,
203
+ ),
204
+ LossItem(
205
+ "splices",
206
+ "Splices",
207
+ str(inp.splice_count),
208
+ f"{g(splice)} dB",
209
+ splice * inp.splice_count,
210
+ ), # fmt: skip
211
+ ]
212
+ if inp.splitter != "none":
213
+ items.append(
214
+ LossItem(
215
+ "splitter",
216
+ f"Splitter {inp.splitter.replace('x', ':')}",
217
+ "1",
218
+ f"{g(SPLITTERS[inp.splitter])} dB",
219
+ SPLITTERS[inp.splitter],
220
+ )
221
+ )
222
+ if inp.other_loss_db:
223
+ items.append(LossItem("other", "Other components", "", "", inp.other_loss_db))
224
+ if all(item.loss_db == 0 for item in items):
225
+ raise OpticalError("Add a fibre length or at least one component.")
226
+ return LossResult(inp, tuple(items), alpha)
227
+
228
+
229
+ # --- optical power budget ----------------------------------------------------------------------
230
+
231
+
232
+ @dataclass(frozen=True, slots=True)
233
+ class PowerPreset:
234
+ label: str
235
+ launch_power_min_dbm: float # mean launched power at S
236
+ launch_power_max_dbm: float
237
+ rx_sensitivity_dbm: float # minimum mean received power at R
238
+ rx_overload_dbm: float # maximum mean received power at R
239
+ path_penalty_db: float = 0.0 # maximum optical path penalty
240
+ margin_db: float = 0.0 # system margin
241
+ attenuation_range_db: tuple[float, float] | None = None # range the class specifies
242
+ family: str = ""
243
+
244
+
245
+ ITU = "ITU-T G.984.2 GPON"
246
+ ETHERNET = "Ethernet optics (typical module datasheet values)"
247
+ OTHER = "Other"
248
+ # The IEEE 802.3 / module values below are typical figures from vendor datasheets (average
249
+ # launched power, sensitivity, overload); products vary, so confirm them against the module's
250
+ # datasheet and the clause it is built to.
251
+ POWER_PRESETS = {
252
+ "gpon-b-plus": PowerPreset(
253
+ "GPON Class B+ downstream, 1490 nm",
254
+ 1.5,
255
+ 5,
256
+ -28,
257
+ -8,
258
+ attenuation_range_db=(13, 28),
259
+ family=ITU,
260
+ ),
261
+ "gpon-b-plus-up": PowerPreset(
262
+ "GPON Class B+ upstream, 1310 nm (check launch power)",
263
+ 0.5,
264
+ 5,
265
+ -28,
266
+ -8,
267
+ attenuation_range_db=(13, 28),
268
+ family=ITU,
269
+ ), # fmt: skip
270
+ "gpon-c-plus": PowerPreset(
271
+ "GPON Class C+ downstream, 1490 nm",
272
+ 3,
273
+ 7,
274
+ -32,
275
+ -12,
276
+ attenuation_range_db=(17, 32),
277
+ family=ITU,
278
+ ),
279
+ "gpon-c-plus-up": PowerPreset(
280
+ "GPON Class C+ upstream, 1310 nm (check launch power)",
281
+ 0.5,
282
+ 5,
283
+ -32,
284
+ -12,
285
+ attenuation_range_db=(17, 32),
286
+ family=ITU,
287
+ ), # fmt: skip
288
+ "1000base-lx": PowerPreset("1000BASE-LX, 1310 nm, 10 km", -9.5, -3, -19, -3, family=ETHERNET),
289
+ "1000base-bx10-d": PowerPreset(
290
+ "1000BASE-BX10-D, 1490 nm (downstream), 10 km", -9, -3, -19.5, -3, family=ETHERNET
291
+ ),
292
+ "1000base-bx10-u": PowerPreset(
293
+ "1000BASE-BX10-U, 1310 nm (upstream), 10 km", -9, -3, -19.5, -3, family=ETHERNET
294
+ ),
295
+ "1000base-zx": PowerPreset("1000BASE-ZX, 1550 nm, 70 km", 0, 5, -22.5, -3, family=ETHERNET),
296
+ "10gbase-lr": PowerPreset("10GBASE-LR, 1310 nm, 10 km", -8.2, 0.5, -14.4, 0.5, family=ETHERNET),
297
+ "10gbase-er": PowerPreset("10GBASE-ER, 1550 nm, 40 km", -4.7, 4, -15.8, -1, family=ETHERNET),
298
+ "10gbase-zr": PowerPreset("10GBASE-ZR, 1550 nm, 80 km", 0, 4, -24, -7, family=ETHERNET),
299
+ "custom": PowerPreset("Custom equipment", 0, 3, -20, -3, family=OTHER),
300
+ }
301
+
302
+
303
+ @dataclass(frozen=True, slots=True)
304
+ class PowerInput:
305
+ """Equipment figures at reference points S and R, and the planned path attenuation."""
306
+
307
+ preset: str
308
+ launch_power_min_dbm: float
309
+ launch_power_max_dbm: float
310
+ rx_sensitivity_dbm: float
311
+ rx_overload_dbm: float
312
+ path_penalty_db: float = 0.0
313
+ margin_db: float = 0.0
314
+ attenuation_max_db: float | None = None # worst-case (largest) path attenuation
315
+ attenuation_min_db: float | None = None # best-case (smallest); defaults to the maximum
316
+
317
+ def __post_init__(self):
318
+ if self.preset not in POWER_PRESETS:
319
+ raise OpticalError(
320
+ f"“{self.preset}” is not a supported equipment preset "
321
+ f"(use {', '.join(POWER_PRESETS)})."
322
+ )
323
+ check(self.launch_power_min_dbm, "minimum mean launched power (dBm)", -60, 30)
324
+ check(self.launch_power_max_dbm, "maximum mean launched power (dBm)", -60, 30)
325
+ check(self.rx_sensitivity_dbm, "receiver sensitivity (dBm)", -70, 30)
326
+ check(self.rx_overload_dbm, "receiver overload (dBm)", -70, 30)
327
+ check(self.path_penalty_db, "maximum optical path penalty (dB)", 0, 20)
328
+ check(self.margin_db, "margin (dB)", 0, 30)
329
+ if self.attenuation_max_db is not None:
330
+ check(self.attenuation_max_db, "path attenuation (dB)", 0, 100)
331
+ if self.attenuation_min_db is not None:
332
+ check(self.attenuation_min_db, "minimum path attenuation (dB)", 0, 100)
333
+ if self.launch_power_min_dbm > self.launch_power_max_dbm:
334
+ raise OpticalError("Minimum mean launched power cannot exceed the maximum.")
335
+ if self.rx_overload_dbm <= self.rx_sensitivity_dbm:
336
+ raise OpticalError("Receiver overload must be higher than receiver sensitivity.")
337
+ if (
338
+ self.attenuation_max_db is not None
339
+ and self.attenuation_min_db is not None
340
+ and self.attenuation_min_db > self.attenuation_max_db
341
+ ):
342
+ raise OpticalError("Minimum path attenuation cannot exceed the maximum.")
343
+
344
+ @classmethod
345
+ def from_preset(cls, preset: str, **overrides: float | None) -> PowerInput:
346
+ """The preset's figures, with any given (not ``None``) values in their place."""
347
+ base = POWER_PRESETS.get(preset)
348
+ if base is None:
349
+ raise OpticalError(
350
+ f"“{preset}” is not a supported equipment preset (use {', '.join(POWER_PRESETS)})."
351
+ )
352
+ values = {
353
+ "launch_power_min_dbm": base.launch_power_min_dbm,
354
+ "launch_power_max_dbm": base.launch_power_max_dbm,
355
+ "rx_sensitivity_dbm": base.rx_sensitivity_dbm,
356
+ "rx_overload_dbm": base.rx_overload_dbm,
357
+ "path_penalty_db": base.path_penalty_db,
358
+ "margin_db": base.margin_db,
359
+ }
360
+ values.update({key: value for key, value in overrides.items() if value is not None})
361
+ return cls(preset=preset, **values)
362
+
363
+
364
+ @dataclass(frozen=True, slots=True)
365
+ class PowerResult:
366
+ inp: PowerInput
367
+
368
+ tool_name = "Optical power budget calculator"
369
+
370
+ @property
371
+ def preset(self) -> PowerPreset:
372
+ return POWER_PRESETS[self.inp.preset]
373
+
374
+ @property
375
+ def title(self) -> str:
376
+ return self.preset.label
377
+
378
+ @property
379
+ def max_attenuation_db(self) -> float:
380
+ """Largest attenuation the link may have: P_min - S_rx - P_pen - M."""
381
+ i = self.inp
382
+ return i.launch_power_min_dbm - i.rx_sensitivity_dbm - i.path_penalty_db - i.margin_db
383
+
384
+ @property
385
+ def min_attenuation_db(self) -> float:
386
+ """Smallest attenuation that keeps the receiver out of overload: P_max - P_ovl."""
387
+ return self.inp.launch_power_max_dbm - self.inp.rx_overload_dbm
388
+
389
+ @property
390
+ def range_valid(self) -> bool:
391
+ return self.max_attenuation_db >= self.min_attenuation_db - 1e-9
392
+
393
+ @property
394
+ def has_link(self) -> bool:
395
+ return self.inp.attenuation_max_db is not None
396
+
397
+ @property
398
+ def best_attenuation_db(self) -> float | None:
399
+ i = self.inp
400
+ if i.attenuation_max_db is None:
401
+ return None
402
+ return i.attenuation_max_db if i.attenuation_min_db is None else i.attenuation_min_db
403
+
404
+ @property
405
+ def rx_power_min_dbm(self) -> float | None:
406
+ """Lowest mean received power at R: P_min - A_max."""
407
+ i = self.inp
408
+ return (
409
+ None if i.attenuation_max_db is None else i.launch_power_min_dbm - i.attenuation_max_db
410
+ )
411
+
412
+ @property
413
+ def rx_power_max_dbm(self) -> float | None:
414
+ """Highest mean received power at R: P_max - A_min."""
415
+ return (
416
+ None if not self.has_link else self.inp.launch_power_max_dbm - self.best_attenuation_db
417
+ )
418
+
419
+ @property
420
+ def sensitivity_margin_db(self) -> float | None:
421
+ """Margin above receiver sensitivity at worst case, after the path penalty."""
422
+ if self.rx_power_min_dbm is None:
423
+ return None
424
+ return self.rx_power_min_dbm - self.inp.path_penalty_db - self.inp.rx_sensitivity_dbm
425
+
426
+ @property
427
+ def overload_headroom_db(self) -> float | None:
428
+ """How far the highest received power is below the receiver overload."""
429
+ if self.rx_power_max_dbm is None:
430
+ return None
431
+ return self.inp.rx_overload_dbm - self.rx_power_max_dbm
432
+
433
+ @property
434
+ def too_lossy(self) -> bool:
435
+ return self.has_link and self.sensitivity_margin_db < self.inp.margin_db - 1e-9
436
+
437
+ @property
438
+ def overloaded(self) -> bool:
439
+ return self.has_link and self.overload_headroom_db < -1e-9
440
+
441
+ @property
442
+ def passes(self) -> bool:
443
+ if not self.range_valid:
444
+ return False
445
+ return not (self.too_lossy or self.overloaded)
446
+
447
+ @property
448
+ def used_pct(self) -> float | None:
449
+ if self.inp.attenuation_max_db is None or self.max_attenuation_db <= 0:
450
+ return None
451
+ return self.inp.attenuation_max_db / self.max_attenuation_db * 100
452
+
453
+ @property
454
+ def problem(self) -> str | None:
455
+ if not self.range_valid:
456
+ return (
457
+ "These equipment values leave no usable attenuation range: the transmitter's "
458
+ "lowest launched power minus penalty and margin is too weak to stay above the "
459
+ "receiver sensitivity at the attenuation needed to stay below overload."
460
+ )
461
+ if self.too_lossy:
462
+ return (
463
+ "The path attenuation exceeds the power budget: the receiver would see too "
464
+ "little power."
465
+ )
466
+ if self.overloaded:
467
+ return (
468
+ "The path attenuation is below the minimum: the receiver would be overloaded. "
469
+ "Add an attenuator."
470
+ )
471
+ return None
472
+
473
+ @property
474
+ def note(self) -> str:
475
+ return (
476
+ "Terms follow ITU-T G.957/G.959.1/G.984.2: mean launched power at reference point S, "
477
+ "receiver sensitivity and overload at R, maximum optical path penalty, and the "
478
+ "attenuation range between them. Enter the figures for your equipment's optics class "
479
+ "from its datasheet or the Recommendation. The GPON presets are the values tabulated "
480
+ "in G.984.2; the upstream launch power in particular should be checked against the "
481
+ "Recommendation. The Ethernet presets are typical module datasheet figures. "
482
+ "Put any cable margin on the loss budget, not here, so it is not counted twice."
483
+ )
484
+
485
+
486
+ def calculate_power(inp: PowerInput) -> PowerResult:
487
+ return PowerResult(inp)