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,333 @@
1
+ """Safe AST-based expression evaluation and sinusoidal parameter extraction."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ import math
7
+ import operator
8
+ import re
9
+ from collections.abc import Callable
10
+ from dataclasses import dataclass
11
+ from typing import TypeAlias
12
+
13
+ import numpy as np
14
+
15
+ Numeric: TypeAlias = float | np.ndarray
16
+ UnaryOperator: TypeAlias = Callable[[Numeric], Numeric]
17
+ BinaryOperator: TypeAlias = Callable[[Numeric, Numeric], Numeric]
18
+
19
+
20
+ class ExpressionError(ValueError):
21
+ """Raised when a mathematical expression is unsafe or cannot be sampled."""
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class SampledFunction:
26
+ """Numerical representation of a validated one-variable function."""
27
+
28
+ normalized_expression: str
29
+ x: np.ndarray
30
+ y: np.ndarray
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class SinusoidParameters:
35
+ """Parameters of ``A*sin(B*x+C)+D`` or its cosine equivalent."""
36
+
37
+ trig_function: str
38
+ a: float
39
+ b: float
40
+ c: float
41
+ d: float
42
+
43
+ @property
44
+ def amplitude(self) -> float:
45
+ return abs(self.a)
46
+
47
+ @property
48
+ def period(self) -> float:
49
+ return 2.0 * math.pi / abs(self.b)
50
+
51
+ @property
52
+ def phase_shift(self) -> float:
53
+ return -self.c / self.b
54
+
55
+
56
+ _FUNCTIONS: dict[str, Callable[..., Numeric]] = {
57
+ "sin": np.sin,
58
+ "cos": np.cos,
59
+ "tan": np.tan,
60
+ "arcsin": np.arcsin,
61
+ "arccos": np.arccos,
62
+ "arctan": np.arctan,
63
+ "sinh": np.sinh,
64
+ "cosh": np.cosh,
65
+ "tanh": np.tanh,
66
+ "exp": np.exp,
67
+ "log": np.log,
68
+ "sqrt": np.sqrt,
69
+ "abs": np.abs,
70
+ }
71
+ _CONSTANTS = {"pi": math.pi, "e": math.e}
72
+ _BINARY_OPERATORS: dict[type[ast.operator], BinaryOperator] = {
73
+ ast.Add: operator.add,
74
+ ast.Sub: operator.sub,
75
+ ast.Mult: operator.mul,
76
+ ast.Div: operator.truediv,
77
+ ast.Pow: np.power,
78
+ }
79
+ _UNARY_OPERATORS: dict[type[ast.unaryop], UnaryOperator] = {
80
+ ast.UAdd: operator.pos,
81
+ ast.USub: operator.neg,
82
+ }
83
+ _PREFIX_PATTERN = re.compile(r"^(?:y|f\s*\(\s*x\s*\))\s*=", re.IGNORECASE)
84
+
85
+
86
+ def normalize_expression(expression: str) -> str:
87
+ """Normalize common mathematical notation without executing user text."""
88
+
89
+ text = expression.strip()
90
+ text = _PREFIX_PATTERN.sub("", text).strip()
91
+ replacements = {
92
+ "π": "pi",
93
+ "−": "-",
94
+ "–": "-",
95
+ "×": "*",
96
+ "÷": "/",
97
+ "^": "**",
98
+ }
99
+ for source, target in replacements.items():
100
+ text = text.replace(source, target)
101
+ if not text:
102
+ raise ExpressionError("function expression must not be empty")
103
+ return text
104
+
105
+
106
+ def parse_expression(expression: str) -> tuple[str, ast.Expression]:
107
+ """Parse and structurally validate an expression using an AST allowlist."""
108
+
109
+ normalized = normalize_expression(expression)
110
+ try:
111
+ tree = ast.parse(normalized, mode="eval")
112
+ except SyntaxError as exc:
113
+ raise ExpressionError(f"invalid expression syntax: {exc.msg}") from exc
114
+ _validate_node(tree)
115
+ return normalized, tree
116
+
117
+
118
+ def sample_expression(
119
+ expression: str,
120
+ *,
121
+ x_min: float,
122
+ x_max: float,
123
+ samples: int,
124
+ ) -> SampledFunction:
125
+ """Evaluate an expression on a finite grid; undefined points become NaN."""
126
+
127
+ normalized, tree = parse_expression(expression)
128
+ x_values = np.linspace(x_min, x_max, samples, dtype=float)
129
+ with np.errstate(all="ignore"):
130
+ raw_values = _eval_node(tree.body, x_values)
131
+ y_values = np.asarray(raw_values, dtype=float)
132
+ if y_values.ndim == 0:
133
+ y_values = np.full_like(x_values, float(y_values))
134
+ if y_values.shape != x_values.shape:
135
+ raise ExpressionError("the expression must produce one scalar y for each x")
136
+ y_values = np.where(np.isfinite(y_values), y_values, np.nan)
137
+ if not np.isfinite(y_values).any():
138
+ raise ExpressionError("the expression has no finite values in the selected window")
139
+ return SampledFunction(normalized, x_values, y_values)
140
+
141
+
142
+ def analyze_sinusoid(expression: str) -> SinusoidParameters | None:
143
+ """Recognize affine scale/shift wrappers around one sine or cosine call."""
144
+
145
+ _normalized, tree = parse_expression(expression)
146
+ return _match_sinusoid(tree.body, scale=1.0, shift=0.0)
147
+
148
+
149
+ def format_quantity(value: float) -> str:
150
+ """Render simple multiples of pi exactly and other values compactly."""
151
+
152
+ if abs(value) < 1e-12:
153
+ return "0"
154
+ ratio = value / math.pi
155
+ for denominator in (1, 2, 3, 4, 6):
156
+ numerator = round(ratio * denominator)
157
+ if numerator and abs(ratio - numerator / denominator) < 1e-10:
158
+ sign = "-" if numerator < 0 else ""
159
+ magnitude = abs(numerator)
160
+ coefficient = "" if magnitude == 1 else str(magnitude)
161
+ denominator_text = "" if denominator == 1 else f"/{denominator}"
162
+ return f"{sign}{coefficient}π{denominator_text}"
163
+ return f"{value:.6g}"
164
+
165
+
166
+ def _validate_node(node: ast.AST) -> None:
167
+ if isinstance(node, ast.Expression):
168
+ _validate_node(node.body)
169
+ return
170
+ if isinstance(node, ast.Constant):
171
+ if isinstance(node.value, bool) or not isinstance(node.value, (int, float)):
172
+ raise ExpressionError("only real numeric constants are allowed")
173
+ return
174
+ if isinstance(node, ast.Name):
175
+ if node.id not in {"x", *_CONSTANTS}:
176
+ raise ExpressionError(f"unknown name '{node.id}'")
177
+ return
178
+ if isinstance(node, ast.BinOp):
179
+ if type(node.op) not in _BINARY_OPERATORS:
180
+ raise ExpressionError(f"operator '{type(node.op).__name__}' is not allowed")
181
+ _validate_node(node.left)
182
+ _validate_node(node.right)
183
+ return
184
+ if isinstance(node, ast.UnaryOp):
185
+ if type(node.op) not in _UNARY_OPERATORS:
186
+ raise ExpressionError(f"operator '{type(node.op).__name__}' is not allowed")
187
+ _validate_node(node.operand)
188
+ return
189
+ if isinstance(node, ast.Call):
190
+ if not isinstance(node.func, ast.Name) or node.func.id not in _FUNCTIONS:
191
+ raise ExpressionError("only approved mathematical functions may be called")
192
+ if len(node.args) != 1 or node.keywords:
193
+ raise ExpressionError(f"{node.func.id} requires exactly one positional argument")
194
+ _validate_node(node.args[0])
195
+ return
196
+ raise ExpressionError(f"syntax element '{type(node).__name__}' is not allowed")
197
+
198
+
199
+ def _eval_node(node: ast.AST, x: np.ndarray | None) -> Numeric:
200
+ if isinstance(node, ast.Constant):
201
+ return float(node.value)
202
+ if isinstance(node, ast.Name):
203
+ if node.id == "x":
204
+ if x is None:
205
+ raise ExpressionError("x is not constant")
206
+ return x
207
+ return _CONSTANTS[node.id]
208
+ if isinstance(node, ast.UnaryOp):
209
+ operand = _eval_node(node.operand, x)
210
+ return _UNARY_OPERATORS[type(node.op)](operand)
211
+ if isinstance(node, ast.BinOp):
212
+ left = _eval_node(node.left, x)
213
+ right = _eval_node(node.right, x)
214
+ if isinstance(node.op, ast.Pow) and isinstance(right, (float, np.floating)):
215
+ if abs(float(right)) > 8:
216
+ raise ExpressionError("constant exponents must be between -8 and 8")
217
+ return _BINARY_OPERATORS[type(node.op)](left, right)
218
+ if isinstance(node, ast.Call):
219
+ function_name = node.func.id
220
+ argument = _eval_node(node.args[0], x)
221
+ return _FUNCTIONS[function_name](argument)
222
+ raise ExpressionError(f"cannot evaluate '{type(node).__name__}'")
223
+
224
+
225
+ def _constant(node: ast.AST) -> float | None:
226
+ if _contains_x(node):
227
+ return None
228
+ try:
229
+ value = _eval_node(node, None)
230
+ result = float(np.asarray(value))
231
+ except (ExpressionError, TypeError, ValueError, OverflowError):
232
+ return None
233
+ return result if math.isfinite(result) else None
234
+
235
+
236
+ def _contains_x(node: ast.AST) -> bool:
237
+ return any(isinstance(child, ast.Name) and child.id == "x" for child in ast.walk(node))
238
+
239
+
240
+ def _linear(node: ast.AST) -> tuple[float, float] | None:
241
+ constant = _constant(node)
242
+ if constant is not None:
243
+ return 0.0, constant
244
+ if isinstance(node, ast.Name) and node.id == "x":
245
+ return 1.0, 0.0
246
+ if isinstance(node, ast.UnaryOp):
247
+ coefficients = _linear(node.operand)
248
+ if coefficients is None:
249
+ return None
250
+ sign = 1.0 if isinstance(node.op, ast.UAdd) else -1.0
251
+ return sign * coefficients[0], sign * coefficients[1]
252
+ if isinstance(node, ast.BinOp) and isinstance(node.op, (ast.Add, ast.Sub)):
253
+ left = _linear(node.left)
254
+ right = _linear(node.right)
255
+ if left is None or right is None:
256
+ return None
257
+ sign = 1.0 if isinstance(node.op, ast.Add) else -1.0
258
+ return left[0] + sign * right[0], left[1] + sign * right[1]
259
+ if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mult):
260
+ left_constant = _constant(node.left)
261
+ right_constant = _constant(node.right)
262
+ if left_constant is not None:
263
+ right = _linear(node.right)
264
+ return None if right is None else (left_constant * right[0], left_constant * right[1])
265
+ if right_constant is not None:
266
+ left = _linear(node.left)
267
+ return None if left is None else (right_constant * left[0], right_constant * left[1])
268
+ if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Div):
269
+ denominator = _constant(node.right)
270
+ numerator = _linear(node.left)
271
+ if denominator not in (None, 0.0) and numerator is not None:
272
+ return numerator[0] / denominator, numerator[1] / denominator
273
+ return None
274
+
275
+
276
+ def _match_sinusoid(
277
+ node: ast.AST,
278
+ *,
279
+ scale: float,
280
+ shift: float,
281
+ ) -> SinusoidParameters | None:
282
+ if (
283
+ isinstance(node, ast.Call)
284
+ and isinstance(node.func, ast.Name)
285
+ and node.func.id in {"sin", "cos"}
286
+ ):
287
+ coefficients = _linear(node.args[0])
288
+ if coefficients is None or abs(coefficients[0]) < 1e-12:
289
+ return None
290
+ return SinusoidParameters(
291
+ trig_function=node.func.id,
292
+ a=scale,
293
+ b=coefficients[0],
294
+ c=coefficients[1],
295
+ d=shift,
296
+ )
297
+ if isinstance(node, ast.UnaryOp):
298
+ sign = 1.0 if isinstance(node.op, ast.UAdd) else -1.0
299
+ return _match_sinusoid(node.operand, scale=sign * scale, shift=shift)
300
+ if not isinstance(node, ast.BinOp):
301
+ return None
302
+ left_constant = _constant(node.left)
303
+ right_constant = _constant(node.right)
304
+ if isinstance(node.op, ast.Mult):
305
+ if left_constant is not None:
306
+ return _match_sinusoid(node.right, scale=scale * left_constant, shift=shift)
307
+ if right_constant is not None:
308
+ return _match_sinusoid(node.left, scale=scale * right_constant, shift=shift)
309
+ if isinstance(node.op, ast.Div) and right_constant not in (None, 0.0):
310
+ return _match_sinusoid(node.left, scale=scale / right_constant, shift=shift)
311
+ if isinstance(node.op, ast.Add):
312
+ if left_constant is not None:
313
+ return _match_sinusoid(node.right, scale=scale, shift=shift + left_constant)
314
+ if right_constant is not None:
315
+ return _match_sinusoid(node.left, scale=scale, shift=shift + right_constant)
316
+ if isinstance(node.op, ast.Sub):
317
+ if right_constant is not None:
318
+ return _match_sinusoid(node.left, scale=scale, shift=shift - right_constant)
319
+ if left_constant is not None:
320
+ return _match_sinusoid(node.right, scale=-scale, shift=shift + left_constant)
321
+ return None
322
+
323
+
324
+ __all__ = [
325
+ "ExpressionError",
326
+ "SampledFunction",
327
+ "SinusoidParameters",
328
+ "analyze_sinusoid",
329
+ "format_quantity",
330
+ "normalize_expression",
331
+ "parse_expression",
332
+ "sample_expression",
333
+ ]
@@ -0,0 +1,55 @@
1
+ """Local mesh hosting three independent AIP v2 partner services."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .agents import IntuitionAgent, PlotterAgent, TransformationAgent
6
+ from .agents.base import AipAgent
7
+ from .identity import make_aic
8
+ from .registry import AgentRegistry
9
+ from .runtime import AgentServer
10
+
11
+ _AGENT_SPECS: tuple[tuple[type[AipAgent], str, str], ...] = (
12
+ (PlotterAgent, "000301", "0PLT"),
13
+ (TransformationAgent, "000302", "0TRN"),
14
+ (IntuitionAgent, "000303", "0INT"),
15
+ )
16
+
17
+
18
+ class LocalAgentMesh:
19
+ """Start, advertise, and stop the complete visualization team."""
20
+
21
+ def __init__(self) -> None:
22
+ self.registry = AgentRegistry()
23
+ self.agents: list[AipAgent] = []
24
+ self._servers: list[AgentServer] = []
25
+
26
+ def __enter__(self) -> LocalAgentMesh:
27
+ self.start()
28
+ return self
29
+
30
+ def __exit__(self, exc_type: object, exc: object, traceback: object) -> None:
31
+ self.stop()
32
+
33
+ def start(self) -> None:
34
+ if self._servers:
35
+ return
36
+ try:
37
+ for agent_class, serial, checksum in _AGENT_SPECS:
38
+ agent = agent_class(make_aic(serial, checksum))
39
+ server = AgentServer(agent)
40
+ server.start()
41
+ self.registry.publish(agent.capability_spec)
42
+ self.agents.append(agent)
43
+ self._servers.append(server)
44
+ except Exception:
45
+ self.stop()
46
+ raise
47
+
48
+ def stop(self) -> None:
49
+ for server in reversed(self._servers):
50
+ server.stop()
51
+ self._servers.clear()
52
+ self.agents.clear()
53
+
54
+
55
+ __all__ = ["LocalAgentMesh"]
@@ -0,0 +1,214 @@
1
+ """Typed application contracts transported inside AIP v2 products."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from enum import Enum
6
+ from typing import Any
7
+
8
+ from pydantic import BaseModel, Field, model_validator
9
+
10
+
11
+ class MessageKind(str, Enum):
12
+ """Application messages carried by SDK ``TextDataItem`` objects."""
13
+
14
+ PLOT_REQUEST = "PLOT_REQUEST"
15
+ TRANSFORM_REQUEST = "TRANSFORM_REQUEST"
16
+ ANIMATION_REQUEST = "ANIMATION_REQUEST"
17
+ INTUITION_REQUEST = "INTUITION_REQUEST"
18
+
19
+
20
+ class IntuitionConcept(str, Enum):
21
+ """Concept that the Intuition Agent should make accessible."""
22
+
23
+ AUTO = "auto"
24
+ TRANSFORMATION = "transformation"
25
+ LIMIT = "limit"
26
+ DERIVATIVE = "derivative"
27
+
28
+
29
+ class FunctionRequest(BaseModel):
30
+ """Validated user input shared through the collaboration pipeline."""
31
+
32
+ expression: str = Field(min_length=1, max_length=200)
33
+ x_min: float = Field(default=-6.283185307179586, allow_inf_nan=False)
34
+ x_max: float = Field(default=6.283185307179586, allow_inf_nan=False)
35
+ samples: int = Field(default=161, ge=40, le=1001)
36
+ output_dir: str = Field(default="output", min_length=1, max_length=500)
37
+
38
+ @model_validator(mode="after")
39
+ def validate_window(self) -> FunctionRequest:
40
+ if self.x_min >= self.x_max:
41
+ raise ValueError("x_min must be smaller than x_max")
42
+ if not self.output_dir.strip():
43
+ raise ValueError("output_dir must not be blank")
44
+ return self
45
+
46
+
47
+ class WireMessage(BaseModel):
48
+ """Correlated JSON envelope used by every AIP command."""
49
+
50
+ kind: MessageKind
51
+ session_id: str = Field(min_length=1)
52
+ task_id: str = Field(min_length=1)
53
+ payload: dict[str, Any]
54
+
55
+
56
+ class ProductMeta(BaseModel):
57
+ """Identity and correlation fields returned by every partner."""
58
+
59
+ session_id: str = Field(min_length=1)
60
+ task_id: str = Field(min_length=1)
61
+ agent: str = Field(min_length=1)
62
+ terminal: bool = True
63
+
64
+
65
+ class PlotPoint(BaseModel):
66
+ """One finite preview point; the CSV artifact contains the full sample."""
67
+
68
+ x: float = Field(allow_inf_nan=False)
69
+ y: float = Field(allow_inf_nan=False)
70
+
71
+
72
+ class PlotProduct(ProductMeta):
73
+ """Numerical curve and static artifacts produced by the Plotter Agent."""
74
+
75
+ terminal: bool = False
76
+ expression: str
77
+ normalized_expression: str
78
+ x_min: float
79
+ x_max: float
80
+ sample_count: int = Field(ge=1)
81
+ defined_count: int = Field(ge=1)
82
+ y_min: float = Field(allow_inf_nan=False)
83
+ y_max: float = Field(allow_inf_nan=False)
84
+ preview_points: list[PlotPoint] = Field(min_length=1, max_length=9)
85
+ image_path: str
86
+ csv_path: str
87
+
88
+
89
+ class AnimationFrame(BaseModel):
90
+ """One mathematical keyframe in ``A*trig(B*x+C)+D`` form."""
91
+
92
+ stage: str
93
+ label: str
94
+ detail: str
95
+ a: float = Field(allow_inf_nan=False)
96
+ b: float = Field(allow_inf_nan=False)
97
+ c: float = Field(allow_inf_nan=False)
98
+ d: float = Field(allow_inf_nan=False)
99
+
100
+
101
+ class TransformationRequest(BaseModel):
102
+ """The Plotter product is the input evidence for transformation analysis."""
103
+
104
+ plot: PlotProduct
105
+
106
+
107
+ class ParameterEffect(BaseModel):
108
+ """Human-readable effect of one formula parameter."""
109
+
110
+ parameter: str
111
+ value: str
112
+ effect: str
113
+
114
+
115
+ class TransformationProduct(ProductMeta):
116
+ """Geometric interpretation and an executable animation plan."""
117
+
118
+ function_family: str
119
+ canonical_form: str
120
+ is_sinusoidal: bool
121
+ trig_function: str | None = None
122
+ amplitude: float | None = Field(default=None, allow_inf_nan=False)
123
+ angular_frequency: float | None = Field(default=None, allow_inf_nan=False)
124
+ period: float | None = Field(default=None, allow_inf_nan=False)
125
+ phase_shift: float | None = Field(default=None, allow_inf_nan=False)
126
+ vertical_shift: float | None = Field(default=None, allow_inf_nan=False)
127
+ effects: list[ParameterEffect] = Field(min_length=1)
128
+ steps: list[str] = Field(min_length=1)
129
+ frames: list[AnimationFrame] = Field(default_factory=list)
130
+
131
+
132
+ class AnimationRequest(BaseModel):
133
+ """Transformation output sent back to the original Plotter task."""
134
+
135
+ trig_function: str | None
136
+ frames: list[AnimationFrame] = Field(default_factory=list)
137
+
138
+
139
+ class AnimationProduct(ProductMeta):
140
+ """Animated GIF generated after the Plotter receives a transform plan."""
141
+
142
+ animation_path: str | None
143
+ frame_count: int = Field(ge=0)
144
+ description: str
145
+
146
+
147
+ class IntuitionRequest(BaseModel):
148
+ """All upstream evidence needed for a grounded, non-generic explanation."""
149
+
150
+ plot: PlotProduct
151
+ transformation: TransformationProduct
152
+ animation: AnimationProduct
153
+ concept: IntuitionConcept = IntuitionConcept.AUTO
154
+
155
+
156
+ class IntuitionProduct(ProductMeta):
157
+ """A memorable analogy plus a small retrieval-practice check."""
158
+
159
+ concept: str
160
+ headline: str
161
+ analogy: str
162
+ steps: list[str] = Field(min_length=1)
163
+ checkpoint: str
164
+ answer: str
165
+
166
+
167
+ class AgentTrace(BaseModel):
168
+ """Auditable SDK-level dispatch record."""
169
+
170
+ agent: str
171
+ aic: str
172
+ skill_id: str
173
+ task_id: str
174
+ operation: str
175
+ state: str
176
+ elapsed_ms: int = Field(ge=0)
177
+ summary: str
178
+
179
+
180
+ class VisualizationResult(BaseModel):
181
+ """Final fan-in result returned to the CLI or another application."""
182
+
183
+ session_id: str
184
+ project_version: str
185
+ sdk_version: str
186
+ generated_at: str
187
+ request: FunctionRequest
188
+ plot: PlotProduct
189
+ transformation: TransformationProduct
190
+ animation: AnimationProduct
191
+ intuition: IntuitionProduct
192
+ traces: list[AgentTrace] = Field(min_length=4)
193
+ total_ms: int = Field(ge=0)
194
+
195
+
196
+ __all__ = [
197
+ "AgentTrace",
198
+ "AnimationFrame",
199
+ "AnimationProduct",
200
+ "AnimationRequest",
201
+ "FunctionRequest",
202
+ "IntuitionConcept",
203
+ "IntuitionProduct",
204
+ "IntuitionRequest",
205
+ "MessageKind",
206
+ "ParameterEffect",
207
+ "PlotPoint",
208
+ "PlotProduct",
209
+ "ProductMeta",
210
+ "TransformationProduct",
211
+ "TransformationRequest",
212
+ "VisualizationResult",
213
+ "WireMessage",
214
+ ]