acps-math-visualizer 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.
@@ -0,0 +1,234 @@
1
+ """Transformation Agent: formula parameters to geometric meaning and keyframes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from acps_sdk.aip import TaskResult, TaskState
6
+
7
+ from ..math_engine import SinusoidParameters, analyze_sinusoid, format_quantity
8
+ from ..models import (
9
+ AnimationFrame,
10
+ MessageKind,
11
+ ParameterEffect,
12
+ TransformationProduct,
13
+ TransformationRequest,
14
+ WireMessage,
15
+ )
16
+ from .base import AipAgent
17
+
18
+
19
+ class TransformationAgent(AipAgent):
20
+ """Explains parameters and returns an executable, Plotter-compatible plan."""
21
+
22
+ name = "Transformation Agent"
23
+ description = (
24
+ "Recognizes A*sin(B*x+C)+D and its cosine equivalent, explains amplitude, "
25
+ "period, phase and vertical shift, and emits ordered animation keyframes."
26
+ )
27
+ skill_id = "function-transformation-analysis"
28
+ skill_name = "Geometric function transformation analysis"
29
+ skill_description = (
30
+ "Maps formula parameters to vertical stretch, horizontal scaling, phase shift "
31
+ "and midline movement with explicit direction and exact multiples of pi."
32
+ )
33
+ tags = ("math-transformation", "amplitude-period-phase", "animation-plan")
34
+ examples = (
35
+ "Explain why y=2*sin(x+π/4) moves left by π/4.",
36
+ "Create keyframes from sin(x) to 3*cos(2*x-π/2)+1.",
37
+ )
38
+ product_name = "transformation-analysis"
39
+
40
+ def handle_start(self, message: WireMessage, task: TaskResult) -> TaskResult:
41
+ if message.kind is not MessageKind.TRANSFORM_REQUEST:
42
+ raise ValueError("Transformation Agent requires TRANSFORM_REQUEST")
43
+ request = TransformationRequest.model_validate(message.payload)
44
+ if request.plot.session_id != message.session_id:
45
+ raise ValueError("plot evidence belongs to a different session")
46
+ if request.plot.agent != "Plotter Agent":
47
+ raise ValueError("transformation analysis requires a Plotter Agent product")
48
+ parameters = analyze_sinusoid(request.plot.normalized_expression)
49
+ if parameters is None:
50
+ product = self._general_product(message, request.plot.normalized_expression)
51
+ else:
52
+ product = self._sinusoidal_product(message, parameters)
53
+ return self.publish(
54
+ task,
55
+ product,
56
+ summary=(
57
+ f"family={product.function_family}; canonical={product.canonical_form}; "
58
+ f"keyframes={len(product.frames)}"
59
+ ),
60
+ state=TaskState.Completed,
61
+ )
62
+
63
+ def _general_product(self, message: WireMessage, expression: str) -> TransformationProduct:
64
+ effect = ParameterEffect(
65
+ parameter="general expression",
66
+ value=expression,
67
+ effect=(
68
+ "该式不是单一正弦/余弦仿射变换,不能套用振幅与相位公式;"
69
+ "本轮以安全数值采样展示整体形状。"
70
+ ),
71
+ )
72
+ return TransformationProduct(
73
+ session_id=message.session_id,
74
+ task_id=message.task_id,
75
+ agent=self.name,
76
+ function_family="general-function",
77
+ canonical_form=f"y = {expression}",
78
+ is_sinusoidal=False,
79
+ effects=[effect],
80
+ steps=["先观察零点、单调性、间断点与值域,再选择对应的专项变换模型。"],
81
+ )
82
+
83
+ def _sinusoidal_product(
84
+ self,
85
+ message: WireMessage,
86
+ parameters: SinusoidParameters,
87
+ ) -> TransformationProduct:
88
+ amplitude = format_quantity(parameters.amplitude)
89
+ frequency = format_quantity(parameters.b)
90
+ period = format_quantity(parameters.period)
91
+ phase = format_quantity(parameters.phase_shift)
92
+ vertical = format_quantity(parameters.d)
93
+ direction = "左移" if parameters.phase_shift < 0 else "右移"
94
+ if parameters.phase_shift == 0:
95
+ phase_effect = "相位平移为 0,图像没有左右移动。"
96
+ else:
97
+ phase_effect = (
98
+ f"h={phase},所以图像相对基准{direction} "
99
+ f"{format_quantity(abs(parameters.phase_shift))};方向由 h=-C/B 决定。"
100
+ )
101
+ if abs(parameters.b) == 1:
102
+ period_effect = f"T=2π/|B|={period},横向尺度与基准函数相同。"
103
+ else:
104
+ period_effect = f"T=2π/|B|={period},B={frequency} 控制水平压缩或拉伸。"
105
+ effects = [
106
+ ParameterEffect(
107
+ parameter="A · 振幅",
108
+ value=amplitude,
109
+ effect=(
110
+ f"|A|={amplitude},纵向缩放 {amplitude} 倍,"
111
+ f"围绕中线 y={vertical} 的最大偏移为 {amplitude}。"
112
+ ),
113
+ ),
114
+ ParameterEffect(
115
+ parameter="B · 周期",
116
+ value=f"B={frequency}, T={period}",
117
+ effect=period_effect,
118
+ ),
119
+ ParameterEffect(
120
+ parameter="h · 相位",
121
+ value=phase,
122
+ effect=phase_effect,
123
+ ),
124
+ ParameterEffect(
125
+ parameter="D · 中线",
126
+ value=vertical,
127
+ effect=f"D={vertical},平衡位置是直线 y={vertical}。",
128
+ ),
129
+ ]
130
+ steps = [
131
+ (
132
+ f"以 y={parameters.trig_function}(x) 为基准,"
133
+ f"使用 A·{parameters.trig_function}(B·x+C)+D。"
134
+ ),
135
+ f"先看 A={format_quantity(parameters.a)}:{effects[0].effect}",
136
+ f"再看 B={frequency}:{period_effect}",
137
+ f"最后看 h=-C/B={phase}:{phase_effect}",
138
+ ]
139
+ if parameters.a < 0:
140
+ steps.append("A<0,因此除纵向伸缩外,还要关于中线作上下翻转。")
141
+ if parameters.b < 0:
142
+ steps.append("B<0,还包含关于竖直方向的反向;周期性计算使用 |B|。")
143
+ canonical = _canonical_form(parameters)
144
+ return TransformationProduct(
145
+ session_id=message.session_id,
146
+ task_id=message.task_id,
147
+ agent=self.name,
148
+ function_family=f"{parameters.trig_function}-affine-transform",
149
+ canonical_form=canonical,
150
+ is_sinusoidal=True,
151
+ trig_function=parameters.trig_function,
152
+ amplitude=parameters.amplitude,
153
+ angular_frequency=parameters.b,
154
+ period=parameters.period,
155
+ phase_shift=parameters.phase_shift,
156
+ vertical_shift=parameters.d,
157
+ effects=effects,
158
+ steps=steps,
159
+ frames=_build_keyframes(parameters),
160
+ )
161
+
162
+
163
+ def _canonical_form(parameters: SinusoidParameters) -> str:
164
+ if parameters.a == 1:
165
+ prefix = ""
166
+ elif parameters.a == -1:
167
+ prefix = "-"
168
+ else:
169
+ prefix = f"{format_quantity(parameters.a)}*"
170
+ if parameters.b == 1:
171
+ argument = "x"
172
+ elif parameters.b == -1:
173
+ argument = "-x"
174
+ else:
175
+ argument = f"{format_quantity(parameters.b)}*x"
176
+ if parameters.c > 0:
177
+ argument += f" + {format_quantity(parameters.c)}"
178
+ elif parameters.c < 0:
179
+ argument += f" - {format_quantity(abs(parameters.c))}"
180
+ canonical = f"y = {prefix}{parameters.trig_function}({argument})"
181
+ if parameters.d > 0:
182
+ canonical += f" + {format_quantity(parameters.d)}"
183
+ elif parameters.d < 0:
184
+ canonical += f" - {format_quantity(abs(parameters.d))}"
185
+ return canonical
186
+
187
+
188
+ def _build_keyframes(parameters: SinusoidParameters) -> list[AnimationFrame]:
189
+ baseline = AnimationFrame(
190
+ stage="baseline",
191
+ label=f"基准 {parameters.trig_function}(x)",
192
+ detail="从单位振幅、原始周期、零相位的基准曲线开始。",
193
+ a=1.0,
194
+ b=1.0,
195
+ c=0.0,
196
+ d=0.0,
197
+ )
198
+ target = AnimationFrame(
199
+ stage="target",
200
+ label="目标函数",
201
+ detail="所有参数均已应用。",
202
+ a=parameters.a,
203
+ b=parameters.b,
204
+ c=parameters.c,
205
+ d=parameters.d,
206
+ )
207
+ if all(
208
+ abs(getattr(baseline, name) - getattr(target, name)) < 1e-12
209
+ for name in ("a", "b", "c", "d")
210
+ ):
211
+ return []
212
+ frames = [baseline]
213
+ current = baseline
214
+ stages = (
215
+ ("a", "amplitude", "调节振幅", "改变 A,观察峰谷到中线的距离。"),
216
+ ("b", "period", "调节周期", "改变 B,观察波峰之间的水平距离。"),
217
+ ("c", "phase", "调节相位", "改变 C,观察同一波形如何左右移动。"),
218
+ ("d", "vertical", "调节中线", "改变 D,观察整条曲线上下平移。"),
219
+ )
220
+ for attribute, stage, label, detail in stages:
221
+ if abs(getattr(current, attribute) - getattr(target, attribute)) > 1e-12:
222
+ current = current.model_copy(
223
+ update={
224
+ "stage": stage,
225
+ "label": label,
226
+ "detail": detail,
227
+ attribute: getattr(target, attribute),
228
+ }
229
+ )
230
+ frames.append(current)
231
+ return frames
232
+
233
+
234
+ __all__ = ["TransformationAgent"]
@@ -0,0 +1,76 @@
1
+ """Command-line entry point for scripted and custom visualizations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ from collections.abc import Sequence
7
+
8
+ from . import __version__
9
+ from .demo import run_visualization
10
+ from .models import FunctionRequest, IntuitionConcept
11
+
12
+ DEMO_EXPRESSION = "y=2*sin(x+π/4)"
13
+
14
+
15
+ def build_parser() -> argparse.ArgumentParser:
16
+ parser = argparse.ArgumentParser(
17
+ prog="acps-math-viz",
18
+ description=(
19
+ "ACPs multi-agent mathematical visualization: plot data and motion, "
20
+ "explain parameter transformations, and build memorable intuition."
21
+ ),
22
+ )
23
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
24
+ parser.set_defaults(
25
+ output="output",
26
+ concept=IntuitionConcept.AUTO.value,
27
+ json=False,
28
+ )
29
+ subparsers = parser.add_subparsers(dest="command")
30
+
31
+ demo = subparsers.add_parser("demo", help="run the y=2*sin(x+π/4) collaboration demo")
32
+ _add_common_arguments(demo)
33
+
34
+ plot = subparsers.add_parser("plot", help="visualize a custom one-variable function")
35
+ plot.add_argument("expression", help="for example: y=3*cos(2*x-π/2)+1")
36
+ plot.add_argument("--x-min", type=float, default=-6.283185307179586)
37
+ plot.add_argument("--x-max", type=float, default=6.283185307179586)
38
+ plot.add_argument("--samples", type=int, default=161)
39
+ _add_common_arguments(plot)
40
+ return parser
41
+
42
+
43
+ def _add_common_arguments(parser: argparse.ArgumentParser) -> None:
44
+ parser.add_argument("--output", default="output", help="artifact output directory")
45
+ parser.add_argument(
46
+ "--concept",
47
+ choices=[item.value for item in IntuitionConcept],
48
+ default=IntuitionConcept.AUTO.value,
49
+ help="Intuition Agent explanation mode",
50
+ )
51
+ parser.add_argument("--json", action="store_true", help="print the typed result as JSON")
52
+
53
+
54
+ def main(argv: Sequence[str] | None = None) -> int:
55
+ args = build_parser().parse_args(argv)
56
+ command = args.command or "demo"
57
+ expression = DEMO_EXPRESSION if command == "demo" else args.expression
58
+ request = FunctionRequest(
59
+ expression=expression,
60
+ x_min=getattr(args, "x_min", -6.283185307179586),
61
+ x_max=getattr(args, "x_max", 6.283185307179586),
62
+ samples=getattr(args, "samples", 161),
63
+ output_dir=args.output,
64
+ )
65
+ try:
66
+ return run_visualization(
67
+ request,
68
+ concept=IntuitionConcept(args.concept),
69
+ as_json=args.json,
70
+ )
71
+ except (ValueError, RuntimeError, LookupError) as exc:
72
+ print(f"acps-math-viz: {exc}")
73
+ return 1
74
+
75
+
76
+ __all__ = ["DEMO_EXPRESSION", "build_parser", "main"]
@@ -0,0 +1,125 @@
1
+ """One-command demonstration and human-readable collaboration report."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import json
7
+ import uuid
8
+ from pathlib import Path
9
+
10
+ from . import __version__
11
+ from .math_engine import format_quantity
12
+ from .mesh import LocalAgentMesh
13
+ from .models import AgentTrace, FunctionRequest, IntuitionConcept, VisualizationResult
14
+ from .orchestrator import MathOrchestrator
15
+
16
+ BANNER = "=" * 78
17
+
18
+
19
+ def run_visualization(
20
+ request: FunctionRequest,
21
+ *,
22
+ concept: IntuitionConcept = IntuitionConcept.AUTO,
23
+ as_json: bool = False,
24
+ ) -> int:
25
+ """Start the real ACPs mesh, execute one request, and persist all artifacts."""
26
+
27
+ if not as_json:
28
+ print(BANNER)
29
+ print(f"ACPs Math Visualizer v{__version__} · Multi-agent Transformation Studio")
30
+ print(f"[User] {request.expression}")
31
+ print("Flow: ADP discovery → Plotter → Transformation → Plotter GIF → Intuition")
32
+ print(BANNER)
33
+ with LocalAgentMesh() as mesh:
34
+ if not as_json:
35
+ for agent in mesh.agents:
36
+ print(f" · {agent.name:<22} skill={agent.skill_id}")
37
+ print(f" endpoint={agent.endpoint_url}")
38
+
39
+ async def execute() -> VisualizationResult:
40
+ async with MathOrchestrator(mesh.registry) as orchestrator:
41
+ return await orchestrator.run(
42
+ request,
43
+ concept=concept,
44
+ on_trace=None if as_json else _print_trace,
45
+ )
46
+
47
+ result = asyncio.run(execute())
48
+
49
+ output_dir = Path(request.output_dir).expanduser().resolve()
50
+ token = uuid.uuid5(uuid.NAMESPACE_URL, result.session_id).hex[:10]
51
+ analysis_path = output_dir / f"analysis-{token}.json"
52
+ analysis_path.write_text(
53
+ json.dumps(result.model_dump(mode="json"), ensure_ascii=False, indent=2) + "\n",
54
+ encoding="utf-8",
55
+ )
56
+ if as_json:
57
+ print(json.dumps(result.model_dump(mode="json"), ensure_ascii=False, indent=2))
58
+ else:
59
+ _print_result(result, analysis_path)
60
+ return 0
61
+
62
+
63
+ def _print_trace(trace: AgentTrace) -> None:
64
+ print(
65
+ f"[AIP] {trace.operation:<8} {trace.agent:<22} "
66
+ f"state={trace.state:<14} {trace.elapsed_ms:>4} ms"
67
+ )
68
+
69
+
70
+ def _print_result(result: VisualizationResult, analysis_path: Path) -> None:
71
+ plot = result.plot
72
+ transformation = result.transformation
73
+ animation = result.animation
74
+ intuition = result.intuition
75
+
76
+ print(f"\n{BANNER}\n[1/4] Plotter Agent · 图像参数与数据\n{BANNER}")
77
+ print(f"标准表达式 : y = {plot.normalized_expression}")
78
+ print(
79
+ f"采样窗口 : x ∈ [{format_quantity(plot.x_min)}, {format_quantity(plot.x_max)}],"
80
+ f"{plot.sample_count} 个采样点"
81
+ )
82
+ print(
83
+ f"数值范围 : y ∈ [{plot.y_min:.6g}, {plot.y_max:.6g}],"
84
+ f"有效点 {plot.defined_count}/{plot.sample_count}"
85
+ )
86
+ print("预览数据点 :")
87
+ for point in plot.preview_points:
88
+ print(f" ({point.x:>10.6f}, {point.y:>10.6f})")
89
+ print(f"PNG 图像 : {plot.image_path}")
90
+ print(f"完整数据 : {plot.csv_path}")
91
+
92
+ print(f"\n{BANNER}\n[2/4] Transformation Agent · 变换解析\n{BANNER}")
93
+ print(f"参数标准式 : {transformation.canonical_form}")
94
+ for effect in transformation.effects:
95
+ print(f" · {effect.parameter} = {effect.value}")
96
+ print(f" {effect.effect}")
97
+ if transformation.frames:
98
+ print("动态关键帧 :")
99
+ for index, frame in enumerate(transformation.frames, start=1):
100
+ print(
101
+ f" {index}. {frame.label}: A={frame.a:g}, B={frame.b:g}, "
102
+ f"C={frame.c:g}, D={frame.d:g}"
103
+ )
104
+
105
+ print(f"\n{BANNER}\n[3/4] Plotter Agent · 动态可视化回派结果\n{BANNER}")
106
+ print(animation.description)
107
+ print(f"GIF 动画 : {animation.animation_path or '不适用(一般函数)'}")
108
+
109
+ print(f"\n{BANNER}\n[4/4] Intuition Agent · 通俗比喻与自测\n{BANNER}")
110
+ print(intuition.headline)
111
+ print(intuition.analogy)
112
+ for index, step in enumerate(intuition.steps, start=1):
113
+ print(f" {index}. {step}")
114
+ print(f"想一想 : {intuition.checkpoint}")
115
+ print(f"参考答案 : {intuition.answer}")
116
+
117
+ print(f"\n{BANNER}\n协作审计与产物\n{BANNER}")
118
+ print(f"Session : {result.session_id}")
119
+ print(f"SDK : acps-sdk {result.sdk_version}")
120
+ print(f"AIP 调度 : {len(result.traces)} 次,三个独立 Agent 服务均已完成协作")
121
+ print(f"结果 JSON : {analysis_path}")
122
+ print(f"总耗时 : {result.total_ms} ms")
123
+
124
+
125
+ __all__ = ["run_visualization"]
@@ -0,0 +1,67 @@
1
+ """ACP identities and Agent Capability Specification construction."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime, timezone
6
+
7
+ from acps_sdk.acs import (
8
+ AgentCapabilities,
9
+ AgentCapabilitySpec,
10
+ AgentEndPoint,
11
+ AgentProvider,
12
+ AgentSkill,
13
+ )
14
+ from acps_sdk.aic import is_valid_aic_format
15
+
16
+ from . import __version__
17
+
18
+ PROTOCOL_VERSION = "02.00"
19
+ AIC_PREFIX = "1.2.156.3088.1.1.34C2.478CE0"
20
+ LEADER_AIC = f"{AIC_PREFIX}.000300.0LDR"
21
+ PROJECT_URL = "https://pypi.org/project/acps-math-visualizer/"
22
+
23
+
24
+ def make_aic(instance_serial: str, checksum: str) -> str:
25
+ """Build and validate one ten-level ACP agent identity."""
26
+
27
+ aic = f"{AIC_PREFIX}.{instance_serial}.{checksum}"
28
+ if not is_valid_aic_format(aic):
29
+ raise ValueError(f"invalid AIC '{aic}'")
30
+ return aic
31
+
32
+
33
+ def build_capability_spec(
34
+ *,
35
+ aic: str,
36
+ name: str,
37
+ description: str,
38
+ skill: AgentSkill,
39
+ endpoint_url: str,
40
+ ) -> AgentCapabilitySpec:
41
+ """Create the ACS document advertised through ADP discovery."""
42
+
43
+ return AgentCapabilitySpec(
44
+ aic=aic,
45
+ active=True,
46
+ last_modified_time=datetime.now(timezone.utc).astimezone().isoformat(timespec="seconds"),
47
+ protocol_version=PROTOCOL_VERSION,
48
+ name=name,
49
+ description=description,
50
+ version=__version__,
51
+ provider=AgentProvider(
52
+ country_code="CN",
53
+ organization="ACPs Math Visualizer Labs",
54
+ department="Mathematical Cognition Engineering",
55
+ url=PROJECT_URL,
56
+ name="Math Visualizer Platform Team",
57
+ ),
58
+ security_schemes={},
59
+ end_points=[AgentEndPoint(url=endpoint_url, transport="JSONRPC")],
60
+ capabilities=AgentCapabilities(streaming=False, notification=False, message_queue=[]),
61
+ default_input_modes=["text/plain", "application/json"],
62
+ default_output_modes=["application/json"],
63
+ skills=[skill],
64
+ )
65
+
66
+
67
+ __all__ = ["LEADER_AIC", "PROTOCOL_VERSION", "build_capability_spec", "make_aic"]