@yahyahammad/venastine 0.3.8 → 0.3.10
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.
- package/.env.example +19 -19
- package/CONFIG_ARCHITECTURE.md +2139 -2002
- package/LICENSE +201 -201
- package/README.md +1043 -1034
- package/agents/builtin/compactor.md +75 -75
- package/agents/builtin/explore.md +77 -77
- package/agents/builtin/pipeline-reviewer.md +100 -100
- package/agents/builtin/plan.md +106 -106
- package/agents/builtin/review.md +74 -74
- package/agents/manager.py +261 -261
- package/agents/subagent_tool.py +472 -472
- package/agents/tui_commands.py +238 -146
- package/bin/venastine.mjs +584 -528
- package/bin/venastine.py +73 -71
- package/cli_commands.py +848 -835
- package/config.yaml +64 -0
- package/config_edit.py +1301 -1301
- package/config_schema.py +987 -966
- package/config_update.py +749 -749
- package/core/agent_activity.py +256 -256
- package/core/ansi.py +452 -452
- package/core/approval.py +137 -137
- package/core/call_view.py +364 -364
- package/core/cancel.py +121 -121
- package/core/chatgpt_auth.py +747 -747
- package/core/claims_view.py +107 -107
- package/core/client.py +2756 -2715
- package/core/commands.py +464 -454
- package/core/compaction.py +1735 -1735
- package/core/config_loader.py +1982 -1982
- package/core/connect.py +686 -686
- package/core/events.py +123 -123
- package/core/file_mentions.py +280 -280
- package/core/interaction.py +411 -411
- package/core/loop.py +2566 -2566
- package/core/memory.py +482 -482
- package/core/pipeline_models.py +190 -190
- package/core/provider_errors.py +274 -234
- package/core/reasoning/authorization.py +130 -130
- package/core/reasoning/base.py +219 -219
- package/core/reasoning/confidence_scoring.py +484 -484
- package/core/reasoning/events.py +149 -149
- package/core/reasoning/orchestrator.py +1561 -1561
- package/core/reasoning/output_writer.py +345 -345
- package/core/reasoning/payload_validation.py +524 -524
- package/core/reasoning/pipeline_storage.py +427 -427
- package/core/reasoning/scholar.py +467 -458
- package/core/reasoning/source_corpus.py +433 -433
- package/core/reasoning/source_scoring.py +855 -855
- package/core/replay.py +315 -315
- package/core/shell_sessions.py +1553 -1553
- package/credentials.py +307 -307
- package/database.py +333 -333
- package/docs/PRIVACY.md +78 -78
- package/docs/SECURITY.md +114 -108
- package/docs/THIRD_PARTY_NOTICES.md +148 -148
- package/env_secrets.py +118 -118
- package/json_store.py +343 -343
- package/logging_setup.py +295 -295
- package/main.py +3433 -3433
- package/mcp_client/client.py +780 -733
- package/mcp_client/config.py +484 -484
- package/mcp_client/registration.py +343 -343
- package/memories/manager.py +147 -147
- package/memories/tui_commands.py +319 -239
- package/package.json +303 -303
- package/project_init/config_files.py +282 -282
- package/project_init/generator.py +728 -728
- package/project_init/manifest.py +418 -418
- package/project_init/tui_commands.py +147 -147
- package/prompts/critic_pass.md +24 -24
- package/prompts/revalidate.md +25 -25
- package/prompts/revise.md +17 -17
- package/prompts/source_grounding.md +66 -66
- package/prompts/system_prompts.py +316 -316
- package/providers.json.example +94 -94
- package/pyproject.toml +149 -149
- package/requirements.txt +314 -295
- package/safety/policy_enforcement.py +1082 -1082
- package/security/askpass.py +419 -419
- package/security/capability.py +207 -207
- package/security/confine.py +484 -484
- package/security/hosted.py +182 -182
- package/security/permissions.py +237 -237
- package/security/protected_paths.py +501 -501
- package/security/sandbox.py +4108 -4108
- package/skills/builtin/math/formal-specification.md +67 -67
- package/skills/builtin/math/numerical-methods.md +66 -66
- package/skills/builtin/research/experiment-design.md +62 -62
- package/skills/builtin/research/reproducibility.md +55 -55
- package/skills/builtin/research/source-evaluation.md +70 -70
- package/skills/builtin/research/statistical-inference.md +63 -63
- package/skills/builtin/research/technical-writing.md +59 -59
- package/skills/builtin/software/code-review.md +61 -61
- package/skills/builtin/software/debugging.md +61 -61
- package/skills/builtin/software/test-design.md +67 -67
- package/skills/tui_commands.py +110 -110
- package/storage.py +1338 -1338
- package/tools/base.py +465 -465
- package/tools/builtin/_math_common.py +667 -667
- package/tools/builtin/_net_common.py +1145 -267
- package/tools/builtin/_page_text.py +490 -0
- package/tools/builtin/_pdf_text.py +113 -0
- package/tools/builtin/arxiv.py +685 -681
- package/tools/builtin/fetch_url.py +639 -371
- package/tools/builtin/file_ops.py +720 -720
- package/tools/builtin/geometry.py +184 -184
- package/tools/builtin/load_skill.py +76 -76
- package/tools/builtin/pin.py +227 -227
- package/tools/builtin/probability_stats.py +224 -224
- package/tools/builtin/project_docs.py +464 -464
- package/tools/builtin/remember.py +175 -175
- package/tools/builtin/shell.py +980 -980
- package/tools/builtin/todo.py +149 -149
- package/tools/builtin/web_search.py +402 -328
- package/tools/context.py +159 -159
- package/tools/isolation.py +387 -387
- package/tools/registry.py +1252 -1242
- package/tui/app.py +8372 -8307
- package/tui/app.tcss +754 -739
- package/tui/commands.py +26 -26
- package/tui/diffs.py +286 -286
- package/tui/history.py +128 -128
- package/tui/hosted_driver.py +102 -102
- package/tui/markdown.py +1329 -1329
- package/tui/meters.py +364 -364
- package/tui/ravens.py +146 -146
- package/tui/screens.py +1255 -1197
- package/tui/themes.py +599 -599
- package/tui/widgets.py +3861 -3796
|
@@ -1,224 +1,224 @@
|
|
|
1
|
-
"""
|
|
2
|
-
tools/builtin/probability_stats.py
|
|
3
|
-
|
|
4
|
-
Descriptive statistics on raw data (using the stdlib `statistics` module
|
|
5
|
-
-- deterministic, no need for sympy here) and probability distributions
|
|
6
|
-
(using sympy.stats, kept exact/symbolic where possible).
|
|
7
|
-
|
|
8
|
-
Named probability_stats rather than statistics.py specifically to avoid
|
|
9
|
-
any reader confusion with the stdlib module of the same name, even though
|
|
10
|
-
Python 3's absolute-import default would resolve `import statistics`
|
|
11
|
-
correctly regardless.
|
|
12
|
-
"""
|
|
13
|
-
|
|
14
|
-
from __future__ import annotations
|
|
15
|
-
|
|
16
|
-
import statistics as pystats
|
|
17
|
-
from typing import Literal, Optional
|
|
18
|
-
|
|
19
|
-
import sympy
|
|
20
|
-
import sympy.stats as sstats
|
|
21
|
-
from pydantic import BaseModel, Field
|
|
22
|
-
|
|
23
|
-
from tools.builtin._math_common import MathParseError, parse_params
|
|
24
|
-
|
|
25
|
-
_OPERATIONS = Literal["describe", "distribution_stats", "distribution_pdf", "distribution_cdf"]
|
|
26
|
-
_DISTRIBUTIONS = Literal["normal", "binomial", "poisson", "uniform", "exponential"]
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
class ProbabilityStatsParams(BaseModel):
|
|
30
|
-
operation: _OPERATIONS = Field(..., description="Which operation to perform")
|
|
31
|
-
data: Optional[list[float]] = Field(None, description="Dataset, for the 'describe' operation")
|
|
32
|
-
distribution: Optional[_DISTRIBUTIONS] = Field(
|
|
33
|
-
None, description="Distribution family, for distribution_* operations"
|
|
34
|
-
)
|
|
35
|
-
distribution_params: Optional[dict[str, float]] = Field(
|
|
36
|
-
None,
|
|
37
|
-
description=(
|
|
38
|
-
"Parameters for the chosen distribution: normal={mu, sigma}, "
|
|
39
|
-
"binomial={n, p}, poisson={lambda}, uniform={a, b}, "
|
|
40
|
-
"exponential={rate}"
|
|
41
|
-
),
|
|
42
|
-
)
|
|
43
|
-
x: Optional[float] = Field(None, description="Point to evaluate pdf/cdf at")
|
|
44
|
-
evaluate: bool = Field(False, description="If true, return numeric approximation (evalf) instead of exact symbolic form (e.g. 0.84... instead of erf(...)). Default false keeps exact symbolic.")
|
|
45
|
-
precision: int = Field(15, ge=1, le=50, description="Significant digits when evaluate is true")
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
TOOL_SCHEMA = {
|
|
49
|
-
"name": "probability_stats",
|
|
50
|
-
"description": (
|
|
51
|
-
"Compute descriptive statistics on a dataset (mean, median, "
|
|
52
|
-
"variance, stdev, min, max), or work with probability "
|
|
53
|
-
"distributions (normal, binomial, poisson, uniform, exponential): "
|
|
54
|
-
"expected value, variance, pdf at a point, or cdf at a point. "
|
|
55
|
-
"Results are exact symbolic expressions (e.g. erf(...), sqrt(pi)) unless 'evaluate' is true, "
|
|
56
|
-
"which returns a numeric approximation with 'precision' digits. When distribution parameters "
|
|
57
|
-
"are omitted, defaults are used (normal mu=0 sigma=1, uniform a=0 b=1, exponential rate=1) and a "
|
|
58
|
-
"'warnings' field explains what was defaulted."
|
|
59
|
-
),
|
|
60
|
-
"input_schema": ProbabilityStatsParams.model_json_schema(),
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
def _build_distribution_with_warnings(name: str, dp_orig: Optional[dict]):
|
|
65
|
-
"""Build distribution and collect warnings for defaulted params.
|
|
66
|
-
|
|
67
|
-
Returns (dist, warnings). Warnings is a list of strings for each param
|
|
68
|
-
that fell back to a default, per decision 2 (keep forgiving but explain).
|
|
69
|
-
Binomial/poisson have no defaults — missing required keys become a
|
|
70
|
-
friendly error at the caller, not a warning.
|
|
71
|
-
|
|
72
|
-
THE ONE BUILDER (#208). A warning-free twin, `_build_distribution`, sat
|
|
73
|
-
above this with no caller and the same five distributions and defaults,
|
|
74
|
-
so a change to one would have left the other silently wrong. It is
|
|
75
|
-
deleted; a caller that wants no warnings takes `[0]` of this.
|
|
76
|
-
"""
|
|
77
|
-
dp = dp_orig or {}
|
|
78
|
-
warnings: list[str] = []
|
|
79
|
-
if name == "normal":
|
|
80
|
-
if "mu" not in dp:
|
|
81
|
-
warnings.append("mu not supplied - defaulted to 0")
|
|
82
|
-
if "sigma" not in dp:
|
|
83
|
-
warnings.append("sigma not supplied - defaulted to 1")
|
|
84
|
-
return sstats.Normal("X", dp.get("mu", 0), dp.get("sigma", 1)), warnings
|
|
85
|
-
if name == "uniform":
|
|
86
|
-
if "a" not in dp:
|
|
87
|
-
warnings.append("a not supplied - defaulted to 0")
|
|
88
|
-
if "b" not in dp:
|
|
89
|
-
warnings.append("b not supplied - defaulted to 1")
|
|
90
|
-
return sstats.Uniform("X", dp.get("a", 0), dp.get("b", 1)), warnings
|
|
91
|
-
if name == "exponential":
|
|
92
|
-
if "rate" not in dp:
|
|
93
|
-
warnings.append("rate not supplied - defaulted to 1")
|
|
94
|
-
return sstats.Exponential("X", dp.get("rate", 1)), warnings
|
|
95
|
-
if name == "binomial":
|
|
96
|
-
# No defaults — caller validates presence
|
|
97
|
-
return sstats.Binomial("X", int(dp["n"]), dp["p"]), warnings
|
|
98
|
-
if name == "poisson":
|
|
99
|
-
return sstats.Poisson("X", dp["lambda"]), warnings
|
|
100
|
-
raise ValueError(f"Unsupported distribution: {name}")
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
def _maybe_evalf(value, do_eval: bool, precision: int):
|
|
104
|
-
if not do_eval or value is None:
|
|
105
|
-
return value
|
|
106
|
-
try:
|
|
107
|
-
if hasattr(value, "evalf"):
|
|
108
|
-
return value.evalf(precision)
|
|
109
|
-
except Exception:
|
|
110
|
-
pass # no numeric form; the exact value is still a correct answer
|
|
111
|
-
return value
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
def _cdf_at(dist, x):
|
|
115
|
-
"""Evaluate CDF at x, handling discrete binomial's dict return."""
|
|
116
|
-
try:
|
|
117
|
-
return sstats.cdf(dist)(x)
|
|
118
|
-
except TypeError as e:
|
|
119
|
-
if "'dict' object is not callable" in str(e):
|
|
120
|
-
# Binomial (and some discretes) return a dict table via two-arg form
|
|
121
|
-
table = sstats.cdf(dist, x)
|
|
122
|
-
if isinstance(table, dict):
|
|
123
|
-
import math
|
|
124
|
-
|
|
125
|
-
try:
|
|
126
|
-
# Discrete CDF at x is sum up to floor(x)
|
|
127
|
-
key = int(math.floor(float(x)))
|
|
128
|
-
except Exception:
|
|
129
|
-
return table
|
|
130
|
-
if key in table:
|
|
131
|
-
return table[key]
|
|
132
|
-
# find greatest key <= x
|
|
133
|
-
sorted_keys = sorted(table.keys())
|
|
134
|
-
candidate = None
|
|
135
|
-
for k in sorted_keys:
|
|
136
|
-
if k <= key:
|
|
137
|
-
candidate = table[k]
|
|
138
|
-
else:
|
|
139
|
-
break
|
|
140
|
-
if candidate is not None:
|
|
141
|
-
return candidate
|
|
142
|
-
if key < sorted_keys[0]:
|
|
143
|
-
return sympy.Integer(0)
|
|
144
|
-
return sympy.Integer(1)
|
|
145
|
-
return table
|
|
146
|
-
raise
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
def run(params: dict) -> dict:
|
|
150
|
-
try:
|
|
151
|
-
parsed = parse_params(ProbabilityStatsParams, params)
|
|
152
|
-
except MathParseError as e:
|
|
153
|
-
return {"error": str(e)}
|
|
154
|
-
|
|
155
|
-
try:
|
|
156
|
-
if parsed.operation == "describe":
|
|
157
|
-
data = parsed.data
|
|
158
|
-
if not data:
|
|
159
|
-
return {"error": "data is required for 'describe'"}
|
|
160
|
-
result = {
|
|
161
|
-
"mean": pystats.mean(data),
|
|
162
|
-
"median": pystats.median(data),
|
|
163
|
-
"stdev": pystats.stdev(data) if len(data) > 1 else 0.0,
|
|
164
|
-
"variance": pystats.variance(data) if len(data) > 1 else 0.0,
|
|
165
|
-
"min": min(data),
|
|
166
|
-
"max": max(data),
|
|
167
|
-
"n": len(data),
|
|
168
|
-
}
|
|
169
|
-
return {"result": result, "operation": parsed.operation}
|
|
170
|
-
|
|
171
|
-
if not parsed.distribution:
|
|
172
|
-
return {"error": "distribution is required for this operation"}
|
|
173
|
-
|
|
174
|
-
dp = parsed.distribution_params or {}
|
|
175
|
-
# Friendly validation for distributions with no defaults
|
|
176
|
-
if parsed.distribution == "binomial":
|
|
177
|
-
if "n" not in dp or "p" not in dp:
|
|
178
|
-
return {"error": "binomial requires 'n' (number of trials) and 'p' (success probability) in distribution_params."}
|
|
179
|
-
if parsed.distribution == "poisson":
|
|
180
|
-
if "lambda" not in dp:
|
|
181
|
-
return {"error": "poisson requires 'lambda' in distribution_params."}
|
|
182
|
-
|
|
183
|
-
dist, warnings = _build_distribution_with_warnings(parsed.distribution, parsed.distribution_params)
|
|
184
|
-
|
|
185
|
-
if parsed.operation == "distribution_stats":
|
|
186
|
-
mean_v = _maybe_evalf(sstats.E(dist), parsed.evaluate, parsed.precision)
|
|
187
|
-
var_v = _maybe_evalf(sstats.variance(dist), parsed.evaluate, parsed.precision)
|
|
188
|
-
# std is sqrt(var) — eval the sqrt when numeric
|
|
189
|
-
raw_var = sstats.variance(dist)
|
|
190
|
-
std_v = _maybe_evalf(sympy.sqrt(raw_var), parsed.evaluate, parsed.precision)
|
|
191
|
-
result = {
|
|
192
|
-
"mean": str(mean_v),
|
|
193
|
-
"variance": str(var_v),
|
|
194
|
-
"std": str(std_v),
|
|
195
|
-
}
|
|
196
|
-
elif parsed.operation == "distribution_pdf":
|
|
197
|
-
if parsed.x is None:
|
|
198
|
-
return {"error": "x is required for distribution_pdf"}
|
|
199
|
-
x_arg = parsed.x
|
|
200
|
-
# Discrete distributions expect int; float 5.0 should be treated as 5
|
|
201
|
-
if parsed.distribution in ("binomial", "poisson") and isinstance(x_arg, float) and x_arg.is_integer():
|
|
202
|
-
x_arg = int(x_arg)
|
|
203
|
-
raw = sstats.density(dist)(x_arg)
|
|
204
|
-
val = _maybe_evalf(raw, parsed.evaluate, parsed.precision)
|
|
205
|
-
result = str(val)
|
|
206
|
-
elif parsed.operation == "distribution_cdf":
|
|
207
|
-
if parsed.x is None:
|
|
208
|
-
return {"error": "x is required for distribution_cdf"}
|
|
209
|
-
x_arg = parsed.x
|
|
210
|
-
if parsed.distribution in ("binomial", "poisson") and isinstance(x_arg, float) and x_arg.is_integer():
|
|
211
|
-
x_arg = int(x_arg)
|
|
212
|
-
raw = _cdf_at(dist, x_arg)
|
|
213
|
-
val = _maybe_evalf(raw, parsed.evaluate, parsed.precision)
|
|
214
|
-
result = str(val)
|
|
215
|
-
else:
|
|
216
|
-
return {"error": f"Unknown operation: {parsed.operation}"}
|
|
217
|
-
|
|
218
|
-
except Exception as e:
|
|
219
|
-
return {"error": f"Computation failed: {e}"}
|
|
220
|
-
|
|
221
|
-
out: dict = {"result": result, "operation": parsed.operation}
|
|
222
|
-
if warnings:
|
|
223
|
-
out["warnings"] = warnings
|
|
224
|
-
return out
|
|
1
|
+
"""
|
|
2
|
+
tools/builtin/probability_stats.py
|
|
3
|
+
|
|
4
|
+
Descriptive statistics on raw data (using the stdlib `statistics` module
|
|
5
|
+
-- deterministic, no need for sympy here) and probability distributions
|
|
6
|
+
(using sympy.stats, kept exact/symbolic where possible).
|
|
7
|
+
|
|
8
|
+
Named probability_stats rather than statistics.py specifically to avoid
|
|
9
|
+
any reader confusion with the stdlib module of the same name, even though
|
|
10
|
+
Python 3's absolute-import default would resolve `import statistics`
|
|
11
|
+
correctly regardless.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import statistics as pystats
|
|
17
|
+
from typing import Literal, Optional
|
|
18
|
+
|
|
19
|
+
import sympy
|
|
20
|
+
import sympy.stats as sstats
|
|
21
|
+
from pydantic import BaseModel, Field
|
|
22
|
+
|
|
23
|
+
from tools.builtin._math_common import MathParseError, parse_params
|
|
24
|
+
|
|
25
|
+
_OPERATIONS = Literal["describe", "distribution_stats", "distribution_pdf", "distribution_cdf"]
|
|
26
|
+
_DISTRIBUTIONS = Literal["normal", "binomial", "poisson", "uniform", "exponential"]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class ProbabilityStatsParams(BaseModel):
|
|
30
|
+
operation: _OPERATIONS = Field(..., description="Which operation to perform")
|
|
31
|
+
data: Optional[list[float]] = Field(None, description="Dataset, for the 'describe' operation")
|
|
32
|
+
distribution: Optional[_DISTRIBUTIONS] = Field(
|
|
33
|
+
None, description="Distribution family, for distribution_* operations"
|
|
34
|
+
)
|
|
35
|
+
distribution_params: Optional[dict[str, float]] = Field(
|
|
36
|
+
None,
|
|
37
|
+
description=(
|
|
38
|
+
"Parameters for the chosen distribution: normal={mu, sigma}, "
|
|
39
|
+
"binomial={n, p}, poisson={lambda}, uniform={a, b}, "
|
|
40
|
+
"exponential={rate}"
|
|
41
|
+
),
|
|
42
|
+
)
|
|
43
|
+
x: Optional[float] = Field(None, description="Point to evaluate pdf/cdf at")
|
|
44
|
+
evaluate: bool = Field(False, description="If true, return numeric approximation (evalf) instead of exact symbolic form (e.g. 0.84... instead of erf(...)). Default false keeps exact symbolic.")
|
|
45
|
+
precision: int = Field(15, ge=1, le=50, description="Significant digits when evaluate is true")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
TOOL_SCHEMA = {
|
|
49
|
+
"name": "probability_stats",
|
|
50
|
+
"description": (
|
|
51
|
+
"Compute descriptive statistics on a dataset (mean, median, "
|
|
52
|
+
"variance, stdev, min, max), or work with probability "
|
|
53
|
+
"distributions (normal, binomial, poisson, uniform, exponential): "
|
|
54
|
+
"expected value, variance, pdf at a point, or cdf at a point. "
|
|
55
|
+
"Results are exact symbolic expressions (e.g. erf(...), sqrt(pi)) unless 'evaluate' is true, "
|
|
56
|
+
"which returns a numeric approximation with 'precision' digits. When distribution parameters "
|
|
57
|
+
"are omitted, defaults are used (normal mu=0 sigma=1, uniform a=0 b=1, exponential rate=1) and a "
|
|
58
|
+
"'warnings' field explains what was defaulted."
|
|
59
|
+
),
|
|
60
|
+
"input_schema": ProbabilityStatsParams.model_json_schema(),
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _build_distribution_with_warnings(name: str, dp_orig: Optional[dict]):
|
|
65
|
+
"""Build distribution and collect warnings for defaulted params.
|
|
66
|
+
|
|
67
|
+
Returns (dist, warnings). Warnings is a list of strings for each param
|
|
68
|
+
that fell back to a default, per decision 2 (keep forgiving but explain).
|
|
69
|
+
Binomial/poisson have no defaults — missing required keys become a
|
|
70
|
+
friendly error at the caller, not a warning.
|
|
71
|
+
|
|
72
|
+
THE ONE BUILDER (#208). A warning-free twin, `_build_distribution`, sat
|
|
73
|
+
above this with no caller and the same five distributions and defaults,
|
|
74
|
+
so a change to one would have left the other silently wrong. It is
|
|
75
|
+
deleted; a caller that wants no warnings takes `[0]` of this.
|
|
76
|
+
"""
|
|
77
|
+
dp = dp_orig or {}
|
|
78
|
+
warnings: list[str] = []
|
|
79
|
+
if name == "normal":
|
|
80
|
+
if "mu" not in dp:
|
|
81
|
+
warnings.append("mu not supplied - defaulted to 0")
|
|
82
|
+
if "sigma" not in dp:
|
|
83
|
+
warnings.append("sigma not supplied - defaulted to 1")
|
|
84
|
+
return sstats.Normal("X", dp.get("mu", 0), dp.get("sigma", 1)), warnings
|
|
85
|
+
if name == "uniform":
|
|
86
|
+
if "a" not in dp:
|
|
87
|
+
warnings.append("a not supplied - defaulted to 0")
|
|
88
|
+
if "b" not in dp:
|
|
89
|
+
warnings.append("b not supplied - defaulted to 1")
|
|
90
|
+
return sstats.Uniform("X", dp.get("a", 0), dp.get("b", 1)), warnings
|
|
91
|
+
if name == "exponential":
|
|
92
|
+
if "rate" not in dp:
|
|
93
|
+
warnings.append("rate not supplied - defaulted to 1")
|
|
94
|
+
return sstats.Exponential("X", dp.get("rate", 1)), warnings
|
|
95
|
+
if name == "binomial":
|
|
96
|
+
# No defaults — caller validates presence
|
|
97
|
+
return sstats.Binomial("X", int(dp["n"]), dp["p"]), warnings
|
|
98
|
+
if name == "poisson":
|
|
99
|
+
return sstats.Poisson("X", dp["lambda"]), warnings
|
|
100
|
+
raise ValueError(f"Unsupported distribution: {name}")
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _maybe_evalf(value, do_eval: bool, precision: int):
|
|
104
|
+
if not do_eval or value is None:
|
|
105
|
+
return value
|
|
106
|
+
try:
|
|
107
|
+
if hasattr(value, "evalf"):
|
|
108
|
+
return value.evalf(precision)
|
|
109
|
+
except Exception:
|
|
110
|
+
pass # no numeric form; the exact value is still a correct answer
|
|
111
|
+
return value
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _cdf_at(dist, x):
|
|
115
|
+
"""Evaluate CDF at x, handling discrete binomial's dict return."""
|
|
116
|
+
try:
|
|
117
|
+
return sstats.cdf(dist)(x)
|
|
118
|
+
except TypeError as e:
|
|
119
|
+
if "'dict' object is not callable" in str(e):
|
|
120
|
+
# Binomial (and some discretes) return a dict table via two-arg form
|
|
121
|
+
table = sstats.cdf(dist, x)
|
|
122
|
+
if isinstance(table, dict):
|
|
123
|
+
import math
|
|
124
|
+
|
|
125
|
+
try:
|
|
126
|
+
# Discrete CDF at x is sum up to floor(x)
|
|
127
|
+
key = int(math.floor(float(x)))
|
|
128
|
+
except Exception:
|
|
129
|
+
return table
|
|
130
|
+
if key in table:
|
|
131
|
+
return table[key]
|
|
132
|
+
# find greatest key <= x
|
|
133
|
+
sorted_keys = sorted(table.keys())
|
|
134
|
+
candidate = None
|
|
135
|
+
for k in sorted_keys:
|
|
136
|
+
if k <= key:
|
|
137
|
+
candidate = table[k]
|
|
138
|
+
else:
|
|
139
|
+
break
|
|
140
|
+
if candidate is not None:
|
|
141
|
+
return candidate
|
|
142
|
+
if key < sorted_keys[0]:
|
|
143
|
+
return sympy.Integer(0)
|
|
144
|
+
return sympy.Integer(1)
|
|
145
|
+
return table
|
|
146
|
+
raise
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def run(params: dict) -> dict:
|
|
150
|
+
try:
|
|
151
|
+
parsed = parse_params(ProbabilityStatsParams, params)
|
|
152
|
+
except MathParseError as e:
|
|
153
|
+
return {"error": str(e)}
|
|
154
|
+
|
|
155
|
+
try:
|
|
156
|
+
if parsed.operation == "describe":
|
|
157
|
+
data = parsed.data
|
|
158
|
+
if not data:
|
|
159
|
+
return {"error": "data is required for 'describe'"}
|
|
160
|
+
result = {
|
|
161
|
+
"mean": pystats.mean(data),
|
|
162
|
+
"median": pystats.median(data),
|
|
163
|
+
"stdev": pystats.stdev(data) if len(data) > 1 else 0.0,
|
|
164
|
+
"variance": pystats.variance(data) if len(data) > 1 else 0.0,
|
|
165
|
+
"min": min(data),
|
|
166
|
+
"max": max(data),
|
|
167
|
+
"n": len(data),
|
|
168
|
+
}
|
|
169
|
+
return {"result": result, "operation": parsed.operation}
|
|
170
|
+
|
|
171
|
+
if not parsed.distribution:
|
|
172
|
+
return {"error": "distribution is required for this operation"}
|
|
173
|
+
|
|
174
|
+
dp = parsed.distribution_params or {}
|
|
175
|
+
# Friendly validation for distributions with no defaults
|
|
176
|
+
if parsed.distribution == "binomial":
|
|
177
|
+
if "n" not in dp or "p" not in dp:
|
|
178
|
+
return {"error": "binomial requires 'n' (number of trials) and 'p' (success probability) in distribution_params."}
|
|
179
|
+
if parsed.distribution == "poisson":
|
|
180
|
+
if "lambda" not in dp:
|
|
181
|
+
return {"error": "poisson requires 'lambda' in distribution_params."}
|
|
182
|
+
|
|
183
|
+
dist, warnings = _build_distribution_with_warnings(parsed.distribution, parsed.distribution_params)
|
|
184
|
+
|
|
185
|
+
if parsed.operation == "distribution_stats":
|
|
186
|
+
mean_v = _maybe_evalf(sstats.E(dist), parsed.evaluate, parsed.precision)
|
|
187
|
+
var_v = _maybe_evalf(sstats.variance(dist), parsed.evaluate, parsed.precision)
|
|
188
|
+
# std is sqrt(var) — eval the sqrt when numeric
|
|
189
|
+
raw_var = sstats.variance(dist)
|
|
190
|
+
std_v = _maybe_evalf(sympy.sqrt(raw_var), parsed.evaluate, parsed.precision)
|
|
191
|
+
result = {
|
|
192
|
+
"mean": str(mean_v),
|
|
193
|
+
"variance": str(var_v),
|
|
194
|
+
"std": str(std_v),
|
|
195
|
+
}
|
|
196
|
+
elif parsed.operation == "distribution_pdf":
|
|
197
|
+
if parsed.x is None:
|
|
198
|
+
return {"error": "x is required for distribution_pdf"}
|
|
199
|
+
x_arg = parsed.x
|
|
200
|
+
# Discrete distributions expect int; float 5.0 should be treated as 5
|
|
201
|
+
if parsed.distribution in ("binomial", "poisson") and isinstance(x_arg, float) and x_arg.is_integer():
|
|
202
|
+
x_arg = int(x_arg)
|
|
203
|
+
raw = sstats.density(dist)(x_arg)
|
|
204
|
+
val = _maybe_evalf(raw, parsed.evaluate, parsed.precision)
|
|
205
|
+
result = str(val)
|
|
206
|
+
elif parsed.operation == "distribution_cdf":
|
|
207
|
+
if parsed.x is None:
|
|
208
|
+
return {"error": "x is required for distribution_cdf"}
|
|
209
|
+
x_arg = parsed.x
|
|
210
|
+
if parsed.distribution in ("binomial", "poisson") and isinstance(x_arg, float) and x_arg.is_integer():
|
|
211
|
+
x_arg = int(x_arg)
|
|
212
|
+
raw = _cdf_at(dist, x_arg)
|
|
213
|
+
val = _maybe_evalf(raw, parsed.evaluate, parsed.precision)
|
|
214
|
+
result = str(val)
|
|
215
|
+
else:
|
|
216
|
+
return {"error": f"Unknown operation: {parsed.operation}"}
|
|
217
|
+
|
|
218
|
+
except Exception as e:
|
|
219
|
+
return {"error": f"Computation failed: {e}"}
|
|
220
|
+
|
|
221
|
+
out: dict = {"result": result, "operation": parsed.operation}
|
|
222
|
+
if warnings:
|
|
223
|
+
out["warnings"] = warnings
|
|
224
|
+
return out
|