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.
- ictdesigntools/__init__.py +16 -0
- ictdesigntools/cabling/__init__.py +1 -0
- ictdesigntools/cabling/cables.py +387 -0
- ictdesigntools/cabling/twistedpair.py +0 -0
- ictdesigntools/geometry/__init__.py +0 -0
- ictdesigntools/geometry/packing.py +187 -0
- ictdesigntools/locations/__init__.py +0 -0
- ictdesigntools/locations/sites.py +0 -0
- ictdesigntools/network/__init__.py +0 -0
- ictdesigntools/network/subnet.py +120 -0
- ictdesigntools/optical/__init__.py +7 -0
- ictdesigntools/optical/budget.py +487 -0
- ictdesigntools/optical/fiber.py +167 -0
- ictdesigntools/pathways/__init__.py +0 -0
- ictdesigntools/pathways/conduit.py +444 -0
- ictdesigntools/pathways/ductbank.py +679 -0
- ictdesigntools/pathways/microtrench.py +547 -0
- ictdesigntools/pathways/pull.py +282 -0
- ictdesigntools/pathways/tray.py +441 -0
- ictdesigntools/projects/__init__.py +0 -0
- ictdesigntools/projects/management.py +6 -0
- ictdesigntools/py.typed +0 -0
- ictdesigntools-0.0.1.dist-info/METADATA +75 -0
- ictdesigntools-0.0.1.dist-info/RECORD +26 -0
- ictdesigntools-0.0.1.dist-info/WHEEL +4 -0
- ictdesigntools-0.0.1.dist-info/licenses/LICENSE +21 -0
|
@@ -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 @@
|
|
|
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)
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
"""Gravity-style circle packing for cable cross-section diagrams.
|
|
2
|
+
|
|
3
|
+
Cables are dropped one at a time (largest first) to the lowest free spot, touching the
|
|
4
|
+
container wall or other cables, so the picture looks like cables resting in a run.
|
|
5
|
+
Containers decide what "inside" means: a round conduit bore or an open-top tray.
|
|
6
|
+
|
|
7
|
+
Coordinates are in inches with y pointing down, matching SVG.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import heapq
|
|
11
|
+
import math
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from functools import lru_cache
|
|
14
|
+
from typing import Protocol
|
|
15
|
+
|
|
16
|
+
EPS = 1e-7
|
|
17
|
+
|
|
18
|
+
Placed = tuple[float, float, float, int] # x, y, radius, line index
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Container(Protocol):
|
|
22
|
+
def seed(self, r: float) -> tuple[float, float] | None: ...
|
|
23
|
+
def anchors(self, r: float) -> list[tuple[float, float]]: ...
|
|
24
|
+
def wall_candidates(self, x: float, y: float, rj: float, r: float): ...
|
|
25
|
+
def contains(self, x: float, y: float, r: float) -> bool: ...
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def intersections(x0, y0, r0, x1, y1, r1):
|
|
29
|
+
"""Intersection points of two circles (0, 1 or 2 points)."""
|
|
30
|
+
dx, dy = x1 - x0, y1 - y0
|
|
31
|
+
d = math.hypot(dx, dy)
|
|
32
|
+
if d < 1e-12 or d > r0 + r1 + EPS or d < abs(r0 - r1) - EPS:
|
|
33
|
+
return []
|
|
34
|
+
a = (r0 * r0 - r1 * r1 + d * d) / (2 * d)
|
|
35
|
+
h = math.sqrt(max(r0 * r0 - a * a, 0.0))
|
|
36
|
+
xm, ym = x0 + a * dx / d, y0 + a * dy / d
|
|
37
|
+
return [(xm + h * dy / d, ym - h * dx / d), (xm - h * dy / d, ym + h * dx / d)]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True, slots=True)
|
|
41
|
+
class CircleContainer:
|
|
42
|
+
"""A round bore centred on the origin."""
|
|
43
|
+
|
|
44
|
+
radius: float
|
|
45
|
+
|
|
46
|
+
def seed(self, r):
|
|
47
|
+
return (0.0, self.radius - r) if r <= self.radius + EPS else None
|
|
48
|
+
|
|
49
|
+
def anchors(self, r):
|
|
50
|
+
return []
|
|
51
|
+
|
|
52
|
+
def wall_candidates(self, x, y, rj, r):
|
|
53
|
+
return intersections(0.0, 0.0, self.radius - r, x, y, rj + r)
|
|
54
|
+
|
|
55
|
+
def contains(self, x, y, r):
|
|
56
|
+
return x * x + y * y <= (self.radius - r + EPS) ** 2
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass(frozen=True, slots=True)
|
|
60
|
+
class RectContainer:
|
|
61
|
+
"""An open-top box: floor at ``bottom``, side walls at +-half_width, usable from ``top``."""
|
|
62
|
+
|
|
63
|
+
half_width: float
|
|
64
|
+
top: float
|
|
65
|
+
bottom: float
|
|
66
|
+
|
|
67
|
+
def seed(self, r):
|
|
68
|
+
fits = 2 * r <= 2 * self.half_width + EPS and 2 * r <= self.bottom - self.top + EPS
|
|
69
|
+
return (0.0, self.bottom - r) if fits else None
|
|
70
|
+
|
|
71
|
+
def anchors(self, r):
|
|
72
|
+
if self.seed(r) is None:
|
|
73
|
+
return []
|
|
74
|
+
y = self.bottom - r
|
|
75
|
+
return [(-self.half_width + r, y), (self.half_width - r, y)] # floor corners
|
|
76
|
+
|
|
77
|
+
def wall_candidates(self, x, y, rj, r):
|
|
78
|
+
reach = rj + r
|
|
79
|
+
points = []
|
|
80
|
+
floor = self.bottom - r
|
|
81
|
+
if abs(floor - y) <= reach:
|
|
82
|
+
dx = math.sqrt(reach * reach - (floor - y) ** 2)
|
|
83
|
+
points += [(x - dx, floor), (x + dx, floor)]
|
|
84
|
+
for wall in (-self.half_width + r, self.half_width - r):
|
|
85
|
+
if abs(wall - x) <= reach:
|
|
86
|
+
dy = math.sqrt(reach * reach - (wall - x) ** 2)
|
|
87
|
+
points += [(wall, y - dy), (wall, y + dy)]
|
|
88
|
+
return points
|
|
89
|
+
|
|
90
|
+
def contains(self, x, y, r):
|
|
91
|
+
return (
|
|
92
|
+
abs(x) <= self.half_width - r + EPS and self.top + r - EPS <= y <= self.bottom - r + EPS
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class _Grid:
|
|
97
|
+
"""Uniform grid over placed circles, for neighbour lookups in roughly constant time."""
|
|
98
|
+
|
|
99
|
+
def __init__(self, cell: float):
|
|
100
|
+
self.cell = cell
|
|
101
|
+
self.cells: dict[tuple[int, int], list[Placed]] = {}
|
|
102
|
+
|
|
103
|
+
def add(self, item: Placed):
|
|
104
|
+
self.cells.setdefault(self._key(item[0], item[1]), []).append(item)
|
|
105
|
+
|
|
106
|
+
def _key(self, x: float, y: float) -> tuple[int, int]:
|
|
107
|
+
return math.floor(x / self.cell), math.floor(y / self.cell)
|
|
108
|
+
|
|
109
|
+
def near(self, x: float, y: float, cells: int = 1):
|
|
110
|
+
kx, ky = self._key(x, y)
|
|
111
|
+
for i in range(kx - cells, kx + cells + 1):
|
|
112
|
+
for j in range(ky - cells, ky + cells + 1):
|
|
113
|
+
yield from self.cells.get((i, j), ())
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _sort_key(point: tuple[float, float]):
|
|
117
|
+
return (-round(point[1], 9), abs(point[0]))
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _candidates_for(container: Container, grid: _Grid, item: Placed, r: float):
|
|
121
|
+
"""Spots of radius r touching ``item`` and the wall or another nearby circle."""
|
|
122
|
+
xj, yj, rj, _ = item
|
|
123
|
+
points = list(container.wall_candidates(xj, yj, rj, r))
|
|
124
|
+
for xk, yk, rk, _ in grid.near(xj, yj, cells=2):
|
|
125
|
+
if (xk, yk) != (xj, yj) and math.hypot(xj - xk, yj - yk) <= rj + rk + 2 * r:
|
|
126
|
+
points += intersections(xj, yj, rj + r, xk, yk, rk + r)
|
|
127
|
+
return points
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _free(container: Container, grid: _Grid, x: float, y: float, r: float) -> bool:
|
|
131
|
+
return container.contains(x, y, r) and all(
|
|
132
|
+
math.hypot(x - xj, y - yj) >= rj + r - EPS for xj, yj, rj, _ in grid.near(x, y)
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _pack(container: Container, radii: tuple[tuple[float, int], ...]):
|
|
137
|
+
"""Drop circles (largest first) to the lowest free spot.
|
|
138
|
+
|
|
139
|
+
Candidate spots are kept in a heap per radius. A spot that is blocked stays blocked
|
|
140
|
+
(circles are only ever added), so it is discarded for good; placing a circle adds only
|
|
141
|
+
the spots that touch it. That keeps large loads fast.
|
|
142
|
+
"""
|
|
143
|
+
items = sorted(radii, key=lambda item: -item[0])
|
|
144
|
+
placed: list[Placed] = []
|
|
145
|
+
unplaced = 0
|
|
146
|
+
if not items:
|
|
147
|
+
return (), 0
|
|
148
|
+
grid = _Grid(2 * items[0][0] + EPS)
|
|
149
|
+
heap: list = []
|
|
150
|
+
heap_radius = None
|
|
151
|
+
|
|
152
|
+
for r, index in items:
|
|
153
|
+
if not placed:
|
|
154
|
+
spot = container.seed(r)
|
|
155
|
+
if spot is None or not container.contains(*spot, r):
|
|
156
|
+
unplaced += 1
|
|
157
|
+
continue
|
|
158
|
+
else:
|
|
159
|
+
if r != heap_radius: # new size: rebuild its candidate spots from what is placed
|
|
160
|
+
heap_radius = r
|
|
161
|
+
points = list(container.anchors(r))
|
|
162
|
+
for item in placed:
|
|
163
|
+
points += _candidates_for(container, grid, item, r)
|
|
164
|
+
heap = [(_sort_key(pt), pt) for pt in points]
|
|
165
|
+
heapq.heapify(heap)
|
|
166
|
+
spot = None
|
|
167
|
+
while heap:
|
|
168
|
+
_, (x, y) = heapq.heappop(heap)
|
|
169
|
+
if _free(container, grid, x, y, r):
|
|
170
|
+
spot = (x, y)
|
|
171
|
+
break
|
|
172
|
+
if spot is None:
|
|
173
|
+
unplaced += 1
|
|
174
|
+
continue
|
|
175
|
+
item = (spot[0], spot[1], r, index)
|
|
176
|
+
grid.add(item)
|
|
177
|
+
placed.append(item)
|
|
178
|
+
if heap_radius == r:
|
|
179
|
+
for pt in _candidates_for(container, grid, item, r):
|
|
180
|
+
heapq.heappush(heap, (_sort_key(pt), pt))
|
|
181
|
+
return tuple(placed), unplaced
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
@lru_cache(maxsize=256)
|
|
185
|
+
def pack(container: CircleContainer | RectContainer, radii: tuple[tuple[float, int], ...]):
|
|
186
|
+
"""Pack (radius, line_index) items, largest first. Returns (placed, unplaced_count)."""
|
|
187
|
+
return _pack(container, radii)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|