ictdesigntools 0.0.1__tar.gz

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.
Files changed (27) hide show
  1. ictdesigntools-0.0.1/LICENSE +21 -0
  2. ictdesigntools-0.0.1/PKG-INFO +75 -0
  3. ictdesigntools-0.0.1/README.md +52 -0
  4. ictdesigntools-0.0.1/pyproject.toml +73 -0
  5. ictdesigntools-0.0.1/pyproject.toml.orig +56 -0
  6. ictdesigntools-0.0.1/src/ictdesigntools/__init__.py +16 -0
  7. ictdesigntools-0.0.1/src/ictdesigntools/cabling/__init__.py +1 -0
  8. ictdesigntools-0.0.1/src/ictdesigntools/cabling/cables.py +387 -0
  9. ictdesigntools-0.0.1/src/ictdesigntools/cabling/twistedpair.py +0 -0
  10. ictdesigntools-0.0.1/src/ictdesigntools/geometry/__init__.py +0 -0
  11. ictdesigntools-0.0.1/src/ictdesigntools/geometry/packing.py +187 -0
  12. ictdesigntools-0.0.1/src/ictdesigntools/locations/__init__.py +0 -0
  13. ictdesigntools-0.0.1/src/ictdesigntools/locations/sites.py +0 -0
  14. ictdesigntools-0.0.1/src/ictdesigntools/network/__init__.py +0 -0
  15. ictdesigntools-0.0.1/src/ictdesigntools/network/subnet.py +120 -0
  16. ictdesigntools-0.0.1/src/ictdesigntools/optical/__init__.py +7 -0
  17. ictdesigntools-0.0.1/src/ictdesigntools/optical/budget.py +487 -0
  18. ictdesigntools-0.0.1/src/ictdesigntools/optical/fiber.py +167 -0
  19. ictdesigntools-0.0.1/src/ictdesigntools/pathways/__init__.py +0 -0
  20. ictdesigntools-0.0.1/src/ictdesigntools/pathways/conduit.py +444 -0
  21. ictdesigntools-0.0.1/src/ictdesigntools/pathways/ductbank.py +679 -0
  22. ictdesigntools-0.0.1/src/ictdesigntools/pathways/microtrench.py +547 -0
  23. ictdesigntools-0.0.1/src/ictdesigntools/pathways/pull.py +282 -0
  24. ictdesigntools-0.0.1/src/ictdesigntools/pathways/tray.py +441 -0
  25. ictdesigntools-0.0.1/src/ictdesigntools/projects/__init__.py +0 -0
  26. ictdesigntools-0.0.1/src/ictdesigntools/projects/management.py +6 -0
  27. ictdesigntools-0.0.1/src/ictdesigntools/py.typed +0 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Eron Lloyd
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,75 @@
1
+ Metadata-Version: 2.4
2
+ Name: ictdesigntools
3
+ Version: 0.0.1
4
+ Summary: Calculations and reference data for ICT design: pathways, cabling, optical links and networks.
5
+ Keywords: ICT,telecommunications,structured cabling,conduit fill,cable tray,fiber optics,AEC
6
+ Author: Eron Lloyd
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: Intended Audience :: Other Audience
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.14
15
+ Classifier: Programming Language :: Python :: 3.15
16
+ Classifier: Topic :: Scientific/Engineering
17
+ Classifier: Typing :: Typed
18
+ Requires-Python: >=3.14
19
+ Project-URL: Homepage, https://github.com/eronlloyd/ictdesigntools
20
+ Project-URL: Repository, https://github.com/eronlloyd/ictdesigntools
21
+ Project-URL: Issues, https://github.com/eronlloyd/ictdesigntools/issues
22
+ Description-Content-Type: text/markdown
23
+
24
+ # ictdesigntools
25
+
26
+ Calculations and reference data for ICT design: pathways, cabling, optical links and networks.
27
+ It is the engine behind the [ICT Design Tools](https://github.com/eronlloyd/ictdesigntoolsweb)
28
+ website, and it is meant to be used directly in scripts, notebooks and computational design
29
+ tools.
30
+
31
+ > Not yet published on PyPI. Until then, install from Git.
32
+
33
+ ## Install
34
+
35
+ ```sh
36
+ uv add "ictdesigntools @ git+https://github.com/eronlloyd/ictdesigntools"
37
+ ```
38
+
39
+ Python 3.14 or later. No runtime dependencies.
40
+
41
+ ## Use
42
+
43
+ ```python
44
+ from ictdesigntools.cabling.cables import parse_cables
45
+ from ictdesigntools.pathways import conduit
46
+
47
+ cables = parse_cables("cat6a:12/0.28:3")
48
+ result = conduit.calculate("emt", "2", cables)
49
+ print(f"{result.fill_pct:.1f}% of {result.limit_pct:.0f}% allowed")
50
+ ```
51
+
52
+ | Module | What it does | Sources |
53
+ | --- | --- | --- |
54
+ | `pathways.conduit` | Conduit fill | NEC Chapter 9, Tables 1 and 4 |
55
+ | `pathways.pull` | Cable pulling tension along a run | Capstan equation, IEEE 1185 practice |
56
+ | `pathways.tray` | Cable tray fill and load | NEC 392.22(A), TIA-569 / BICSI practice |
57
+ | `pathways.ductbank` | Concrete-encased duct bank layout | ASTM F512, NEMA TC 2, TC 6/8 |
58
+ | `pathways.microtrench` | Microduct and FuturePath layout in a microtrench | Dura-Line data sheets |
59
+ | `cabling.cables` | Cable lists, presets, weights and tension limits | Manufacturer typicals |
60
+ | `cabling.optical` | Fibre performance classes, ITU-T recommendations, WDM bands | IEC 60793, ITU-T G.65x |
61
+ | `transmission.optical` | Optical loss and power budgets | ITU-T G.957, G.959.1, G.984.2, G.Sup39 |
62
+ | `network.subnet` | IPv4 and IPv6 subnets | Python `ipaddress` |
63
+ | `geometry.packing` | Circle packing for cable cross-sections | |
64
+
65
+ The notebooks in `notebooks/` derive the formulas with SymPy and are the start of the reference
66
+ material for each tool.
67
+
68
+ ## Develop
69
+
70
+ ```sh
71
+ uv sync
72
+ uv run pytest
73
+ uv run ruff check src tests
74
+ uv build && uv run twine check dist/* # builds only; nothing is uploaded
75
+ ```
@@ -0,0 +1,52 @@
1
+ # ictdesigntools
2
+
3
+ Calculations and reference data for ICT design: pathways, cabling, optical links and networks.
4
+ It is the engine behind the [ICT Design Tools](https://github.com/eronlloyd/ictdesigntoolsweb)
5
+ website, and it is meant to be used directly in scripts, notebooks and computational design
6
+ tools.
7
+
8
+ > Not yet published on PyPI. Until then, install from Git.
9
+
10
+ ## Install
11
+
12
+ ```sh
13
+ uv add "ictdesigntools @ git+https://github.com/eronlloyd/ictdesigntools"
14
+ ```
15
+
16
+ Python 3.14 or later. No runtime dependencies.
17
+
18
+ ## Use
19
+
20
+ ```python
21
+ from ictdesigntools.cabling.cables import parse_cables
22
+ from ictdesigntools.pathways import conduit
23
+
24
+ cables = parse_cables("cat6a:12/0.28:3")
25
+ result = conduit.calculate("emt", "2", cables)
26
+ print(f"{result.fill_pct:.1f}% of {result.limit_pct:.0f}% allowed")
27
+ ```
28
+
29
+ | Module | What it does | Sources |
30
+ | --- | --- | --- |
31
+ | `pathways.conduit` | Conduit fill | NEC Chapter 9, Tables 1 and 4 |
32
+ | `pathways.pull` | Cable pulling tension along a run | Capstan equation, IEEE 1185 practice |
33
+ | `pathways.tray` | Cable tray fill and load | NEC 392.22(A), TIA-569 / BICSI practice |
34
+ | `pathways.ductbank` | Concrete-encased duct bank layout | ASTM F512, NEMA TC 2, TC 6/8 |
35
+ | `pathways.microtrench` | Microduct and FuturePath layout in a microtrench | Dura-Line data sheets |
36
+ | `cabling.cables` | Cable lists, presets, weights and tension limits | Manufacturer typicals |
37
+ | `cabling.optical` | Fibre performance classes, ITU-T recommendations, WDM bands | IEC 60793, ITU-T G.65x |
38
+ | `transmission.optical` | Optical loss and power budgets | ITU-T G.957, G.959.1, G.984.2, G.Sup39 |
39
+ | `network.subnet` | IPv4 and IPv6 subnets | Python `ipaddress` |
40
+ | `geometry.packing` | Circle packing for cable cross-sections | |
41
+
42
+ The notebooks in `notebooks/` derive the formulas with SymPy and are the start of the reference
43
+ material for each tool.
44
+
45
+ ## Develop
46
+
47
+ ```sh
48
+ uv sync
49
+ uv run pytest
50
+ uv run ruff check src tests
51
+ uv build && uv run twine check dist/* # builds only; nothing is uploaded
52
+ ```
@@ -0,0 +1,73 @@
1
+ [project]
2
+ name = "ictdesigntools"
3
+ version = "0.0.1"
4
+ description = "Calculations and reference data for ICT design: pathways, cabling, optical links and networks."
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.14"
9
+ dependencies = []
10
+ keywords = [
11
+ "ICT",
12
+ "telecommunications",
13
+ "structured cabling",
14
+ "conduit fill",
15
+ "cable tray",
16
+ "fiber optics",
17
+ "AEC",
18
+ ]
19
+ classifiers = [
20
+ "Development Status :: 3 - Alpha",
21
+ "Intended Audience :: Science/Research",
22
+ "Intended Audience :: Other Audience",
23
+ "Operating System :: OS Independent",
24
+ "Programming Language :: Python :: 3",
25
+ "Programming Language :: Python :: 3.14",
26
+ "Programming Language :: Python :: 3.15",
27
+ "Topic :: Scientific/Engineering",
28
+ "Typing :: Typed",
29
+ ]
30
+
31
+ [[project.authors]]
32
+ name = "Eron Lloyd"
33
+
34
+ [project.urls]
35
+ Homepage = "https://github.com/eronlloyd/ictdesigntools"
36
+ Repository = "https://github.com/eronlloyd/ictdesigntools"
37
+ Issues = "https://github.com/eronlloyd/ictdesigntools/issues"
38
+
39
+ [build-system]
40
+ requires = ["uv_build>=0.11,<0.12"]
41
+ build-backend = "uv_build"
42
+
43
+ [dependency-groups]
44
+ dev = [
45
+ "coverage>=7.17.3",
46
+ "ipykernel>=7.4.0",
47
+ "numpy>=2.5.4",
48
+ "pytest>=9.2.0",
49
+ "ruff>=0.17.5",
50
+ "sympy>=1.14.0",
51
+ "twine>=6.2.0",
52
+ ]
53
+
54
+ [tool.pytest.ini_options]
55
+ testpaths = ["tests"]
56
+
57
+ [tool.coverage.run]
58
+ source = ["src/ictdesigntools"]
59
+
60
+ [tool.ruff]
61
+ line-length = 100
62
+ target-version = "py314"
63
+ extend-exclude = ["notebooks"]
64
+
65
+ [tool.ruff.lint]
66
+ select = [
67
+ "E",
68
+ "F",
69
+ "W",
70
+ "I",
71
+ "B",
72
+ "UP",
73
+ ]
@@ -0,0 +1,56 @@
1
+ [project]
2
+ name = "ictdesigntools"
3
+ version = "0.0.1"
4
+ description = "Calculations and reference data for ICT design: pathways, cabling, optical links and networks."
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ authors = [{ name = "Eron Lloyd" }]
9
+ requires-python = ">=3.14"
10
+ dependencies = []
11
+ keywords = ["ICT", "telecommunications", "structured cabling", "conduit fill", "cable tray", "fiber optics", "AEC"]
12
+ classifiers = [
13
+ "Development Status :: 3 - Alpha",
14
+ "Intended Audience :: Science/Research",
15
+ "Intended Audience :: Other Audience",
16
+ "Operating System :: OS Independent",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.14",
19
+ "Programming Language :: Python :: 3.15",
20
+ "Topic :: Scientific/Engineering",
21
+ "Typing :: Typed",
22
+ ]
23
+
24
+ [project.urls]
25
+ Homepage = "https://github.com/eronlloyd/ictdesigntools"
26
+ Repository = "https://github.com/eronlloyd/ictdesigntools"
27
+ Issues = "https://github.com/eronlloyd/ictdesigntools/issues"
28
+
29
+ [build-system]
30
+ requires = ["uv_build>=0.11,<0.12"]
31
+ build-backend = "uv_build"
32
+
33
+ [dependency-groups]
34
+ dev = [
35
+ "coverage>=7.17.3",
36
+ "ipykernel>=7.4.0",
37
+ "numpy>=2.5.4",
38
+ "pytest>=9.2.0",
39
+ "ruff>=0.17.5",
40
+ "sympy>=1.14.0",
41
+ "twine>=6.2.0",
42
+ ]
43
+
44
+ [tool.pytest.ini_options]
45
+ testpaths = ["tests"]
46
+
47
+ [tool.coverage.run]
48
+ source = ["src/ictdesigntools"]
49
+
50
+ [tool.ruff]
51
+ line-length = 100
52
+ target-version = "py314"
53
+ extend-exclude = ["notebooks"]
54
+
55
+ [tool.ruff.lint]
56
+ select = ["E", "F", "W", "I", "B", "UP"]
@@ -0,0 +1,16 @@
1
+ """Calculations and reference data for ICT design.
2
+
3
+ Subpackages:
4
+
5
+ * ``pathways``: conduit fill, cable tray fill and load, pulling tension, duct banks, microtrenches
6
+ * ``cabling``: cable lists and presets, fibre and twisted-pair cable types
7
+ * ``transmission``: optical loss and power budgets
8
+ * ``network``: IPv4 and IPv6 subnets
9
+ * ``geometry``: circle packing for cable cross-sections
10
+ * ``locations``, ``projects``: sites and project planning (early work)
11
+
12
+ The package has no runtime dependencies. File formats (PDF, SVG, DXF) are left to callers such as
13
+ the ICT Design Tools website.
14
+ """
15
+
16
+ __version__ = "0.0.1"
@@ -0,0 +1,387 @@
1
+ """Cable list handling shared by the fill calculators (conduit, cable tray).
2
+
3
+ A cable list is a path-friendly string such as ``cat6:12/cat6a:4/0.28:3``: each item is a
4
+ preset name or an outside diameter in inches, a colon, and a count. An item may end with
5
+ ``:w=`` and a weight in pounds per foot of one cable, e.g. ``cat6:12:w=0.03``, which overrides
6
+ the preset's typical weight (custom cables have none unless one is given), and with ``:t=`` and
7
+ the most one cable may be pulled with, in pounds-force, e.g. ``cat6:12:t=25``.
8
+ """
9
+
10
+ import math
11
+ from collections.abc import Callable, Iterable, Sequence
12
+ from dataclasses import dataclass, replace
13
+ from urllib.parse import parse_qsl
14
+
15
+ MAX_LINES = 20
16
+ MAX_COUNT = 1000
17
+ MIN_OD, MAX_OD = 0.05, 2.0 # inches
18
+ WEIGHT_PREFIX = "w="
19
+ MAX_WEIGHT = 5.0 # lb/ft of one cable
20
+ TENSION_PREFIX = "t="
21
+ MAX_TENSION = 10000.0 # lbf, one cable
22
+
23
+ CUSTOM = "custom"
24
+
25
+
26
+ NAME_PREFIX = "n="
27
+ MAX_NAME_LENGTH = 40
28
+ _NAME_FORBIDDEN = str.maketrans("", "", '/:\\?#%&<>"')
29
+
30
+
31
+ def clean_name(text: str) -> str:
32
+ """A subduct name made safe for a URL path segment and for report text."""
33
+ return " ".join(text.translate(_NAME_FORBIDDEN).split())[:MAX_NAME_LENGTH].strip()
34
+
35
+
36
+ class FillError(ValueError):
37
+ """Raised when a conduit, tray, size or cable list cannot be understood."""
38
+
39
+
40
+ @dataclass(frozen=True, slots=True)
41
+ class CableType:
42
+ label: str
43
+ od: float # nominal outside diameter, inches
44
+ weight: float # typical weight, lb per foot of one cable
45
+ max_tension: float # most one cable may be pulled with, lbf
46
+
47
+
48
+ # Typical nominal diameters and weights (from manufacturers' data sheets, rounded); real
49
+ # cables vary by manufacturer and jacket, so custom ODs and weights are supported. Pulling
50
+ # limits: 25 lbf (110 N) for 4-pair balanced twisted-pair cable per ANSI/TIA-568; the coax
51
+ # figures are at the low end of manufacturers' ratings, which vary widely.
52
+ CABLE_TYPES = {
53
+ "cat5e": CableType("Cat 5e UTP", 0.20, 0.022, 25),
54
+ "cat6": CableType("Cat 6 UTP", 0.23, 0.026, 25),
55
+ "cat6a": CableType("Cat 6A UTP", 0.30, 0.040, 25),
56
+ "cat6a-s": CableType("Cat 6A shielded", 0.33, 0.045, 25),
57
+ "rg59": CableType("RG-59 coax", 0.24, 0.022, 50),
58
+ "rg6": CableType("RG-6 coax", 0.27, 0.030, 65),
59
+ "rg11": CableType("RG-11 coax", 0.41, 0.062, 140),
60
+ }
61
+
62
+
63
+ @dataclass(frozen=True, slots=True)
64
+ class CableLine:
65
+ token: str # preset slug, or the OD as text for custom cables
66
+ label: str
67
+ od: float
68
+ count: int
69
+ weight: float | None = None # lb/ft of one cable; None when unknown
70
+ weight_set: bool = False # the weight was given in the cable list, not a preset default
71
+ max_tension: float | None = None # most one cable may be pulled with, lbf
72
+ tension_set: bool = False # the pulling limit was given in the cable list
73
+
74
+ @property
75
+ def options(self) -> str:
76
+ """The ``:w=…:t=…`` part of the spec, for values given rather than taken from a preset."""
77
+ text = f":{WEIGHT_PREFIX}{self.weight:g}" if self.weight_set else ""
78
+ if self.tension_set:
79
+ text += f":{TENSION_PREFIX}{self.max_tension:g}"
80
+ return text
81
+
82
+ @property
83
+ def key(self) -> str:
84
+ """What makes two lines the same cable: the type and any values given for it."""
85
+ return self.token + self.options
86
+
87
+ @property
88
+ def spec(self) -> str:
89
+ return f"{self.token}:{self.count}{self.options}"
90
+
91
+ @property
92
+ def weight_total(self) -> float | None:
93
+ return None if self.weight is None else self.weight * self.count
94
+
95
+ @property
96
+ def area_each(self) -> float:
97
+ return math.pi / 4 * self.od**2
98
+
99
+ @property
100
+ def area_total(self) -> float:
101
+ return self.area_each * self.count
102
+
103
+
104
+ def parse_cables(spec: str) -> list[CableLine]:
105
+ """Parse ``cat6:12/cat6a:4/0.28:3`` into cable lines.
106
+
107
+ The part before the colon is a preset name or an outside diameter in inches.
108
+ """
109
+ tokens = [t for t in spec.strip().strip("/").split("/") if t]
110
+ if not tokens:
111
+ raise FillError("Add at least one cable.")
112
+ if len(tokens) > MAX_LINES:
113
+ raise FillError(f"Use at most {MAX_LINES} cable lines.")
114
+
115
+ lines = []
116
+ for item in tokens:
117
+ name, sep, rest = item.partition(":")
118
+ if not sep:
119
+ raise FillError(f"“{item}” needs a count, e.g. {item}:4.")
120
+ count_text, *options = rest.split(":")
121
+ weight = tension = None
122
+ for option in options:
123
+ if option.lower().startswith(TENSION_PREFIX):
124
+ tension = parse_tension(option)
125
+ else:
126
+ weight = parse_weight(option)
127
+ try:
128
+ count = int(count_text)
129
+ except ValueError:
130
+ raise FillError(f"“{count_text}” is not a valid cable count.") from None
131
+ if not 1 <= count <= MAX_COUNT:
132
+ raise FillError(f"Cable count must be between 1 and {MAX_COUNT}.")
133
+
134
+ name = name.strip().lower()
135
+ extras = ([f"{weight:g} lb/ft"] if weight is not None else []) + (
136
+ [f"{tension:g} lbf max pull"] if tension is not None else []
137
+ )
138
+ if name in CABLE_TYPES:
139
+ cable = CABLE_TYPES[name]
140
+ label = ", ".join([cable.label, *extras])
141
+ lines.append(
142
+ CableLine(name, label, cable.od, count,
143
+ cable.weight if weight is None else weight, weight is not None,
144
+ cable.max_tension if tension is None else tension, tension is not None)
145
+ ) # fmt: skip
146
+ continue
147
+ try:
148
+ od = float(name)
149
+ except ValueError:
150
+ raise FillError(
151
+ f"“{name}” is not a known cable type or an outside diameter in inches."
152
+ ) from None
153
+ if not (math.isfinite(od) and MIN_OD <= od <= MAX_OD):
154
+ raise FillError(f"Outside diameter must be between {MIN_OD} and {MAX_OD} inches.")
155
+ lines.append(
156
+ CableLine(f"{od:g}", f"Custom {od:g} in OD", od, count, weight, weight is not None,
157
+ tension, tension is not None)
158
+ ) # fmt: skip
159
+ return lines
160
+
161
+
162
+ def parse_weight(text: str) -> float:
163
+ """Read ``w=0.03`` (lb/ft of one cable)."""
164
+ if not text.lower().startswith(WEIGHT_PREFIX):
165
+ raise FillError(f"“{text}” is not understood; give a cable weight as w=0.03 (lb/ft).")
166
+ value = text[len(WEIGHT_PREFIX) :]
167
+ try:
168
+ weight = float(value)
169
+ except ValueError:
170
+ raise FillError(f"“{value}” is not a valid cable weight in lb/ft.") from None
171
+ if not (math.isfinite(weight) and 0 < weight <= MAX_WEIGHT):
172
+ raise FillError(f"Cable weight must be more than 0 and at most {MAX_WEIGHT:g} lb/ft.")
173
+ return weight
174
+
175
+
176
+ def parse_tension(text: str) -> float:
177
+ """Read ``t=25`` (the most one cable may be pulled with, lbf)."""
178
+ value = text[len(TENSION_PREFIX) :]
179
+ try:
180
+ tension = float(value)
181
+ except ValueError:
182
+ raise FillError(f"“{value}” is not a valid pulling limit in lbf.") from None
183
+ if not (math.isfinite(tension) and 0 < tension <= MAX_TENSION):
184
+ raise FillError(
185
+ f"A cable’s pulling limit must be more than 0 and at most {MAX_TENSION:g} lbf."
186
+ )
187
+ return tension
188
+
189
+
190
+ def build_spec(rows: Iterable[dict[str, str]]) -> str:
191
+ """Turn submitted form rows (cable, od, count) into a path spec; blank counts are skipped."""
192
+ parts = []
193
+ for row in rows:
194
+ count = row.get("count", "").strip()
195
+ if not count:
196
+ continue
197
+ cable = row.get("cable", "").strip()
198
+ if cable == CUSTOM:
199
+ od = row.get("od", "").strip()
200
+ if not od:
201
+ raise FillError("Enter an outside diameter for each custom cable.")
202
+ cable = od
203
+ weight = row.get("weight", "").strip()
204
+ tension = row.get("tension", "").strip()
205
+ part = f"{cable}:{count}"
206
+ if weight:
207
+ part += f":{WEIGHT_PREFIX}{weight}"
208
+ if tension:
209
+ part += f":{TENSION_PREFIX}{tension}"
210
+ parts.append(part)
211
+ return "/".join(parts)
212
+
213
+
214
+ def rows_from_lines(lines: Sequence[CableLine]) -> list[dict[str, str]]:
215
+ return [
216
+ {
217
+ "cable": line.token if line.token in CABLE_TYPES else CUSTOM,
218
+ "od": "" if line.token in CABLE_TYPES else line.token,
219
+ "count": str(line.count),
220
+ "weight": f"{line.weight:g}" if line.weight_set else "",
221
+ "tension": f"{line.max_tension:g}" if line.tension_set else "",
222
+ }
223
+ for line in lines
224
+ ]
225
+
226
+
227
+ # --- groups: lanes of a tray, subducts of a conduit -------------------------------------------
228
+
229
+ MAX_GROUPS = 12
230
+
231
+
232
+ @dataclass(frozen=True, slots=True)
233
+ class Group:
234
+ """Cables belonging to one lane or subduct. ``header`` holds the colon-separated parts of
235
+ the group's path segment (``subduct:solid:1.1:1.3`` gives ("solid", "1.1", "1.3")), or is
236
+ None for the cables listed before the first header."""
237
+
238
+ header: tuple[str, ...] | None
239
+ lines: list[CableLine]
240
+
241
+
242
+ def parse_groups(spec: str, keyword: str) -> list[Group]:
243
+ """Split a path spec at ``keyword:...`` segments. The first group (before any header) is
244
+ always returned, empty or not; groups may be empty."""
245
+ chunks: list[tuple[tuple[str, ...] | None, list[str]]] = [(None, [])]
246
+ for segment in (s.strip() for s in spec.strip().strip("/").split("/")):
247
+ if not segment:
248
+ continue
249
+ if segment.lower().startswith(f"{keyword}:"):
250
+ chunks.append((tuple(part.strip() for part in segment.split(":")[1:]), []))
251
+ else:
252
+ chunks[-1][1].append(segment)
253
+ if len(chunks) - 1 > MAX_GROUPS:
254
+ raise FillError(f"Use at most {MAX_GROUPS} {keyword}s.")
255
+ return [
256
+ Group(header, parse_cables("/".join(segments)) if segments else [])
257
+ for header, segments in chunks
258
+ ]
259
+
260
+
261
+ def merge_lines(groups: Sequence[Sequence[CableLine]]) -> tuple[list[CableLine], list[list[int]]]:
262
+ """Combine the cable lines of several groups into one list (for colours and the legend).
263
+
264
+ Lines of the same cable type are merged and their counts added. Returns the merged lines
265
+ and, for each group, the merged index of each of its lines.
266
+ """
267
+ merged: list[CableLine] = []
268
+ positions: dict[str, int] = {}
269
+ maps: list[list[int]] = []
270
+ for lines in groups:
271
+ mapping = []
272
+ for line in lines:
273
+ if line.key in positions:
274
+ i = positions[line.key]
275
+ merged[i] = replace(merged[i], count=merged[i].count + line.count)
276
+ else:
277
+ i = positions[line.key] = len(merged)
278
+ merged.append(line)
279
+ mapping.append(i)
280
+ maps.append(mapping)
281
+ return merged, maps
282
+
283
+
284
+ def _columns() -> dict[str, list[str]]:
285
+ return {"cable": [], "od": [], "count": [], "weight": [], "tension": []}
286
+
287
+
288
+ def groups_from_query(query_string: str, header_keys: Sequence[str]) -> list[dict]:
289
+ """Read a submitted form in document order into groups of cable rows.
290
+
291
+ A form lists, for each group, its header fields (``header_keys``; the first starts a new
292
+ group) followed by its cable rows (``cable``, ``od``, ``count``). Cables before the first
293
+ header belong to the implicit first group, whose ``header`` is None.
294
+ """
295
+ columns: list[dict[str, list[str]]] = [_columns()]
296
+ groups: list[dict] = [{"header": None}]
297
+ for key, value in parse_qsl(query_string, keep_blank_values=True):
298
+ if key == header_keys[0]:
299
+ groups.append({"header": {key: value}})
300
+ columns.append(_columns())
301
+ elif key in header_keys:
302
+ if groups[-1]["header"] is not None:
303
+ groups[-1]["header"][key] = value
304
+ elif key in columns[-1]:
305
+ columns[-1][key].append(value)
306
+ for group, cols in zip(groups, columns, strict=True):
307
+ n = len(cols["cable"])
308
+ weights = cols["weight"] + [""] * (n - len(cols["weight"])) # optional columns
309
+ tensions = cols["tension"] + [""] * (n - len(cols["tension"]))
310
+ group["rows"] = [
311
+ {"cable": cable, "od": od, "count": count, "weight": weight, "tension": tension}
312
+ for cable, od, count, weight, tension in zip(
313
+ cols["cable"], cols["od"], cols["count"], weights, tensions, strict=False
314
+ )
315
+ ]
316
+ if len(groups) - 1 > MAX_GROUPS:
317
+ raise FillError(f"Use at most {MAX_GROUPS} {header_keys[0].split('_')[0]}s.")
318
+ return groups
319
+
320
+
321
+ def groups_spec(groups: Sequence[dict], header_segment: Callable[[dict], str]) -> str:
322
+ """Turn submitted groups into a path spec (see ``parse_groups``)."""
323
+ parts = []
324
+ for group in groups:
325
+ if group["header"] is not None:
326
+ parts.append(header_segment(group["header"]))
327
+ cables = build_spec(group["rows"])
328
+ if cables:
329
+ parts.append(cables)
330
+ return "/".join(parts)
331
+
332
+
333
+ def lines_spec(lines: Sequence[CableLine]) -> str:
334
+ return "/".join(line.spec for line in lines)
335
+
336
+
337
+ @dataclass(frozen=True)
338
+ class Compartment:
339
+ """One separately checked space: a tray lane or a subduct."""
340
+
341
+ label: str
342
+ detail: str
343
+ lines: list[CableLine]
344
+ container_area: float # sq in
345
+ limit_pct: float
346
+ target_pct: float | None = None
347
+ kind: str = "" # "lane", "solid" or "mesh"
348
+ inner: float = 0.0 # lane width, or subduct inside diameter (in)
349
+ outer: float = 0.0 # subduct outside diameter (in)
350
+
351
+ @property
352
+ def total_count(self) -> int:
353
+ return sum(line.count for line in self.lines)
354
+
355
+ @property
356
+ def cable_area(self) -> float:
357
+ return sum(line.area_total for line in self.lines)
358
+
359
+ @property
360
+ def fill_pct(self) -> float:
361
+ return self.cable_area / self.container_area * 100
362
+
363
+ @property
364
+ def bar_pct(self) -> float:
365
+ return min(self.fill_pct, 100.0)
366
+
367
+ @property
368
+ def passes(self) -> bool:
369
+ return self.fill_pct <= self.limit_pct + 1e-7
370
+
371
+ @property
372
+ def within_target(self) -> bool | None:
373
+ return None if self.target_pct is None else self.fill_pct <= self.target_pct + 1e-7
374
+
375
+ @property
376
+ def max_area(self) -> float:
377
+ return self.container_area * self.limit_pct / 100
378
+
379
+ @property
380
+ def remaining_area(self) -> float:
381
+ return self.max_area - self.cable_area
382
+
383
+ @property
384
+ def contents(self) -> str:
385
+ if not self.lines:
386
+ return "empty"
387
+ return ", ".join(f"{line.label} × {line.count}" for line in self.lines)