traceforge-pcb 1.0.0__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.
- traceforge/__init__.py +3 -0
- traceforge/__main__.py +3 -0
- traceforge/acp_server.py +570 -0
- traceforge/agent.py +680 -0
- traceforge/altium/__init__.py +6 -0
- traceforge/altium/cfb.py +70 -0
- traceforge/altium/cli.py +60 -0
- traceforge/altium/model.py +163 -0
- traceforge/altium/outputs.py +24 -0
- traceforge/altium/pcb.py +301 -0
- traceforge/altium/project.py +328 -0
- traceforge/altium/schematic.py +400 -0
- traceforge/altium/tools.py +166 -0
- traceforge/approval.py +219 -0
- traceforge/attachments.py +346 -0
- traceforge/background.py +253 -0
- traceforge/bench/__init__.py +5 -0
- traceforge/bench/adapters.py +337 -0
- traceforge/bench/checks.py +410 -0
- traceforge/bench/cli.py +121 -0
- traceforge/bench/design.py +439 -0
- traceforge/bench/kicad.py +99 -0
- traceforge/bench/partscheck.py +159 -0
- traceforge/bench/review.py +100 -0
- traceforge/bench/runner.py +226 -0
- traceforge/bench/score.py +204 -0
- traceforge/bench/tasks.py +102 -0
- traceforge/chat.py +1185 -0
- traceforge/checks.py +328 -0
- traceforge/checks_sides.py +118 -0
- traceforge/cli.py +2224 -0
- traceforge/clipboard.py +107 -0
- traceforge/config.py +299 -0
- traceforge/context.py +276 -0
- traceforge/design/__init__.py +1 -0
- traceforge/design/constraints.py +397 -0
- traceforge/design/generate.py +1789 -0
- traceforge/design/outline.py +905 -0
- traceforge/design/schematic_layout.py +932 -0
- traceforge/design/schematic_lint.py +329 -0
- traceforge/design/schematic_route.py +207 -0
- traceforge/design/sheets.py +854 -0
- traceforge/design/sides.py +328 -0
- traceforge/design/spec.py +462 -0
- traceforge/design/specsheet.py +2351 -0
- traceforge/design/specsheet_render.py +183 -0
- traceforge/desktop/__init__.py +109 -0
- traceforge/desktop/keys.py +90 -0
- traceforge/desktop/project.py +443 -0
- traceforge/desktop/review.py +20 -0
- traceforge/desktop/server.py +1277 -0
- traceforge/desktop/static/app.css +223 -0
- traceforge/desktop/static/app.js +683 -0
- traceforge/desktop/static/highlight.js +77 -0
- traceforge/desktop/static/index.html +89 -0
- traceforge/desktop/static/md.js +90 -0
- traceforge/desktop/static/viewer.js +213 -0
- traceforge/desktop/symbols.py +212 -0
- traceforge/desktop/update.py +65 -0
- traceforge/diagnostics.py +67 -0
- traceforge/errata.py +219 -0
- traceforge/fab.py +108 -0
- traceforge/fab_layers.py +44 -0
- traceforge/features/__init__.py +6 -0
- traceforge/features/candidates.py +117 -0
- traceforge/features/cli.py +200 -0
- traceforge/features/package.py +433 -0
- traceforge/features/revdiff.py +224 -0
- traceforge/features/sarif.py +145 -0
- traceforge/features/viewer.py +265 -0
- traceforge/firmware/__init__.py +3 -0
- traceforge/firmware/cli.py +174 -0
- traceforge/firmware/drivers.py +372 -0
- traceforge/firmware/drivers_data.py +256 -0
- traceforge/firmware/mcus.py +177 -0
- traceforge/firmware/netlist.py +55 -0
- traceforge/firmware/pinmap.py +296 -0
- traceforge/firmware/scaffold.py +466 -0
- traceforge/firmware/toolchain.py +262 -0
- traceforge/hooks.py +237 -0
- traceforge/kicad/__init__.py +0 -0
- traceforge/kicad/cli.py +519 -0
- traceforge/kicad/diffpair.py +174 -0
- traceforge/kicad/edgegeom.py +191 -0
- traceforge/kicad/edit.py +405 -0
- traceforge/kicad/escape.py +1410 -0
- traceforge/kicad/formats.py +1073 -0
- traceforge/kicad/impedance.py +320 -0
- traceforge/kicad/install.py +75 -0
- traceforge/kicad/libraries.py +490 -0
- traceforge/kicad/models3d.py +942 -0
- traceforge/kicad/outputs.py +81 -0
- traceforge/kicad/pcb.py +787 -0
- traceforge/kicad/planes.py +1242 -0
- traceforge/kicad/project.py +136 -0
- traceforge/kicad/route.py +2698 -0
- traceforge/kicad/routegeom.py +164 -0
- traceforge/kicad/schematic.py +268 -0
- traceforge/kicad/sides.py +34 -0
- traceforge/kicad/stackup.py +424 -0
- traceforge/kicad_plugin/__init__.py +12 -0
- traceforge/kicad_plugin/actions.py +92 -0
- traceforge/kicad_plugin/cli.py +66 -0
- traceforge/kicad_plugin/client.py +86 -0
- traceforge/kicad_plugin/context.py +257 -0
- traceforge/kicad_plugin/discovery.py +81 -0
- traceforge/kicad_plugin/install.py +203 -0
- traceforge/kicad_plugin/overlay.py +60 -0
- traceforge/kicad_plugin/payload/action_plugin.py +65 -0
- traceforge/kicad_plugin/payload/ipc_main.py +42 -0
- traceforge/kicad_plugin/payload/plugin.json +90 -0
- traceforge/kicad_plugin/payload/requirements.txt +1 -0
- traceforge/kicad_plugin/views.py +202 -0
- traceforge/langchain.py +57 -0
- traceforge/local.py +580 -0
- traceforge/mcp_server.py +304 -0
- traceforge/models.py +310 -0
- traceforge/next_steps.py +110 -0
- traceforge/parts/__init__.py +52 -0
- traceforge/parts/alternates.py +488 -0
- traceforge/parts/bom.py +423 -0
- traceforge/parts/brief.py +705 -0
- traceforge/parts/catalog.py +297 -0
- traceforge/parts/cli_sourcing.py +156 -0
- traceforge/parts/data/duty_rates.yaml +37 -0
- traceforge/parts/data/hs_codes.yaml +103 -0
- traceforge/parts/datasheet.py +278 -0
- traceforge/parts/fx.py +100 -0
- traceforge/parts/model.py +185 -0
- traceforge/parts/net.py +187 -0
- traceforge/parts/offers.py +46 -0
- traceforge/parts/packages.py +397 -0
- traceforge/parts/pinout.py +714 -0
- traceforge/parts/providers/__init__.py +17 -0
- traceforge/parts/providers/base.py +100 -0
- traceforge/parts/providers/jlc.py +364 -0
- traceforge/parts/providers/keyed.py +661 -0
- traceforge/parts/report.py +508 -0
- traceforge/parts/supply.py +330 -0
- traceforge/parts/verify.py +455 -0
- traceforge/parts/web.py +575 -0
- traceforge/plans.py +70 -0
- traceforge/preferences.py +127 -0
- traceforge/prices.py +130 -0
- traceforge/prices.yaml +28 -0
- traceforge/prompts/__init__.py +54 -0
- traceforge/prompts/system.md +103 -0
- traceforge/providers.py +764 -0
- traceforge/remote/__init__.py +33 -0
- traceforge/remote/client.py +422 -0
- traceforge/remote/oidc.py +240 -0
- traceforge/remote/orgs.py +510 -0
- traceforge/remote/server.py +690 -0
- traceforge/remote/store.py +100 -0
- traceforge/review_changes.py +187 -0
- traceforge/routing.py +99 -0
- traceforge/runtime.py +435 -0
- traceforge/sessions.py +324 -0
- traceforge/sexpr.py +279 -0
- traceforge/sim/__init__.py +17 -0
- traceforge/sim/acmath.py +234 -0
- traceforge/sim/circuit.py +499 -0
- traceforge/sim/cli.py +162 -0
- traceforge/sim/engine.py +172 -0
- traceforge/sim/ltspice.py +175 -0
- traceforge/sim/measure.py +123 -0
- traceforge/sim/models.py +76 -0
- traceforge/sim/project.py +218 -0
- traceforge/sim/rawfile.py +123 -0
- traceforge/sim/results.py +298 -0
- traceforge/sim/tune.py +172 -0
- traceforge/skill_commands.py +165 -0
- traceforge/skill_library/circuit-simulation/SKILL.md +30 -0
- traceforge/skill_library/compliance-review/SKILL.md +51 -0
- traceforge/skill_library/design-review/SKILL.md +47 -0
- traceforge/skill_library/errata-hunt/SKILL.md +30 -0
- traceforge/skill_library/firmware/SKILL.md +26 -0
- traceforge/skill_library/power-budget/SKILL.md +27 -0
- traceforge/skill_library/release-package/SKILL.md +29 -0
- traceforge/skill_library/sourcing-brief/SKILL.md +24 -0
- traceforge/skill_library/thermal-review/SKILL.md +15 -0
- traceforge/skills.py +131 -0
- traceforge/thermal.py +557 -0
- traceforge/tools/__init__.py +48 -0
- traceforge/tools/agent_tools.py +213 -0
- traceforge/tools/base.py +303 -0
- traceforge/tools/batch.py +155 -0
- traceforge/tools/connections.py +245 -0
- traceforge/tools/files.py +777 -0
- traceforge/tools/firmware_tools.py +218 -0
- traceforge/tools/kicad_tools.py +1072 -0
- traceforge/tools/models3d_tools.py +141 -0
- traceforge/tools/parts_tools.py +473 -0
- traceforge/tools/processes.py +246 -0
- traceforge/tools/review_tools.py +178 -0
- traceforge/tools/sim_tools.py +230 -0
- traceforge/tui.py +620 -0
- traceforge/updates.py +124 -0
- traceforge/validate/__init__.py +77 -0
- traceforge/validate/builtins.py +1091 -0
- traceforge/validate/circuits.py +1240 -0
- traceforge/validate/config.py +410 -0
- traceforge/validate/default.yaml +113 -0
- traceforge/validate/design.py +191 -0
- traceforge/validate/explain.py +112 -0
- traceforge/validate/grounding.py +169 -0
- traceforge/validate/ipc2221.py +350 -0
- traceforge/validate/multilayer.py +805 -0
- traceforge/validate/netmodel.py +261 -0
- traceforge/validate/partcheck.py +472 -0
- traceforge/validate/report.py +280 -0
- traceforge/validate/review.py +322 -0
- traceforge/validate/runner.py +662 -0
- traceforge/workspace.py +171 -0
- traceforge_pcb-1.0.0.dist-info/METADATA +463 -0
- traceforge_pcb-1.0.0.dist-info/RECORD +219 -0
- traceforge_pcb-1.0.0.dist-info/WHEEL +4 -0
- traceforge_pcb-1.0.0.dist-info/entry_points.txt +2 -0
- traceforge_pcb-1.0.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
"""Background shell processes: long simulations, renders, autorouter runs.
|
|
2
|
+
|
|
3
|
+
``execute`` with ``background: true`` starts a command in its own process group and
|
|
4
|
+
returns at once with an id. Output goes to a log file in the scratch folder, so it is
|
|
5
|
+
never held in memory and the model can page through it with ``read_file``.
|
|
6
|
+
``process_output`` reports status and new output (optionally waiting a while for the
|
|
7
|
+
process to finish); ``process_kill`` stops it with everything it spawned. All
|
|
8
|
+
processes of a session are killed when the session closes.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import asyncio
|
|
14
|
+
import os
|
|
15
|
+
import signal
|
|
16
|
+
import sys
|
|
17
|
+
import time
|
|
18
|
+
import uuid
|
|
19
|
+
from dataclasses import dataclass, field
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from traceforge.tools.base import Tool, ToolContext, ToolError, ToolKind
|
|
24
|
+
|
|
25
|
+
MAX_RUNNING = 8
|
|
26
|
+
MAX_WAIT = 600.0
|
|
27
|
+
OUTPUT_CHARS = 20_000
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass
|
|
31
|
+
class BackgroundProcess:
|
|
32
|
+
id: str
|
|
33
|
+
command: str
|
|
34
|
+
description: str
|
|
35
|
+
process: asyncio.subprocess.Process
|
|
36
|
+
log: Path
|
|
37
|
+
started: float = field(default_factory=time.monotonic)
|
|
38
|
+
read_offset: int = 0
|
|
39
|
+
killed: bool = False
|
|
40
|
+
waiter: asyncio.Task | None = None
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def running(self) -> bool:
|
|
44
|
+
return self.process.returncode is None
|
|
45
|
+
|
|
46
|
+
def status(self) -> str:
|
|
47
|
+
if self.running:
|
|
48
|
+
return "running"
|
|
49
|
+
if self.killed:
|
|
50
|
+
return "killed"
|
|
51
|
+
return "exited"
|
|
52
|
+
|
|
53
|
+
def summary(self) -> dict[str, Any]:
|
|
54
|
+
return {
|
|
55
|
+
"id": self.id,
|
|
56
|
+
"command": self.command,
|
|
57
|
+
"description": self.description,
|
|
58
|
+
"pid": self.process.pid,
|
|
59
|
+
"status": self.status(),
|
|
60
|
+
"exit_code": self.process.returncode,
|
|
61
|
+
"seconds": round(time.monotonic() - self.started, 1),
|
|
62
|
+
"log": self.log.as_posix(),
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
async def _kill_tree(process: asyncio.subprocess.Process) -> None:
|
|
67
|
+
if process.returncode is not None:
|
|
68
|
+
return
|
|
69
|
+
try:
|
|
70
|
+
if sys.platform != "win32":
|
|
71
|
+
os.killpg(os.getpgid(process.pid), signal.SIGKILL)
|
|
72
|
+
else: # pragma: no cover
|
|
73
|
+
process.kill()
|
|
74
|
+
except (ProcessLookupError, PermissionError, OSError):
|
|
75
|
+
try:
|
|
76
|
+
process.kill()
|
|
77
|
+
except ProcessLookupError:
|
|
78
|
+
return
|
|
79
|
+
try:
|
|
80
|
+
await asyncio.wait_for(process.wait(), 5)
|
|
81
|
+
except TimeoutError: # pragma: no cover
|
|
82
|
+
pass
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class ProcessManager:
|
|
86
|
+
def __init__(self, folder: Path):
|
|
87
|
+
self.folder = folder
|
|
88
|
+
self.processes: dict[str, BackgroundProcess] = {}
|
|
89
|
+
|
|
90
|
+
def running(self) -> list[BackgroundProcess]:
|
|
91
|
+
return [p for p in self.processes.values() if p.running]
|
|
92
|
+
|
|
93
|
+
async def start(
|
|
94
|
+
self, command: str, cwd: Path, env: dict[str, str], description: str = ""
|
|
95
|
+
) -> BackgroundProcess:
|
|
96
|
+
if len(self.running()) >= MAX_RUNNING:
|
|
97
|
+
raise ToolError(
|
|
98
|
+
f"{MAX_RUNNING} background processes are already running; wait for one or "
|
|
99
|
+
"stop one with process_kill"
|
|
100
|
+
)
|
|
101
|
+
self.folder.mkdir(parents=True, exist_ok=True)
|
|
102
|
+
identifier = uuid.uuid4().hex[:8]
|
|
103
|
+
log = self.folder / f"{identifier}.log"
|
|
104
|
+
handle = log.open("wb")
|
|
105
|
+
try:
|
|
106
|
+
process = await asyncio.create_subprocess_shell(
|
|
107
|
+
command,
|
|
108
|
+
cwd=cwd,
|
|
109
|
+
stdin=asyncio.subprocess.DEVNULL,
|
|
110
|
+
stdout=handle,
|
|
111
|
+
stderr=asyncio.subprocess.STDOUT,
|
|
112
|
+
env=env,
|
|
113
|
+
start_new_session=sys.platform != "win32",
|
|
114
|
+
)
|
|
115
|
+
finally:
|
|
116
|
+
handle.close() # the child keeps its own descriptor
|
|
117
|
+
item = BackgroundProcess(identifier, command, description, process, log)
|
|
118
|
+
item.waiter = asyncio.create_task(process.wait())
|
|
119
|
+
self.processes[identifier] = item
|
|
120
|
+
return item
|
|
121
|
+
|
|
122
|
+
def get(self, identifier: str) -> BackgroundProcess:
|
|
123
|
+
item = self.processes.get(identifier)
|
|
124
|
+
if item is None:
|
|
125
|
+
known = ", ".join(self.processes) or "none"
|
|
126
|
+
raise ToolError(f"no background process {identifier!r} (known: {known})")
|
|
127
|
+
return item
|
|
128
|
+
|
|
129
|
+
def new_output(self, item: BackgroundProcess, limit: int = OUTPUT_CHARS) -> tuple[str, int]:
|
|
130
|
+
"""Output written since the last call, and how many characters were skipped."""
|
|
131
|
+
try:
|
|
132
|
+
with item.log.open("rb") as handle:
|
|
133
|
+
handle.seek(item.read_offset)
|
|
134
|
+
data = handle.read()
|
|
135
|
+
except OSError:
|
|
136
|
+
return "", 0
|
|
137
|
+
item.read_offset += len(data)
|
|
138
|
+
text = data.decode("utf-8", errors="replace")
|
|
139
|
+
skipped = max(0, len(text) - limit)
|
|
140
|
+
return text[skipped:], skipped
|
|
141
|
+
|
|
142
|
+
async def kill(self, item: BackgroundProcess) -> None:
|
|
143
|
+
if item.running:
|
|
144
|
+
item.killed = True
|
|
145
|
+
await _kill_tree(item.process)
|
|
146
|
+
|
|
147
|
+
async def kill_all(self) -> None:
|
|
148
|
+
for item in list(self.processes.values()):
|
|
149
|
+
await self.kill(item)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def manager(ctx: ToolContext) -> ProcessManager:
|
|
153
|
+
found = ctx.state.get("processes")
|
|
154
|
+
if found is None:
|
|
155
|
+
assert ctx.scratch is not None
|
|
156
|
+
found = ProcessManager(ctx.scratch / "processes")
|
|
157
|
+
ctx.state["processes"] = found
|
|
158
|
+
return found
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
async def start_background(
|
|
162
|
+
command: str, cwd: Path, env: dict[str, str], ctx: ToolContext, description: str = ""
|
|
163
|
+
) -> dict[str, Any]:
|
|
164
|
+
item = await manager(ctx).start(command, cwd, env, description)
|
|
165
|
+
await asyncio.sleep(0.5) # catch commands that fail at once
|
|
166
|
+
output, _ = manager(ctx).new_output(item)
|
|
167
|
+
result = item.summary()
|
|
168
|
+
result["log"] = ctx.display(item.log)
|
|
169
|
+
result["output_so_far"] = output
|
|
170
|
+
result["note"] = (
|
|
171
|
+
"Running in the background. Check it with process_output (wait_seconds to block until "
|
|
172
|
+
"it finishes) and stop it with process_kill."
|
|
173
|
+
)
|
|
174
|
+
return result
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
async def process_output(args: dict[str, Any], ctx: ToolContext) -> dict[str, Any]:
|
|
178
|
+
procs = manager(ctx)
|
|
179
|
+
if not args.get("id"):
|
|
180
|
+
return {
|
|
181
|
+
"processes": [
|
|
182
|
+
{**p.summary(), "log": ctx.display(p.log)} for p in procs.processes.values()
|
|
183
|
+
]
|
|
184
|
+
}
|
|
185
|
+
item = procs.get(args["id"])
|
|
186
|
+
wait = min(max(float(args.get("wait_seconds") or 0), 0.0), MAX_WAIT)
|
|
187
|
+
if wait and item.running and item.waiter is not None:
|
|
188
|
+
try:
|
|
189
|
+
await asyncio.wait_for(asyncio.shield(item.waiter), wait)
|
|
190
|
+
except TimeoutError:
|
|
191
|
+
pass
|
|
192
|
+
output, skipped = procs.new_output(item)
|
|
193
|
+
result = item.summary()
|
|
194
|
+
result["log"] = ctx.display(item.log)
|
|
195
|
+
if skipped:
|
|
196
|
+
result["skipped_chars"] = skipped
|
|
197
|
+
result["note"] = f"{skipped} earlier characters of new output are in the log file"
|
|
198
|
+
result["new_output"] = output or "(no new output)"
|
|
199
|
+
return result
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
async def process_kill(args: dict[str, Any], ctx: ToolContext) -> dict[str, Any]:
|
|
203
|
+
procs = manager(ctx)
|
|
204
|
+
item = procs.get(args["id"])
|
|
205
|
+
was_running = item.running
|
|
206
|
+
await procs.kill(item)
|
|
207
|
+
output, _ = procs.new_output(item)
|
|
208
|
+
result = item.summary()
|
|
209
|
+
result["log"] = ctx.display(item.log)
|
|
210
|
+
result["result"] = "killed" if was_running else "already finished"
|
|
211
|
+
result["new_output"] = output
|
|
212
|
+
return result
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
PROCESS_TOOLS = [
|
|
216
|
+
Tool(
|
|
217
|
+
"process_output",
|
|
218
|
+
"Status and new output of background processes started with execute(background=true). "
|
|
219
|
+
"Without id, lists every background process. wait_seconds (max 600) blocks until the "
|
|
220
|
+
"process exits or the time runs out, so you can wait for a long job without polling.",
|
|
221
|
+
{
|
|
222
|
+
"type": "object",
|
|
223
|
+
"properties": {
|
|
224
|
+
"id": {"type": "string", "description": "process id returned by execute"},
|
|
225
|
+
"wait_seconds": {"type": "number", "description": "wait up to this long"},
|
|
226
|
+
},
|
|
227
|
+
},
|
|
228
|
+
process_output,
|
|
229
|
+
ToolKind.READ,
|
|
230
|
+
"id",
|
|
231
|
+
schedule=lambda args: "exclusive" if args.get("wait_seconds") else "read",
|
|
232
|
+
),
|
|
233
|
+
Tool(
|
|
234
|
+
"process_kill",
|
|
235
|
+
"Stop a background process and everything it started.",
|
|
236
|
+
{
|
|
237
|
+
"type": "object",
|
|
238
|
+
"properties": {"id": {"type": "string"}},
|
|
239
|
+
"required": ["id"],
|
|
240
|
+
},
|
|
241
|
+
process_kill,
|
|
242
|
+
ToolKind.WRITE,
|
|
243
|
+
"id",
|
|
244
|
+
schedule=lambda args: "exclusive",
|
|
245
|
+
),
|
|
246
|
+
]
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
"""Review-quality tools: errata hunt backed by sources, thermal analysis, IPC-2221 compliance check."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from traceforge.tools.base import Tool, ToolContext, ToolError
|
|
8
|
+
from traceforge.tools.kicad_tools import _pcb_path, _schematic_path
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def errata_hunt(args: dict[str, Any], ctx: ToolContext) -> dict:
|
|
12
|
+
from traceforge import errata
|
|
13
|
+
from traceforge.parts import Offline, ProviderError, default_catalog
|
|
14
|
+
from traceforge.parts.web import web_search
|
|
15
|
+
|
|
16
|
+
part = str(args.get("part") or "").strip()
|
|
17
|
+
sources: list[dict] = [
|
|
18
|
+
{"url": u, "kind": "errata" if "errat" in u.lower() else "datasheet"}
|
|
19
|
+
for u in args.get("urls") or []
|
|
20
|
+
]
|
|
21
|
+
sources += [
|
|
22
|
+
{
|
|
23
|
+
"path": str(ctx.resolve(p, must_exist=True)),
|
|
24
|
+
"kind": "errata" if "errat" in p.lower() else "datasheet",
|
|
25
|
+
}
|
|
26
|
+
for p in args.get("paths") or []
|
|
27
|
+
]
|
|
28
|
+
notes = []
|
|
29
|
+
if part and not args.get("no_search"):
|
|
30
|
+
datasheet_url = None
|
|
31
|
+
try:
|
|
32
|
+
info = default_catalog().lookup(part)
|
|
33
|
+
datasheet_url = getattr(info, "datasheet_url", None) if info else None
|
|
34
|
+
except (Offline, ProviderError) as exc:
|
|
35
|
+
notes.append(f"catalogue unavailable ({exc}); datasheet not looked up")
|
|
36
|
+
known = {s.get("url") for s in sources}
|
|
37
|
+
found = errata.find_sources(part, datasheet_url, lambda q: web_search(q, limit=8))
|
|
38
|
+
sources += [s for s in found if s.get("url") not in known]
|
|
39
|
+
if not found:
|
|
40
|
+
notes.append("no datasheet or errata document found by catalogue or web search")
|
|
41
|
+
if not sources:
|
|
42
|
+
raise ToolError("give 'part' (MPN), or 'urls' / 'paths' of datasheet and errata documents")
|
|
43
|
+
result = errata.hunt(sources, ctx.workspace / ".traceforge" / "datasheets")
|
|
44
|
+
result["part"] = part
|
|
45
|
+
if notes:
|
|
46
|
+
result["notes"] = notes
|
|
47
|
+
result["items"] = result["items"][: int(args.get("limit") or 25)]
|
|
48
|
+
return result
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def kicad_thermal(args: dict[str, Any], ctx: ToolContext) -> dict:
|
|
52
|
+
from traceforge import thermal
|
|
53
|
+
from traceforge.kicad.pcb import read_board
|
|
54
|
+
from traceforge.kicad.schematic import read_schematic
|
|
55
|
+
from traceforge.validate.netmodel import build_model
|
|
56
|
+
|
|
57
|
+
board = read_board(_pcb_path(args, ctx))
|
|
58
|
+
try:
|
|
59
|
+
schematic = read_schematic(_schematic_path(args, ctx))
|
|
60
|
+
except ToolError:
|
|
61
|
+
schematic = None
|
|
62
|
+
model = build_model(schematic, board)
|
|
63
|
+
|
|
64
|
+
def table(name: str) -> dict[str, float]:
|
|
65
|
+
return {str(k): float(v) for k, v in (args.get(name) or {}).items()}
|
|
66
|
+
|
|
67
|
+
return thermal.analyse(
|
|
68
|
+
model,
|
|
69
|
+
board,
|
|
70
|
+
ambient_c=float(args.get("ambient_c", 25.0)),
|
|
71
|
+
loads_ma=table("loads_ma"),
|
|
72
|
+
rail_current_ma=table("rail_current_ma"),
|
|
73
|
+
power_mw=table("power_mw"),
|
|
74
|
+
theta_ja=table("theta_ja"),
|
|
75
|
+
iq_ma=table("iq_ma"),
|
|
76
|
+
rds_on_mohm=table("rds_on_mohm"),
|
|
77
|
+
efficiency=float(args.get("efficiency", 0.85)),
|
|
78
|
+
window_mm=float(args.get("window_mm", 10.0)),
|
|
79
|
+
tj_max_c=float(args.get("tj_max_c", 125.0)),
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def ipc2221_check(args: dict[str, Any], ctx: ToolContext) -> dict:
|
|
84
|
+
from traceforge.kicad.pcb import read_board
|
|
85
|
+
from traceforge.kicad.project import discover
|
|
86
|
+
from traceforge.validate import ipc2221
|
|
87
|
+
|
|
88
|
+
board = read_board(_pcb_path(args, ctx))
|
|
89
|
+
spec = ipc2221.load_electrical(ctx.workspace)
|
|
90
|
+
currents = {str(k): float(v) for k, v in (args.get("currents_a") or {}).items()}
|
|
91
|
+
voltages = {str(k): float(v) for k, v in (args.get("voltages_v") or {}).items()}
|
|
92
|
+
classes = ipc2221.netclasses_of(discover(ctx.workspace).project)
|
|
93
|
+
findings = ipc2221.check_board(board, spec, classes, currents=currents, voltages=voltages)
|
|
94
|
+
out: dict[str, Any] = {"findings": [f.to_dict() for f in findings], "note": ipc2221.GUIDE_NOTE}
|
|
95
|
+
if args.get("width_for_a") is not None:
|
|
96
|
+
amps = float(args["width_for_a"])
|
|
97
|
+
out["min_width_mm"] = {
|
|
98
|
+
"external_1oz": round(ipc2221.min_width_mm(amps), 3),
|
|
99
|
+
"internal_0.5oz": round(ipc2221.min_width_mm(amps, copper_oz=0.5, internal=True), 3),
|
|
100
|
+
"delta_t_k": 10,
|
|
101
|
+
}
|
|
102
|
+
if args.get("voltage_v") is not None:
|
|
103
|
+
volts = float(args["voltage_v"])
|
|
104
|
+
out["spacing_mm"] = {
|
|
105
|
+
**{c: ipc2221.spacing_mm(volts, c) for c in ipc2221.SPACING_COLUMNS},
|
|
106
|
+
"creepage_pd2_material_III": ipc2221.creepage_mm(volts, 3),
|
|
107
|
+
"clearance_ovc2_pd2": ipc2221.clearance_mm(volts),
|
|
108
|
+
}
|
|
109
|
+
return out
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
_MAP = {"type": "object", "additionalProperties": {"type": "number"}}
|
|
113
|
+
|
|
114
|
+
REVIEW_TOOLS = [
|
|
115
|
+
Tool(
|
|
116
|
+
"errata_hunt",
|
|
117
|
+
"Hunt errata for a part from retrievable sources: fetches the datasheet and errata documents "
|
|
118
|
+
"(catalogue datasheet URL, web search for errata sheets, or given urls/paths), extracts candidate "
|
|
119
|
+
"items with page and section citations and a P0-P3 severity, merges duplicates and returns a ranked "
|
|
120
|
+
"list. Items whose source could not be retrieved carry verified=false. Candidates are heuristic: "
|
|
121
|
+
"confirm each against the cited page and the silicon revision in use.",
|
|
122
|
+
{
|
|
123
|
+
"type": "object",
|
|
124
|
+
"properties": {
|
|
125
|
+
"part": {"type": "string", "description": "MPN or LCSC code"},
|
|
126
|
+
"urls": {"type": "array", "items": {"type": "string"}},
|
|
127
|
+
"paths": {"type": "array", "items": {"type": "string"}},
|
|
128
|
+
"no_search": {"type": "boolean"},
|
|
129
|
+
"limit": {"type": "integer"},
|
|
130
|
+
},
|
|
131
|
+
},
|
|
132
|
+
errata_hunt,
|
|
133
|
+
),
|
|
134
|
+
Tool(
|
|
135
|
+
"kicad_thermal",
|
|
136
|
+
"Screening thermal analysis: per-part dissipation (linear regulators (Vin-Vout)*I, switching "
|
|
137
|
+
"regulators from efficiency, resistors, LEDs, MOSFET I^2*Rds), copper area around the part from the "
|
|
138
|
+
"board's pours/tracks/vias, junction temperature from theta_JA (user/datasheet value or a package "
|
|
139
|
+
"table) and ambient, hotspots and mitigation. Give IC currents in loads_ma (ref -> mA) or "
|
|
140
|
+
"rail_current_ma (net -> mA). States its limits in the output.",
|
|
141
|
+
{
|
|
142
|
+
"type": "object",
|
|
143
|
+
"properties": {
|
|
144
|
+
"pcb": {"type": "string"},
|
|
145
|
+
"schematic": {"type": "string"},
|
|
146
|
+
"ambient_c": {"type": "number"},
|
|
147
|
+
"loads_ma": _MAP,
|
|
148
|
+
"rail_current_ma": _MAP,
|
|
149
|
+
"power_mw": _MAP,
|
|
150
|
+
"theta_ja": _MAP,
|
|
151
|
+
"iq_ma": _MAP,
|
|
152
|
+
"rds_on_mohm": _MAP,
|
|
153
|
+
"efficiency": {"type": "number"},
|
|
154
|
+
"window_mm": {"type": "number"},
|
|
155
|
+
"tj_max_c": {"type": "number"},
|
|
156
|
+
},
|
|
157
|
+
},
|
|
158
|
+
kicad_thermal,
|
|
159
|
+
),
|
|
160
|
+
Tool(
|
|
161
|
+
"kicad_ipc2221",
|
|
162
|
+
"IPC-2221 check of the board: tracks too narrow for the net's declared current "
|
|
163
|
+
"(.traceforge/electrical.yaml, net class names like Power_10A, or currents_a) and clearances too "
|
|
164
|
+
"small for the voltage between nets. Also answers 'width_for_a' and 'voltage_v' lookups "
|
|
165
|
+
"(IPC-2221 spacing, IEC 60664-1 style creepage/clearance guide; not certification).",
|
|
166
|
+
{
|
|
167
|
+
"type": "object",
|
|
168
|
+
"properties": {
|
|
169
|
+
"pcb": {"type": "string"},
|
|
170
|
+
"currents_a": _MAP,
|
|
171
|
+
"voltages_v": _MAP,
|
|
172
|
+
"width_for_a": {"type": "number"},
|
|
173
|
+
"voltage_v": {"type": "number"},
|
|
174
|
+
},
|
|
175
|
+
},
|
|
176
|
+
ipc2221_check,
|
|
177
|
+
),
|
|
178
|
+
]
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
"""Simulation tools: ``kicad_simulate``, ``sim_tune`` and ``sim_plot`` (ngspice; LTspice export)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from traceforge.sim import SimError, find_ngspice
|
|
8
|
+
from traceforge.sim.circuit import Circuit
|
|
9
|
+
from traceforge.sim.project import (
|
|
10
|
+
export_ltspice,
|
|
11
|
+
load_circuit,
|
|
12
|
+
replot,
|
|
13
|
+
simulate,
|
|
14
|
+
split_analysis,
|
|
15
|
+
)
|
|
16
|
+
from traceforge.sim.tune import tune
|
|
17
|
+
from traceforge.tools.base import Tool, ToolContext, ToolError, ToolKind
|
|
18
|
+
from traceforge.tools.kicad_tools import _out_dir, _schematic_path
|
|
19
|
+
|
|
20
|
+
__all__ = ["SIM_TOOLS", "find_ngspice", "simulate_tool", "tune_tool"]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _circuit(args: dict[str, Any], ctx: ToolContext, out) -> Circuit:
|
|
24
|
+
try:
|
|
25
|
+
if args.get("netlist"):
|
|
26
|
+
circuit = Circuit.from_file(ctx.resolve(args["netlist"], must_exist=True))
|
|
27
|
+
else:
|
|
28
|
+
circuit = load_circuit(
|
|
29
|
+
_schematic_path(args, ctx),
|
|
30
|
+
out,
|
|
31
|
+
sources=args.get("sources"),
|
|
32
|
+
ground=args.get("ground_nets"),
|
|
33
|
+
)
|
|
34
|
+
for ref, value in (args.get("set") or {}).items():
|
|
35
|
+
circuit.set_value(ref, str(value))
|
|
36
|
+
return circuit
|
|
37
|
+
except (SimError, ValueError, KeyError, OSError) as exc:
|
|
38
|
+
raise ToolError(f"cannot build the circuit: {exc}") from exc
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def simulate_tool(args: dict[str, Any], ctx: ToolContext) -> dict:
|
|
42
|
+
out = _out_dir(ctx, "sim")
|
|
43
|
+
circuit = _circuit(args, ctx, out)
|
|
44
|
+
analyses, meas = split_analysis(args.get("analysis"))
|
|
45
|
+
meas += [str(m) for m in args.get("meas") or []]
|
|
46
|
+
if not analyses:
|
|
47
|
+
return {
|
|
48
|
+
"circuit": circuit.to_spice(),
|
|
49
|
+
"generic_models": circuit.generic,
|
|
50
|
+
"skipped_parts": circuit.skipped,
|
|
51
|
+
"warnings": circuit.warnings,
|
|
52
|
+
"note": 'circuit built; pass \'analysis\' (e.g. {"type":"ac","start":10,"stop":"100k"} '
|
|
53
|
+
"or '.tran 1u 5m') to simulate",
|
|
54
|
+
}
|
|
55
|
+
if args.get("engine") == "ltspice":
|
|
56
|
+
result = export_ltspice(circuit, analyses, out, args.get("name") or "circuit")
|
|
57
|
+
result["generic_models"] = circuit.generic
|
|
58
|
+
return result
|
|
59
|
+
probes = [str(p) for p in args.get("probes") or []]
|
|
60
|
+
results = []
|
|
61
|
+
for i, analysis in enumerate(analyses):
|
|
62
|
+
try:
|
|
63
|
+
results.append(
|
|
64
|
+
simulate(
|
|
65
|
+
circuit,
|
|
66
|
+
_with_pz(analysis, args.get("pz")),
|
|
67
|
+
out,
|
|
68
|
+
meas=meas,
|
|
69
|
+
probes=probes,
|
|
70
|
+
export=[str(e) for e in args.get("export") or []],
|
|
71
|
+
loop=args.get("loop_gain"),
|
|
72
|
+
name=f"run{i + 1}" if len(analyses) > 1 else "run",
|
|
73
|
+
timeout=float(args.get("timeout") or ctx.shell_timeout),
|
|
74
|
+
)
|
|
75
|
+
)
|
|
76
|
+
except (SimError, ValueError, KeyError) as exc:
|
|
77
|
+
raise ToolError(str(exc)) from exc
|
|
78
|
+
return results[0] if len(results) == 1 else {"runs": results}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _with_pz(analysis: Any, pz: Any):
|
|
82
|
+
from traceforge.sim.engine import parse_analysis
|
|
83
|
+
|
|
84
|
+
ana = parse_analysis(analysis)
|
|
85
|
+
if pz and ana.kind == "ac" and isinstance(pz, list) and len(pz) == 2:
|
|
86
|
+
ana.pz = (str(pz[0]), str(pz[1]))
|
|
87
|
+
return ana
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def tune_tool(args: dict[str, Any], ctx: ToolContext) -> dict:
|
|
91
|
+
out = _out_dir(ctx, "sim-tune")
|
|
92
|
+
circuit = _circuit(args, ctx, out)
|
|
93
|
+
analyses, meas = split_analysis(args.get("analysis"))
|
|
94
|
+
if not analyses or not args.get("parameter") or not args.get("target"):
|
|
95
|
+
raise ToolError("sim_tune needs 'parameter', 'target' and 'analysis'")
|
|
96
|
+
bounds = args.get("bounds")
|
|
97
|
+
try:
|
|
98
|
+
result = tune(
|
|
99
|
+
circuit,
|
|
100
|
+
str(args["parameter"]),
|
|
101
|
+
args["target"] if isinstance(args["target"], str) else float(args["target"]),
|
|
102
|
+
float(args.get("tolerance") if args.get("tolerance") is not None else 0.01),
|
|
103
|
+
quantity=args.get("quantity"),
|
|
104
|
+
analysis=analyses[0],
|
|
105
|
+
bounds=(float(bounds[0]), float(bounds[1])) if bounds else None,
|
|
106
|
+
max_iter=int(args.get("max_iter") or 25),
|
|
107
|
+
workdir=out,
|
|
108
|
+
meas=meas or None,
|
|
109
|
+
)
|
|
110
|
+
except (SimError, ValueError, KeyError) as exc:
|
|
111
|
+
raise ToolError(str(exc)) from exc
|
|
112
|
+
data = result.to_dict()
|
|
113
|
+
tuned = out / "tuned.cir"
|
|
114
|
+
tuned.write_text(result.circuit.to_spice(), encoding="utf-8")
|
|
115
|
+
data["tuned_netlist"] = str(tuned)
|
|
116
|
+
data["values"] = {
|
|
117
|
+
ref.strip(): result.circuit.element(ref.strip()).value
|
|
118
|
+
for ref in result.parameter.split(",")
|
|
119
|
+
if not ref.strip().lower().startswith("param:")
|
|
120
|
+
}
|
|
121
|
+
data["next_step"] = "apply the tuned values to the schematic with kicad_set_field, then rerun"
|
|
122
|
+
return data
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def plot_tool(args: dict[str, Any], ctx: ToolContext) -> dict:
|
|
126
|
+
raw = ctx.resolve(args.get("raw") or str(_out_dir(ctx, "sim") / "run.raw"), must_exist=True)
|
|
127
|
+
kinds = [str(k) for k in args.get("formats") or ["svg"]]
|
|
128
|
+
if any(k not in {"svg", "csv", "vcd"} for k in kinds):
|
|
129
|
+
raise ToolError("formats must be svg, csv or vcd")
|
|
130
|
+
try:
|
|
131
|
+
return replot(raw, _out_dir(ctx, "sim"), args.get("signals"), kinds)
|
|
132
|
+
except (SimError, ValueError, KeyError, OSError) as exc:
|
|
133
|
+
raise ToolError(str(exc)) from exc
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
_SOURCES = {
|
|
137
|
+
"type": "array",
|
|
138
|
+
"description": "Sources to add (a schematic has none unless it has V/I parts): "
|
|
139
|
+
'{"pos":"VBUS","neg":"GND","dc":5,"ac":1} or {"pos":"IN","spec":"PULSE(0 5 0 1n 1n 1m 2m)"}',
|
|
140
|
+
"items": {"type": "object"},
|
|
141
|
+
}
|
|
142
|
+
_COMMON = {
|
|
143
|
+
"schematic": {"type": "string", "description": "KiCad .kicad_sch (default: the project's)"},
|
|
144
|
+
"netlist": {"type": "string", "description": "a SPICE deck instead of a schematic"},
|
|
145
|
+
"sources": _SOURCES,
|
|
146
|
+
"ground_nets": {"type": "array", "items": {"type": "string"}},
|
|
147
|
+
"set": {"type": "object", "description": 'component values to override, e.g. {"R1":"10k"}'},
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
SIM_TOOLS = [
|
|
151
|
+
Tool(
|
|
152
|
+
"kicad_simulate",
|
|
153
|
+
"Simulate a schematic (or SPICE deck) with ngspice: DC, AC, transient, noise or "
|
|
154
|
+
"operating point. Builds the netlist from the schematic's connectivity, using Sim.* "
|
|
155
|
+
"fields where present and clearly labelled generic models otherwise (LED, diode, "
|
|
156
|
+
"op-amp, LDO, MOSFET, BJT); parts without a model are listed as skipped. Returns a "
|
|
157
|
+
"summary, .meas values, -3 dB point, poles (ngspice .pz or fitted), margins (with "
|
|
158
|
+
"'loop_gain'), and exports CSV/VCD/SVG. engine 'ltspice' only writes a netlist and "
|
|
159
|
+
".asc for LTspice (it cannot run here).",
|
|
160
|
+
{
|
|
161
|
+
"type": "object",
|
|
162
|
+
"properties": {
|
|
163
|
+
**_COMMON,
|
|
164
|
+
"analysis": {
|
|
165
|
+
"description": "an analysis or list: '.ac dec 20 10 1meg', '.tran 1u 5m', "
|
|
166
|
+
"or {type: op|dc|ac|tran|noise, ...}; '.meas ...' lines may be mixed in",
|
|
167
|
+
},
|
|
168
|
+
"meas": {"type": "array", "items": {"type": "string"}},
|
|
169
|
+
"probes": {
|
|
170
|
+
"type": "array",
|
|
171
|
+
"items": {"type": "string"},
|
|
172
|
+
"description": "v(out), i(R5), @r1[i]",
|
|
173
|
+
},
|
|
174
|
+
"export": {"type": "array", "items": {"enum": ["csv", "vcd", "svg"]}},
|
|
175
|
+
"pz": {
|
|
176
|
+
"type": "array",
|
|
177
|
+
"items": {"type": "string"},
|
|
178
|
+
"description": "[input node, output node] for ngspice .pz",
|
|
179
|
+
},
|
|
180
|
+
"loop_gain": {
|
|
181
|
+
"type": "string",
|
|
182
|
+
"description": "AC signal that is the loop gain, for phase/gain margin",
|
|
183
|
+
},
|
|
184
|
+
"engine": {"enum": ["ngspice", "ltspice"]},
|
|
185
|
+
"name": {"type": "string"},
|
|
186
|
+
"timeout": {"type": "number"},
|
|
187
|
+
},
|
|
188
|
+
},
|
|
189
|
+
simulate_tool,
|
|
190
|
+
ToolKind.SHELL,
|
|
191
|
+
),
|
|
192
|
+
Tool(
|
|
193
|
+
"sim_tune",
|
|
194
|
+
"Closed-loop tuning: change a component (or a tied group like 'R1,R2' or 'param:NAME') "
|
|
195
|
+
"and rerun ngspice until a measured quantity meets a target, e.g. parameter 'R1,R2', "
|
|
196
|
+
"target 'f3db(v(out))=500', analysis '.ac dec 40 10 100k'. Reports every iteration. "
|
|
197
|
+
"Quantities: f3db, dc_gain_db, gain_db(v,f), phase_deg, phase_margin, gain_margin, "
|
|
198
|
+
"unity_gain_freq, value, max, min, pp, mean, rms, rise_time, meas(name), v(node), i(Rref).",
|
|
199
|
+
{
|
|
200
|
+
"type": "object",
|
|
201
|
+
"properties": {
|
|
202
|
+
**_COMMON,
|
|
203
|
+
"parameter": {"type": "string"},
|
|
204
|
+
"target": {"description": "'quantity=value' or a number with 'quantity'"},
|
|
205
|
+
"quantity": {"type": "string"},
|
|
206
|
+
"tolerance": {"type": "number", "description": "relative, default 0.01"},
|
|
207
|
+
"analysis": {},
|
|
208
|
+
"bounds": {"type": "array", "items": {"type": "number"}},
|
|
209
|
+
"max_iter": {"type": "integer"},
|
|
210
|
+
},
|
|
211
|
+
"required": ["parameter", "target", "analysis"],
|
|
212
|
+
},
|
|
213
|
+
tune_tool,
|
|
214
|
+
ToolKind.SHELL,
|
|
215
|
+
),
|
|
216
|
+
Tool(
|
|
217
|
+
"sim_plot",
|
|
218
|
+
"Re-plot or export a simulation rawfile (ngspice, or LTspice .raw) as SVG, CSV or VCD.",
|
|
219
|
+
{
|
|
220
|
+
"type": "object",
|
|
221
|
+
"properties": {
|
|
222
|
+
"raw": {"type": "string", "description": "default: the last kicad_simulate run"},
|
|
223
|
+
"signals": {"type": "array", "items": {"type": "string"}},
|
|
224
|
+
"formats": {"type": "array", "items": {"enum": ["svg", "csv", "vcd"]}},
|
|
225
|
+
},
|
|
226
|
+
},
|
|
227
|
+
plot_tool,
|
|
228
|
+
ToolKind.WRITE,
|
|
229
|
+
),
|
|
230
|
+
]
|