Repository navigation
Expand file tree
/
Copy pathanalysis.py
More file actions
742 lines (654 loc) · 38.6 KB
/
Copy pathanalysis.py
File metadata and controls
742 lines (654 loc) · 38.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
"""Cross-project connector and cable mapping backend."""
from __future__ import annotations
import csv
import fnmatch
import math
import re
from html import escape
from dataclasses import dataclass, asdict, field
from pathlib import Path
@dataclass(frozen=True)
class PinRecord:
project: str
connector: str
pin: str
net: str
function: str = ""
voltage: str = ""
connector_part: str = ""
contact_part: str = ""
endpoint_type: str = "board"
load_a: float = 0.0
@dataclass
class HarnessLink:
source: PinRecord
destination: PinRecord
wire_id: str
gauge_awg: str = "24"
pair: str = ""
shield: str = ""
status: str = "linked"
bundle: str = ""
splice: str = ""
color: str = ""
length_m: float = 1.0
notes: str = ""
@dataclass(frozen=True)
class ConnectorRule:
source_project: str
source_connector: str
destination_project: str
destination_connector: str
pin_offset: int = 0
explicit_pin_map: tuple[tuple[str, str], ...] = ()
rule_name: str = "Pin correspondence"
@dataclass(frozen=True)
class PinMapRow:
"""One reviewed wire definition from the tabular harness editor."""
source_project: str
source_connector: str
source_pin: str
destination_project: str
destination_connector: str
destination_pin: str
wire_id: str = ""
gauge_awg: str = "24"
color: str = ""
bundle: str = ""
splice: str = ""
length_m: float = 1.0
shield: str = ""
notes: str = "Manual pin map"
@dataclass(frozen=True)
class VirtualLoad:
project: str
reference: str
pin: str
net: str
function: str = "External load"
voltage: str = ""
current_a: float = 0.0
connector_part: str = ""
@dataclass
class HarnessBundle:
name: str
wire_ids: list[str] = field(default_factory=list)
gauge_awg: str = "24"
shield: str = ""
sleeve: str = ""
length_m: float = 1.0
service_loop_percent: float = 10.0
@dataclass
class HarnessSplice:
splice_id: str
wire_ids: list[str] = field(default_factory=list)
splice_type: str = "Crimp splice"
location: str = ""
part_number: str = ""
@dataclass(frozen=True)
class BoardSignalPath:
"""Audited path from an internal IC/peripheral pin to a board connector."""
project: str
endpoint_reference: str
endpoint_value: str
endpoint_pin: str
endpoint_function: str
endpoint_net: str
connector: str
connector_pin: str
connector_net: str
net_sequence: str = ""
inline_components: str = ""
pin_transitions: str = ""
active_devices: str = ""
condition_notes: str = ""
status: str = "Resolved"
confidence: str = "High"
ordered_path: str = ""
sheet: str = ""
@dataclass(frozen=True)
class SystemSignalPath:
"""End-to-end logical route across board copper and a physical harness."""
path_id: str
source_project: str
source_reference: str
source_value: str
source_pin: str
source_function: str
source_net: str
source_connector: str
source_connector_pin: str
wire_id: str
bundle: str
destination_connector: str
destination_connector_pin: str
destination_project: str
destination_reference: str
destination_value: str
destination_pin: str
destination_function: str
destination_net: str
inline_components: str
board_net_sequence: str
ordered_path: str
protocol: str
status: str
confidence: str
notes: str = ""
def load_pin_csv(path: str | Path, project: str = "") -> list[PinRecord]:
source = Path(path)
with source.open(newline="", encoding="utf-8-sig") as handle:
rows = list(csv.DictReader(handle))
records = []
for row in rows:
folded = {str(key).strip().casefold(): str(value or "").strip() for key, value in row.items()}
records.append(PinRecord(
project or folded.get("project", source.stem),
folded.get("connector", folded.get("reference", folded.get("ref", ""))),
folded.get("pin", folded.get("pad", "")),
folded.get("net", folded.get("net name", "")),
folded.get("function", folded.get("signal", "")),
folded.get("voltage", ""),
folded.get("connector part", folded.get("connector_part", folded.get("connector pn", ""))),
folded.get("contact part", folded.get("contact_part", folded.get("terminal part", ""))),
folded.get("endpoint type", "board"),
_safe_float(folded.get("load a", folded.get("current a", "0"))),
))
return [record for record in records if record.connector and record.pin]
def _safe_float(value: str | None) -> float:
try:
return float(value or 0)
except (TypeError, ValueError):
return 0.0
def load_pin_documents(paths: list[str | Path], maximum_projects: int = 50) -> list[PinRecord]:
"""Load many board exports with deterministic de-duplication and a project cap."""
records: dict[tuple[str, str, str, str], PinRecord] = {}
for raw_path in paths:
path = Path(raw_path)
if path.suffix.lower() != ".csv":
continue
for record in load_pin_csv(path):
records[(record.project, record.connector, record.pin, record.net)] = record
projects = {record.project for record in records.values()}
if len(projects) > maximum_projects:
raise ValueError(f"Imported {len(projects)} projects; the configured limit is {maximum_projects}.")
return sorted(records.values(), key=lambda item: (item.project.casefold(), item.connector.casefold(), _pin_key(item.pin), item.net.casefold()))
def load_signal_path_csv(path: str | Path, project: str = "") -> list[BoardSignalPath]:
"""Load Pin Extractor controller-map CSV without discarding audit fields."""
source = Path(path)
with source.open(newline="", encoding="utf-8-sig") as handle:
rows = list(csv.DictReader(handle))
result = []
for number, raw in enumerate(rows, 2):
folded = {str(key).strip().casefold().replace("_", " "): str(value or "").strip()
for key, value in raw.items()}
endpoint_reference = folded.get("source reference", folded.get("endpoint reference", ""))
endpoint_pin = folded.get("source pin", folded.get("endpoint pin", ""))
connector = folded.get("connector reference", folded.get("connector", ""))
connector_pin = folded.get("connector pin", "")
if not all((endpoint_reference, endpoint_pin, connector, connector_pin)):
raise ValueError(
f"Signal path row {number} needs Source Reference/Pin and Connector Reference/Pin columns."
)
result.append(BoardSignalPath(
project or folded.get("project", source.stem), endpoint_reference,
folded.get("source value", folded.get("endpoint value", "")), endpoint_pin,
folded.get("source pin function", folded.get("endpoint function", "")),
folded.get("source net", ""), connector, connector_pin,
folded.get("connector net", ""), folded.get("net sequence", ""),
folded.get("inline components", ""), folded.get("pin transitions", ""),
folded.get("active devices", ""), folded.get("condition notes", ""),
folded.get("status", "Resolved"), folded.get("confidence", "High"),
folded.get("ordered path", ""), folded.get("sheet", ""),
))
return result
def load_signal_path_documents(paths: list[str | Path], maximum_projects: int = 50) -> list[BoardSignalPath]:
records = {}
for raw_path in paths:
for item in load_signal_path_csv(raw_path):
key = (item.project, item.endpoint_reference, item.endpoint_pin, item.connector, item.connector_pin,
item.ordered_path)
records[key] = item
projects = {item.project for item in records.values()}
if len(projects) > maximum_projects:
raise ValueError(f"Imported {len(projects)} signal-path projects; the configured limit is {maximum_projects}.")
return sorted(records.values(), key=lambda item: (
item.project.casefold(), _pin_key(item.endpoint_reference), _pin_key(item.endpoint_pin),
_pin_key(item.connector), _pin_key(item.connector_pin), item.ordered_path.casefold()))
def _matches_patterns(value: str, patterns: str) -> bool:
choices = [item.strip() for item in str(patterns or "*").split(",") if item.strip()]
return any(fnmatch.fnmatchcase(value.casefold(), item.casefold()) for item in choices or ["*"])
def _reverse_ordered_path(path: BoardSignalPath) -> str:
text = path.ordered_path.strip()
if text:
return " -> ".join(reversed([item.strip() for item in text.split(" -> ")]))
return " -> ".join(filter(None, (
f"{path.connector}.{path.connector_pin}", f"[{path.connector_net}]",
f"{path.endpoint_reference}.{path.endpoint_pin}",
)))
def _protocol_name(*values: str) -> str:
text = " ".join(values).upper()
patterns = (
("UART", ("UART", "USART")), ("I2C", ("I2C", "SCL", "SDA")),
("SPI", ("SPI", "MOSI", "MISO", "SCLK", "CS_")),
("CAN", ("CANH", "CANL", "CAN_")), ("USB", ("USB",)),
("Ethernet", ("ETH", "MDI", "RGMII", "RMII")),
("RS-485", ("RS485", "RS-485")), ("JTAG/SWD", ("JTAG", "SWD", "SWCLK", "SWDIO")),
)
return next((name for name, tokens in patterns if any(token in text for token in tokens)), "General signal")
def build_system_signal_paths(links: list[HarnessLink], board_paths: list[BoardSignalPath],
source_patterns: str = "U*", destination_patterns: str = "U*",
include_partial: bool = True) -> list[SystemSignalPath]:
"""Join audited internal-to-connector paths across reviewed harness wires."""
index: dict[tuple[str, str, str], list[BoardSignalPath]] = {}
for path in board_paths:
index.setdefault((path.project.casefold(), path.connector.casefold(), path.connector_pin.casefold()), []).append(path)
results = []
for link in links:
source_candidates = index.get((link.source.project.casefold(), link.source.connector.casefold(),
link.source.pin.casefold()), [])
destination_candidates = index.get((link.destination.project.casefold(), link.destination.connector.casefold(),
link.destination.pin.casefold()), [])
sources = [item for item in source_candidates
if _matches_patterns(item.endpoint_reference, source_patterns)]
destinations = [item for item in destination_candidates
if _matches_patterns(item.endpoint_reference, destination_patterns)]
if not sources and include_partial and not source_candidates:
sources = [BoardSignalPath(link.source.project, "", "", "", "", link.source.net,
link.source.connector, link.source.pin, link.source.net,
status="Unresolved", confidence="Low")]
if not destinations and include_partial and not destination_candidates:
destinations = [BoardSignalPath(link.destination.project, "", "", "", "", link.destination.net,
link.destination.connector, link.destination.pin, link.destination.net,
status="Unresolved", confidence="Low")]
for source in sources:
for destination in destinations:
path_id = f"P{len(results)+1:05d}"
harness_step = (f"{link.source.project}:{link.source.connector}.{link.source.pin}"
f" --{link.wire_id}/{link.bundle or 'Unbundled'}--> "
f"{link.destination.project}:{link.destination.connector}.{link.destination.pin}")
source_ordered = source.ordered_path or " -> ".join(filter(None, (
f"{source.endpoint_reference}.{source.endpoint_pin}" if source.endpoint_reference else "",
f"[{source.endpoint_net}]" if source.endpoint_net else "",
f"{source.connector}.{source.connector_pin}",
)))
ordered = " -> ".join(filter(None, (source_ordered, harness_step, _reverse_ordered_path(destination))))
statuses = {source.status.casefold(), destination.status.casefold(), link.status.casefold()}
if "unmatched" in statuses or "unresolved" in statuses:
status, confidence = "Incomplete", "Low"
elif "ambiguous" in statuses:
status, confidence = "Ambiguous", "Low"
elif "conditional" in statuses:
status, confidence = "Conditional", "Conditional"
else:
status = "Resolved"; confidence = "High" if source.confidence == destination.confidence == "High" else "Review"
inline = "; ".join(filter(None, (
f"{source.project}: {source.inline_components}" if source.inline_components else "",
f"{destination.project}: {destination.inline_components}" if destination.inline_components else "",
)))
net_sequence = " | harness | ".join(filter(None, (source.net_sequence or source.endpoint_net,
destination.net_sequence or destination.endpoint_net)))
notes = "; ".join(dict.fromkeys(filter(None, (
source.condition_notes, destination.condition_notes, link.notes,
"Destination board path shown connector-to-endpoint (reverse of extracted route).",
))))
results.append(SystemSignalPath(
path_id, source.project, source.endpoint_reference, source.endpoint_value,
source.endpoint_pin, source.endpoint_function, source.endpoint_net,
link.source.connector, link.source.pin, link.wire_id, link.bundle or "Unbundled",
link.destination.connector, link.destination.pin, destination.project,
destination.endpoint_reference, destination.endpoint_value, destination.endpoint_pin,
destination.endpoint_function, destination.endpoint_net, inline, net_sequence, ordered,
_protocol_name(source.endpoint_function, source.endpoint_net, destination.endpoint_function,
destination.endpoint_net), status, confidence, notes,
))
return sorted(results, key=lambda item: (
item.bundle.casefold(), item.source_project.casefold(), _pin_key(item.source_reference),
_pin_key(item.source_pin), item.destination_project.casefold(), _pin_key(item.destination_reference),
_pin_key(item.destination_pin)))
def system_signal_rows(paths: list[SystemSignalPath]) -> list[dict[str, str]]:
return [{
"Path": item.path_id,
"Source IC / Peripheral": f"{item.source_project}:{item.source_reference}.{item.source_pin}",
"Source Function": item.source_function,
"Source Net": item.source_net,
"Source Connector": f"{item.source_connector}.{item.source_connector_pin}",
"Wire": item.wire_id,
"Bundle": item.bundle,
"Destination Connector": f"{item.destination_connector}.{item.destination_connector_pin}",
"Destination IC / Peripheral": f"{item.destination_project}:{item.destination_reference}.{item.destination_pin}",
"Destination Function": item.destination_function,
"Destination Net": item.destination_net,
"Protocol": item.protocol,
"Inline Components": item.inline_components,
"Status": item.status,
"Confidence": item.confidence,
"Ordered Path": item.ordered_path,
} for item in paths]
def discover_pin_documents(directory: str | Path, recursive: bool = True) -> list[Path]:
root = Path(directory)
if not root.is_dir():
raise ValueError(f"Not a directory: {root}")
return sorted(root.rglob("*.csv") if recursive else root.glob("*.csv"))
def virtual_load_records(loads: list[VirtualLoad]) -> list[PinRecord]:
return [PinRecord(load.project, load.reference, load.pin, load.net, load.function,
load.voltage, load.connector_part, "", "virtual-load", load.current_a)
for load in loads]
def connector_correspondence(records: list[PinRecord], rules: list[ConnectorRule]) -> list[HarnessLink]:
"""Link connectors in O(records + rules*pins), defaulting to pin N -> pin N."""
index: dict[tuple[str, str], dict[str, PinRecord]] = {}
for record in records:
index.setdefault((record.project.casefold(), record.connector.casefold()), {})[record.pin.casefold()] = record
links: list[HarnessLink] = []
for rule in rules:
source_pins = index.get((rule.source_project.casefold(), rule.source_connector.casefold()), {})
destination_pins = index.get((rule.destination_project.casefold(), rule.destination_connector.casefold()), {})
explicit = {source.casefold(): destination.casefold() for source, destination in rule.explicit_pin_map}
for source_pin, source in sorted(source_pins.items(), key=lambda item: _pin_key(item[0])):
destination_pin = explicit.get(source_pin)
if destination_pin is None:
try: destination_pin = str(int(source.pin) + rule.pin_offset).casefold()
except ValueError: destination_pin = source_pin
destination = destination_pins.get(destination_pin)
status = "linked" if destination else "unmatched"
if destination is None:
destination = PinRecord(rule.destination_project, rule.destination_connector, destination_pin, "")
links.append(HarnessLink(source, destination, f"W{len(links)+1:05d}", status=status,
notes=rule.rule_name))
return links
def links_from_pin_map(records: list[PinRecord], rows: list[PinMapRow]) -> list[HarnessLink]:
"""Resolve exact, user-reviewed endpoint rows without assuming pin correspondence."""
index = {
(record.project.casefold(), record.connector.casefold(), record.pin.casefold()): record
for record in records
}
links = []
for number, row in enumerate(rows, 1):
source_key = (row.source_project.casefold(), row.source_connector.casefold(), row.source_pin.casefold())
destination_key = (
row.destination_project.casefold(), row.destination_connector.casefold(), row.destination_pin.casefold()
)
source = index.get(source_key) or PinRecord(
row.source_project, row.source_connector, row.source_pin, "", endpoint_type="unresolved"
)
destination = index.get(destination_key) or PinRecord(
row.destination_project, row.destination_connector, row.destination_pin, "", endpoint_type="unresolved"
)
missing = []
if source_key not in index:
missing.append("source")
if destination_key not in index:
missing.append("destination")
links.append(HarnessLink(
source=source,
destination=destination,
wire_id=row.wire_id or f"W{number:05d}",
gauge_awg=row.gauge_awg or "24",
shield=row.shield,
status="linked" if not missing else "unmatched",
bundle=row.bundle,
splice=row.splice,
color=row.color,
length_m=max(0.0, row.length_m),
notes=row.notes if not missing else f"{row.notes}; unresolved {' and '.join(missing)} endpoint",
))
return links
def load_pin_map_csv(path: str | Path) -> list[PinMapRow]:
"""Load an editable pin-map CSV using stable, case-insensitive column names."""
with Path(path).open(newline="", encoding="utf-8-sig") as handle:
source_rows = list(csv.DictReader(handle))
result = []
for number, source_row in enumerate(source_rows, 2):
row = {str(key).strip().casefold().replace(" ", "_"): str(value or "").strip()
for key, value in source_row.items()}
required = ("source_project", "source_connector", "source_pin",
"destination_project", "destination_connector", "destination_pin")
missing = [name for name in required if not row.get(name)]
if missing:
raise ValueError(f"Pin map row {number} is missing: {', '.join(missing)}")
result.append(PinMapRow(
row["source_project"], row["source_connector"], row["source_pin"],
row["destination_project"], row["destination_connector"], row["destination_pin"],
row.get("wire_id", ""), row.get("gauge_awg", row.get("awg", "24")), row.get("color", ""),
row.get("bundle", ""), row.get("splice", ""), _safe_float(row.get("length_m", "1")),
row.get("shield", ""), row.get("notes", "Manual pin map"),
))
return result
def pin_map_editor_rows(rows: list[PinMapRow]) -> list[dict[str, str]]:
return [{
"source_project": row.source_project,
"source_connector": row.source_connector,
"source_pin": row.source_pin,
"destination_project": row.destination_project,
"destination_connector": row.destination_connector,
"destination_pin": row.destination_pin,
"wire_id": row.wire_id,
"gauge_awg": row.gauge_awg,
"color": row.color,
"bundle": row.bundle,
"splice": row.splice,
"length_m": f"{row.length_m:.3f}",
"shield": row.shield,
"notes": row.notes,
} for row in rows]
def validate_pin_map(records: list[PinRecord], rows: list[PinMapRow]) -> list[str]:
endpoint_keys = {(r.project.casefold(), r.connector.casefold(), r.pin.casefold()) for r in records}
issues = []
seen_sources: dict[tuple[str, str, str], int] = {}
for number, row in enumerate(rows, 1):
source = (row.source_project.casefold(), row.source_connector.casefold(), row.source_pin.casefold())
destination = (row.destination_project.casefold(), row.destination_connector.casefold(), row.destination_pin.casefold())
if source not in endpoint_keys:
issues.append(f"Row {number}: source endpoint does not exist: {row.source_project}:{row.source_connector}.{row.source_pin}")
if destination not in endpoint_keys:
issues.append(f"Row {number}: destination endpoint does not exist: {row.destination_project}:{row.destination_connector}.{row.destination_pin}")
seen_sources[source] = seen_sources.get(source, 0) + 1
issues.extend(
f"Source endpoint {project}:{connector}.{pin} is mapped to {count} destinations; verify a splice is intended."
for (project, connector, pin), count in seen_sources.items() if count > 1
)
return issues
def parse_connector_rules(text: str) -> list[ConnectorRule]:
"""Parse `BOARD:J1 -> BOARD:J2 [offset=N] [map=1:3,2:4]` rules."""
rules = []
expression = re.compile(r"^\s*([^:]+):([^\s]+)\s*->\s*([^:]+):([^\s]+)(.*)$")
for line_number, line in enumerate(text.splitlines(), 1):
if not line.strip() or line.lstrip().startswith("#"): continue
match = expression.match(line)
if not match: raise ValueError(f"Invalid connector rule on line {line_number}: {line}")
source_project, source_connector, destination_project, destination_connector, options = match.groups()
offset_match = re.search(r"offset\s*=\s*(-?\d+)", options, re.I)
map_match = re.search(r"map\s*=\s*([^;\]]+)", options, re.I)
pin_map = []
if map_match:
for pair in map_match.group(1).split(","):
if ":" not in pair: continue
source, destination = pair.split(":", 1); pin_map.append((source.strip(), destination.strip()))
rules.append(ConnectorRule(source_project.strip(), source_connector.strip(),
destination_project.strip(), destination_connector.strip(),
int(offset_match.group(1)) if offset_match else 0, tuple(pin_map),
f"Connector rule {line_number}"))
return rules
def _pin_key(value: str):
parts = re.split(r"(\d+)", str(value))
return tuple(int(part) if part.isdigit() else part.casefold() for part in parts)
def _capture(pattern: str, value: str, regex: bool) -> str | None:
if regex:
match = re.fullmatch(pattern, value, flags=re.IGNORECASE)
if not match: return None
return match.groupdict().get("link", match.group(1) if match.groups() else match.group(0)).casefold()
if not fnmatch.fnmatchcase(value.casefold(), pattern.casefold()): return None
escaped = re.escape(pattern).replace(r"\*", "(.*)").replace(r"\?", "(.)")
match = re.fullmatch(escaped, value, flags=re.IGNORECASE)
return "|".join(match.groups()).casefold() if match and match.groups() else value.casefold()
def auto_link(sources: list[PinRecord], destinations: list[PinRecord], source_pattern: str = "*",
destination_pattern: str = "*", regex: bool = False) -> list[HarnessLink]:
source_keys = [(record, _capture(source_pattern, record.net, regex)) for record in sources]
destination_keys = [(record, _capture(destination_pattern, record.net, regex)) for record in destinations]
links = []
for source, key in source_keys:
if key is None: continue
matches = [record for record, other_key in destination_keys if other_key == key]
status = "linked" if len(matches) == 1 else "ambiguous" if matches else "unmatched"
if not matches:
placeholder = PinRecord("", "", "", source.net)
links.append(HarnessLink(source, placeholder, f"W{len(links)+1:04d}", status=status))
else:
for destination in matches:
links.append(HarnessLink(source, destination, f"W{len(links)+1:04d}", status=status))
return links
def auto_link_multi(records: list[PinRecord], net_pattern: str = "*", regex: bool = False,
include_power: bool = False, max_links: int = 50000) -> list[HarnessLink]:
"""Index signals across many projects and link unique cross-connector peers."""
buckets: dict[str, list[PinRecord]] = {}
for record in records:
if not record.net or (not include_power and _looks_power(record.net)): continue
key = _capture(net_pattern, record.net, regex)
if key is not None: buckets.setdefault(key, []).append(record)
links=[]
for key, endpoints in sorted(buckets.items()):
unique=list({(e.project,e.connector,e.pin,e.net):e for e in endpoints}.values())
candidates=[]
for index,source in enumerate(unique):
for destination in unique[index+1:]:
if (source.project.casefold(),source.connector.casefold()) == (destination.project.casefold(),destination.connector.casefold()): continue
candidates.append((source,destination))
status="linked" if len(candidates)==1 else "ambiguous" if candidates else "unmatched"
for source,destination in candidates:
links.append(HarnessLink(source,destination,f"W{len(links)+1:05d}",status=status,notes=f"Indexed net match: {key}"))
if len(links)>=max_links: raise ValueError(f"Automatic linking exceeded {max_links} wires. Narrow the net pattern or use connector rules.")
return links
def _looks_power(net: str) -> bool:
value=re.sub(r"[^A-Z0-9]","",net.upper())
return bool(re.match(r"^(GND|AGND|DGND|PGND|VSS|VCC|VDD|VBAT|PWR|POWER|[0-9]+V[0-9]*)",value))
def validate_links(links: list[HarnessLink]) -> list[str]:
issues = []
destinations: dict[tuple[str, str, str], int] = {}
for link in links:
key = (link.destination.project, link.destination.connector, link.destination.pin)
if all(key): destinations[key] = destinations.get(key, 0) + 1
if link.source.voltage and link.destination.voltage and link.source.voltage != link.destination.voltage:
issues.append(f"Voltage mismatch {link.source.voltage} -> {link.destination.voltage} on {link.wire_id}")
if link.status != "linked": issues.append(f"{link.status.title()} mapping on {link.wire_id}: {link.source.net}")
issues.extend(f"Multiple wires terminate at {project}:{connector}.{pin}" for (project, connector, pin), count in destinations.items() if count > 1)
return issues
def export_csv(path: str | Path, links: list[HarnessLink]) -> None:
fields = ["wire_id", "source_project", "source_connector", "source_pin", "source_net",
"destination_project", "destination_connector", "destination_pin", "destination_net",
"gauge_awg", "pair", "bundle", "splice", "shield", "color", "length_m", "status", "notes"]
with Path(path).open("w", newline="", encoding="utf-8") as handle:
writer = csv.DictWriter(handle, fieldnames=fields); writer.writeheader()
for link in links:
writer.writerow({"wire_id": link.wire_id, "source_project": link.source.project,
"source_connector": link.source.connector, "source_pin": link.source.pin,
"source_net": link.source.net, "destination_project": link.destination.project,
"destination_connector": link.destination.connector, "destination_pin": link.destination.pin,
"destination_net": link.destination.net, "gauge_awg": link.gauge_awg,
"pair": link.pair, "bundle": link.bundle, "splice": link.splice,
"shield": link.shield, "color": link.color, "length_m": f"{link.length_m:.3f}",
"status": link.status, "notes": link.notes})
def pin_map_rows(links: list[HarnessLink]) -> list[dict[str, str]]:
return [{
"Wire": link.wire_id,
"Source": f"{link.source.project}:{link.source.connector}.{link.source.pin}",
"Source Net": link.source.net,
"Destination": f"{link.destination.project}:{link.destination.connector}.{link.destination.pin}",
"Destination Net": link.destination.net,
"Function": link.source.function or link.destination.function,
"Bundle": link.bundle,
"Splice": link.splice,
"Status": link.status,
} for link in links]
def net_map_rows(links: list[HarnessLink]) -> list[dict[str, str]]:
groups: dict[str, dict[str, object]] = {}
for link in links:
key = link.source.net or link.destination.net or link.wire_id
row = groups.setdefault(key, {"Net / Signal": key, "Endpoints": set(), "Wires": [], "Bundles": set(), "Loads (A)": 0.0})
row["Endpoints"].update((f"{link.source.project}:{link.source.connector}.{link.source.pin}",
f"{link.destination.project}:{link.destination.connector}.{link.destination.pin}"))
row["Wires"].append(link.wire_id)
if link.bundle: row["Bundles"].add(link.bundle)
row["Loads (A)"] += max(link.source.load_a, link.destination.load_a)
return [{"Net / Signal": str(row["Net / Signal"]), "Endpoints": "; ".join(sorted(row["Endpoints"])),
"Wires": ", ".join(row["Wires"]), "Bundles": ", ".join(sorted(row["Bundles"])),
"Loads (A)": f"{row['Loads (A)']:.3f}"} for row in groups.values()]
def apply_bundle(links: list[HarnessLink], bundle: HarnessBundle) -> None:
targets = set(bundle.wire_ids)
for link in links:
if link.wire_id in targets:
link.bundle = bundle.name; link.gauge_awg = bundle.gauge_awg
link.shield = bundle.shield; link.length_m = bundle.length_m
def apply_splice(links: list[HarnessLink], splice: HarnessSplice) -> None:
targets = set(splice.wire_ids)
for link in links:
if link.wire_id in targets: link.splice = splice.splice_id
def harness_bom(records: list[PinRecord], links: list[HarnessLink], bundles: list[HarnessBundle] = (),
splices: list[HarnessSplice] = ()) -> list[dict[str, str]]:
"""Create a procurement-oriented aggregate without inventing missing part numbers."""
rows: list[dict[str, str]] = []
connectors: dict[str, set[tuple[str, str]]] = {}
contacts: dict[str, int] = {}
for record in records:
connector_part = record.connector_part or "UNSPECIFIED CONNECTOR"
connectors.setdefault(connector_part, set()).add((record.project, record.connector))
contact_part = record.contact_part or f"UNSPECIFIED CONTACT AWG {next((l.gauge_awg for l in links if l.source == record or l.destination == record), 'TBD')}"
contacts[contact_part] = contacts.get(contact_part, 0) + 1
for part, instances in sorted(connectors.items()):
rows.append({"Category":"Connector","Part Number":part,"Description":"Connector housing","Quantity":str(len(instances)),"Unit":"ea","Notes":"; ".join(f"{p}:{c}" for p,c in sorted(instances))})
for part, count in sorted(contacts.items()):
rows.append({"Category":"Contact","Part Number":part,"Description":"Crimp/contact terminal","Quantity":str(count),"Unit":"ea","Notes":"Verify plating and mating family"})
wire_groups: dict[tuple[str, str], float] = {}
for link in links:
key=(link.gauge_awg or "TBD",link.color or "Unspecified")
wire_groups[key]=wire_groups.get(key,0.0)+max(0.0,link.length_m)
for (gauge,color),length in sorted(wire_groups.items()):
rows.append({"Category":"Wire","Part Number":"TBD","Description":f"AWG {gauge}, {color}","Quantity":f"{length*1.10:.2f}","Unit":"m","Notes":"Includes 10% general cut allowance"})
for bundle in bundles:
rows.append({"Category":"Bundle","Part Number":"TBD","Description":bundle.sleeve or bundle.shield or "Harness bundle protection","Quantity":f"{bundle.length_m*(1+bundle.service_loop_percent/100):.2f}","Unit":"m","Notes":bundle.name})
for splice in splices:
rows.append({"Category":"Splice","Part Number":splice.part_number or "TBD","Description":splice.splice_type,"Quantity":"1","Unit":"ea","Notes":f"{splice.splice_id} {splice.location}".strip()})
labels={link.bundle for link in links if link.bundle}
if labels: rows.append({"Category":"Identification","Part Number":"TBD","Description":"Harness/bundle labels","Quantity":str(len(labels)),"Unit":"ea","Notes":", ".join(sorted(labels))})
return rows
def export_rows(path: str | Path, rows: list[dict[str, str]]) -> None:
if not rows: return
with Path(path).open("w", newline="", encoding="utf-8") as handle:
writer=csv.DictWriter(handle,fieldnames=list(rows[0]));writer.writeheader();writer.writerows(rows)
def connector_graph(links: list[HarnessLink]) -> tuple[list[str], list[tuple[str, str, HarnessLink]]]:
nodes=set();edges=[]
for link in links:
source=f"{link.source.project}:{link.source.connector}";destination=f"{link.destination.project}:{link.destination.connector}"
nodes.update((source,destination));edges.append((source,destination,link))
return sorted(nodes),edges
def universal_harness_svg(links: list[HarnessLink], title: str = "Universal Harness Architecture") -> str:
nodes,edges=connector_graph(links);columns=max(2,math.ceil(math.sqrt(max(len(nodes),1))));rows=math.ceil(max(len(nodes),1)/columns);width=max(1200,columns*300);height=max(700,rows*190+100)
positions={node:(160+(index%columns)*300,100+(index//columns)*190) for index,node in enumerate(nodes)}
bundle_colors={name:color for name,color in zip(sorted({l.bundle or "Unbundled" for l in links}),("#237c73","#d15b45","#5577aa","#8d62a8","#d39b32","#3c8d56","#b84d72"))}
lines=[f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}">','<rect width="100%" height="100%" fill="#f6f8fa"/>',f'<text x="30" y="38" font-family="Segoe UI" font-size="24" font-weight="bold" fill="#263744">{escape(title)}</text>','<g fill="none" stroke-linecap="round">']
grouped:dict[tuple[str,str],list[HarnessLink]]={}
for source,destination,link in edges:grouped.setdefault((source,destination),[]).append(link)
for (source,destination),group in grouped.items():
x1,y1=positions[source];x2,y2=positions[destination]
for index,link in enumerate(group):
offset=(index-(len(group)-1)/2)*3;color=bundle_colors[link.bundle or "Unbundled"];lines.append(f'<path d="M{x1+105} {y1+offset} C {(x1+x2)/2} {y1+offset}, {(x1+x2)/2} {y2+offset}, {x2-105} {y2+offset}" stroke="{color}" stroke-width="2"><title>{escape(link.wire_id)} {escape(link.source.net)} {escape(link.gauge_awg)} AWG</title></path>')
lines.append('</g>')
for node,(x,y) in positions.items():
project,connector=node.split(":",1);pin_count=sum(1 for l in links if node in (f"{l.source.project}:{l.source.connector}",f"{l.destination.project}:{l.destination.connector}"));lines.extend([f'<g><rect x="{x-105}" y="{y-42}" width="210" height="84" rx="6" fill="#ffffff" stroke="#4c6475" stroke-width="2"/>',f'<text x="{x-92}" y="{y-12}" font-family="Segoe UI" font-size="15" font-weight="bold" fill="#263744">{escape(connector)}</text>',f'<text x="{x-92}" y="{y+10}" font-family="Segoe UI" font-size="12" fill="#52616b">{escape(project)}</text>',f'<text x="{x-92}" y="{y+29}" font-family="Segoe UI" font-size="11" fill="#52616b">{pin_count} mapped wire(s)</text></g>'])
lines.append('</svg>');return "\n".join(lines)
def harness_svg(links: list[HarnessLink]) -> str:
row_height = 34; height = max(180, 90 + row_height * len(links)); width = 1200
lines = [f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}">',
'<rect width="100%" height="100%" fill="#f7f9fb"/>',
'<style>text{font-family:Arial,sans-serif;fill:#17202a}.h{font-size:18px;font-weight:bold}.p{font-size:12px}.w{font-size:11px}</style>',
'<text class="h" x="35" y="35">Source connector pins</text><text class="h" x="930" y="35">Destination connector pins</text>']
colors = {"linked": "#2e8b57", "ambiguous": "#d9822b", "unmatched": "#c23b53"}
for index, link in enumerate(links):
y = 70 + index * row_height; color = colors.get(link.status, "#607d8b")
source = f"{link.source.project} {link.source.connector}.{link.source.pin} {link.source.net}"
destination = f"{link.destination.project} {link.destination.connector}.{link.destination.pin} {link.destination.net}" if link.destination.connector else "UNRESOLVED"
lines.extend([f'<text class="p" x="35" y="{y+4}">{escape(source)}</text>',
f'<text class="p" x="930" y="{y+4}">{escape(destination)}</text>',
f'<path d="M 340 {y} C 560 {y-12}, 650 {y+12}, 910 {y}" fill="none" stroke="{color}" stroke-width="3"/>',
f'<text class="w" x="570" y="{y-7}">{escape(link.wire_id)} AWG {escape(link.gauge_awg)} {escape(link.pair)} {escape(link.shield)}</text>'])
lines.append('</svg>')
return "\n".join(lines)