forgeproof-cli 0.2.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.
- forge_gate/__init__.py +44 -0
- forge_gate/_deprecated_cli.py +16 -0
- forgeproof/__init__.py +3 -0
- forgeproof/catalog.py +110 -0
- forgeproof/cli.py +560 -0
- forgeproof/config.py +339 -0
- forgeproof/data/gate_catalog.json +66 -0
- forgeproof/data/host_sets.json +7 -0
- forgeproof/debug_caller.py +271 -0
- forgeproof/debug_core.py +368 -0
- forgeproof/fixture_engine.py +81 -0
- forgeproof/fixtures/__init__.py +19 -0
- forgeproof/fixtures/decision_tree_id3.py +90 -0
- forgeproof/fixtures/gradient_descent_momentum.py +73 -0
- forgeproof/fixtures/kmeans_clustering.py +98 -0
- forgeproof/fixtures/knn_classifier.py +79 -0
- forgeproof/fixtures/linear_regression_gd.py +77 -0
- forgeproof/fixtures/logistic_regression.py +85 -0
- forgeproof/fixtures/naive_bayes_text.py +114 -0
- forgeproof/fixtures/perceptron.py +84 -0
- forgeproof/fixtures/polynomial_regression.py +67 -0
- forgeproof/fixtures/ridge_regression_normal_eq.py +75 -0
- forgeproof/ledger.py +633 -0
- forgeproof/lens_tools/__init__.py +11 -0
- forgeproof/lens_tools/guard_lens.py +1250 -0
- forgeproof/lens_tools/invariant_contracts/linear_regression_gd.json +74 -0
- forgeproof/lens_tools/invariant_contracts/polynomial_regression.json +86 -0
- forgeproof/lens_tools/invariant_contracts/ridge_regression_normal_eq.json +86 -0
- forgeproof/lens_tools/invariant_gate.py +199 -0
- forgeproof/lens_tools/metamorphic/__init__.py +9 -0
- forgeproof/lens_tools/metamorphic/relations.py +962 -0
- forgeproof/lens_tools/metamorphic/runner.py +112 -0
- forgeproof/lens_tools/twin_consensus.py +395 -0
- forgeproof/lenses.py +923 -0
- forgeproof/paths.py +56 -0
- forgeproof/reference/ORIGIN.md +29 -0
- forgeproof/reference/decision_tree_id3.py +197 -0
- forgeproof/reference/gradient_descent_momentum.py +141 -0
- forgeproof/reference/kmeans_clustering.py +139 -0
- forgeproof/reference/knn_classifier.py +118 -0
- forgeproof/reference/linear_regression_gd.py +106 -0
- forgeproof/reference/logistic_regression.py +141 -0
- forgeproof/reference/naive_bayes_text.py +152 -0
- forgeproof/reference/perceptron.py +123 -0
- forgeproof/reference/polynomial_regression.py +125 -0
- forgeproof/reference/ridge_regression_normal_eq.py +165 -0
- forgeproof/runner.py +147 -0
- forgeproof/scout/__init__.py +7 -0
- forgeproof/scout/behaviour.py +365 -0
- forgeproof/scout/box.py +581 -0
- forgeproof/scout/cards.py +180 -0
- forgeproof/scout/contract.py +37 -0
- forgeproof/scout/corpus.py +104 -0
- forgeproof/scout/embed.py +217 -0
- forgeproof/scout/engines/__init__.py +1 -0
- forgeproof/scout/engines/chaos.py +454 -0
- forgeproof/scout/engines/chaos_port.py +1331 -0
- forgeproof/scout/engines/chaos_runner.py +178 -0
- forgeproof/scout/engines/executor_port.py +239 -0
- forgeproof/scout/envfit.py +54 -0
- forgeproof/scout/experience.py +161 -0
- forgeproof/scout/fetchproxy.py +368 -0
- forgeproof/scout/ghcache.py +395 -0
- forgeproof/scout/ghpool.py +253 -0
- forgeproof/scout/ghsearch.py +248 -0
- forgeproof/scout/ids.py +82 -0
- forgeproof/scout/intent_lens.py +170 -0
- forgeproof/scout/learn.py +583 -0
- forgeproof/scout/meaning_lens.py +231 -0
- forgeproof/scout/outcomes.py +42 -0
- forgeproof/scout/plant.py +327 -0
- forgeproof/scout/ratify.py +214 -0
- forgeproof/scout/report.py +448 -0
- forgeproof/scout/rule2.py +177 -0
- forgeproof/scout/shape.py +107 -0
- forgeproof/scout/shape_lens.py +71 -0
- forgeproof/scout/signature.py +52 -0
- forgeproof/scout/slots.py +39 -0
- forgeproof/scout/upstream_facts.py +536 -0
- forgeproof/unsupported.py +83 -0
- forgeproof/verifier.py +208 -0
- forgeproof/view_coverage.py +166 -0
- forgeproof_cli-0.2.0.dist-info/METADATA +285 -0
- forgeproof_cli-0.2.0.dist-info/RECORD +89 -0
- forgeproof_cli-0.2.0.dist-info/WHEEL +5 -0
- forgeproof_cli-0.2.0.dist-info/entry_points.txt +3 -0
- forgeproof_cli-0.2.0.dist-info/licenses/LICENSE +201 -0
- forgeproof_cli-0.2.0.dist-info/licenses/NOTICE +23 -0
- forgeproof_cli-0.2.0.dist-info/top_level.txt +2 -0
forgeproof/paths.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""One path canonicaliser for forgeproof and its tools, moved verbatim from ``ledger.py``.
|
|
2
|
+
|
|
3
|
+
``real`` resolves links; ``canonical`` returns the spelling the file system stores; ``is_under``
|
|
4
|
+
compares by identity (device + inode). ``ledger.py`` keeps its old private names as aliases;
|
|
5
|
+
every other module uses these public names, never the ledger's copies (``tests/test_ledger_routes.py``).
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import fcntl
|
|
10
|
+
import os
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def real(p) -> Path:
|
|
15
|
+
return Path(os.path.realpath(p))
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def canonical(p) -> Path:
|
|
19
|
+
"""The path as the file system spells it, for the path HASHES (8a s7 review F1): on macOS's
|
|
20
|
+
case-insensitive disk ``realpath`` keeps the case that was typed, so ``Proj`` and ``PROJ``
|
|
21
|
+
would be two reuse sites for one folder. ``F_GETPATH`` (macOS) returns the stored spelling;
|
|
22
|
+
elsewhere, or if the path cannot be opened, ``realpath`` (case-sensitive file systems)."""
|
|
23
|
+
rp = os.path.realpath(p)
|
|
24
|
+
if hasattr(fcntl, "F_GETPATH"):
|
|
25
|
+
try:
|
|
26
|
+
fd = os.open(rp, os.O_RDONLY)
|
|
27
|
+
except OSError:
|
|
28
|
+
return Path(rp)
|
|
29
|
+
try:
|
|
30
|
+
return Path(fcntl.fcntl(fd, fcntl.F_GETPATH, bytes(1024)).split(b"\0", 1)[0].decode(
|
|
31
|
+
"utf-8", "surrogateescape"))
|
|
32
|
+
except OSError:
|
|
33
|
+
return Path(rp)
|
|
34
|
+
finally:
|
|
35
|
+
os.close(fd)
|
|
36
|
+
return Path(rp)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def is_under(p: Path, root: Path) -> bool:
|
|
40
|
+
"""By identity (device + inode), not by spelling: on a case-insensitive file system two
|
|
41
|
+
spellings of one folder are one folder (8a s3 review F6).
|
|
42
|
+
|
|
43
|
+
Callers pass RESOLVED paths (``real(...)``): the walk is over ``p``'s lexical parents, so an
|
|
44
|
+
unresolved ``root/link/x`` whose link points outside ``root`` still counts as under it."""
|
|
45
|
+
try:
|
|
46
|
+
r = os.stat(root)
|
|
47
|
+
except OSError:
|
|
48
|
+
return False
|
|
49
|
+
for q in (p, *p.parents):
|
|
50
|
+
try:
|
|
51
|
+
st = os.stat(q)
|
|
52
|
+
except OSError:
|
|
53
|
+
continue
|
|
54
|
+
if (st.st_dev, st.st_ino) == (r.st_dev, r.st_ino):
|
|
55
|
+
return True
|
|
56
|
+
return False
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# ORIGIN — reference implementations (copied, not written here)
|
|
2
|
+
|
|
3
|
+
These 10 files are **byte-for-byte copies** of patterns from the AURA Pattern Library.
|
|
4
|
+
`forgeproof verify` runs each one as the ground-truth oracle for its pattern, so the
|
|
5
|
+
shipped tool no longer reads the library at run time (build step 1, Q1, 2026-11-11).
|
|
6
|
+
|
|
7
|
+
- **Source:** aura-pattern-library, commit `c39c1dcc3adb0aa9bd04eb30f1f00045c14c88ce` (GitHub master, PR #7).
|
|
8
|
+
Copied 2026-11-11 from `d7462d320c263f9870e80321e1edbb0d112fe6e6`, a dev-machine commit never pushed; re-pinned the same day
|
|
9
|
+
to the published commit, where all 10 files are byte-identical (KNOWN-DEBT KD-3, the maintainer's
|
|
10
|
+
option b). The sha256s below did not change.
|
|
11
|
+
- **Licence:** Apache-2.0, Copyright 2026 Illia Hladkyi (Reality Optimizer), the same
|
|
12
|
+
author and licence as ForgeProof. The library's NOTICE applies to these files.
|
|
13
|
+
- **Changed here:** nothing. Do not edit them in this repo. Fix the pattern in the
|
|
14
|
+
library, then re-copy, and update the commit and every sha256 below in the same change.
|
|
15
|
+
- **Drift check:** `tests/test_live_library.py` (tier `live`, needs
|
|
16
|
+
`FORGE_GATE_LIBRARY_DIR`) compares each copy against the library checkout.
|
|
17
|
+
|
|
18
|
+
| file here | path in the library | sha256 |
|
|
19
|
+
|---|---|---|
|
|
20
|
+
| `kmeans_clustering.py` | `python/data-science/core_ml/kmeans_clustering.py` | `55d6e53c91e646eedc6157d86ed4343d30db62f7b44ecc9c06d8c65f8193bf8a` |
|
|
21
|
+
| `linear_regression_gd.py` | `python/data-science/core_ml/linear_regression_gd.py` | `bbe705e724d0c99a93932cf7297c4bb7ebc9ce2ae1683cc18b94ad7ad2b09e10` |
|
|
22
|
+
| `knn_classifier.py` | `python/data-science/core_ml/knn_classifier.py` | `54338b4c40e5677c35bc0c840467b442c628830cc368639c8d241339b258d269` |
|
|
23
|
+
| `logistic_regression.py` | `python/data-science/core_ml/logistic_regression.py` | `75b9aa0ced8513806b4f8d12d9742d2894be8574dcfe6885274e61ca71239dbd` |
|
|
24
|
+
| `naive_bayes_text.py` | `python/data-science/core_ml/naive_bayes_text.py` | `ae5ab902788a16dfc1d9cbdd46dbc5f01014b158d034443a7b10d705f357008b` |
|
|
25
|
+
| `polynomial_regression.py` | `python/data-science/statistical_modeling/polynomial_regression.py` | `24ca3b6a78bbbb8dd29f3887a32373c1eadec92e101709ede5db6aa1b291a4c4` |
|
|
26
|
+
| `decision_tree_id3.py` | `python/data-science/core_ml/decision_tree_id3.py` | `4e2d16f0d9766fdab3c7c04430628da97e994068017dbef8663277e5c0f6d986` |
|
|
27
|
+
| `perceptron.py` | `python/data-science/core_ml/perceptron.py` | `033bf1abc5ab1ed0e1476e18c1866c347ab838802b256a68e44769879e4c3611` |
|
|
28
|
+
| `ridge_regression_normal_eq.py` | `python/data-science/core_ml/ridge_regression_normal_eq.py` | `d93d8ede8a412ff3d4f958cbaeec1a61366c29c41fea0b50497fb6624d9d1bfd` |
|
|
29
|
+
| `gradient_descent_momentum.py` | `python/data-science/optimization_and_distances/gradient_descent_momentum.py` | `9d55286a77733865875b53abf1d7565bc96a2f40183f38ce595f7cf36917b15b` |
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Decision Tree Classifier using ID3 Algorithm (from scratch).
|
|
3
|
+
|
|
4
|
+
Core idea: Recursively split data on the feature that gives the highest
|
|
5
|
+
information gain (reduction in entropy). Build tree top-down, stopping when
|
|
6
|
+
all samples are of one class or max depth is reached.
|
|
7
|
+
|
|
8
|
+
When to use: Non-linear boundaries; interpretable rules; categorical/continuous data.
|
|
9
|
+
"""
|
|
10
|
+
# △ AURA Pattern Library — © Reality Optimizer ⟦AE1.PMRGG3ZCHIRFEZLBNRUXI6JAJ5YHI2LNNF5GK4RCFQRG2IR2EJAUKTKBKJFTCIRMEJXCEORCGARCYITQNFSCEORCEIWCE5DNEI5CEQKVKJASAUDBOR2GK4TOEBGGSYTSMFZHSIRMEJ3CEORRPWYSJPXO⟧
|
|
11
|
+
#
|
|
12
|
+
_AURA_MARK = "AE1.PMRGG3ZCHIRFEZLBNRUXI6JAJ5YHI2LNNF5GK4RCFQRG2IR2EJAUKTKBKJFTCIRMEJXCEORCGARCYITQNFSCEORCEIWCE5DNEI5CEQKVKJASAUDBOR2GK4TOEBGGSYTSMFZHSIRMEJ3CEORRPWYSJPXO"
|
|
13
|
+
|
|
14
|
+
import random
|
|
15
|
+
import math
|
|
16
|
+
from typing import List, Tuple, Optional, Dict, Any
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def entropy(class_counts: Dict[int, int]) -> float:
|
|
20
|
+
"""Compute Shannon entropy from class counts."""
|
|
21
|
+
total = sum(class_counts.values())
|
|
22
|
+
if total == 0:
|
|
23
|
+
return 0.0
|
|
24
|
+
ent = 0.0
|
|
25
|
+
for count in class_counts.values():
|
|
26
|
+
if count > 0:
|
|
27
|
+
p = count / total
|
|
28
|
+
ent -= p * math.log2(p)
|
|
29
|
+
return ent
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def information_gain(
|
|
33
|
+
parent_entropy: float,
|
|
34
|
+
child_entropies: List[Tuple[int, float]]
|
|
35
|
+
) -> float:
|
|
36
|
+
"""
|
|
37
|
+
Compute information gain from a split.
|
|
38
|
+
|
|
39
|
+
Args:
|
|
40
|
+
parent_entropy: entropy of parent node
|
|
41
|
+
child_entropies: list of (sample_count, entropy) for each child
|
|
42
|
+
|
|
43
|
+
Returns:
|
|
44
|
+
information gain
|
|
45
|
+
"""
|
|
46
|
+
total = sum(count for count, _ in child_entropies)
|
|
47
|
+
weighted_child_entropy = sum((count / total) * ent for count, ent in child_entropies)
|
|
48
|
+
return parent_entropy - weighted_child_entropy
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class TreeNode:
|
|
52
|
+
"""A node in the decision tree."""
|
|
53
|
+
def __init__(self):
|
|
54
|
+
self.feature: Optional[int] = None
|
|
55
|
+
self.threshold: Optional[float] = None
|
|
56
|
+
self.label: Optional[int] = None # For leaf nodes
|
|
57
|
+
self.left: Optional['TreeNode'] = None
|
|
58
|
+
self.right: Optional['TreeNode'] = None
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def build_tree(
|
|
62
|
+
X: List[List[float]],
|
|
63
|
+
y: List[int],
|
|
64
|
+
max_depth: int = 5,
|
|
65
|
+
depth: int = 0
|
|
66
|
+
) -> TreeNode:
|
|
67
|
+
"""
|
|
68
|
+
Build a decision tree using ID3 (information gain).
|
|
69
|
+
|
|
70
|
+
Args:
|
|
71
|
+
X: feature matrix
|
|
72
|
+
y: labels
|
|
73
|
+
max_depth: maximum tree depth
|
|
74
|
+
depth: current depth (for recursion)
|
|
75
|
+
|
|
76
|
+
Returns:
|
|
77
|
+
root TreeNode
|
|
78
|
+
"""
|
|
79
|
+
node = TreeNode()
|
|
80
|
+
|
|
81
|
+
# Base cases: all same class or max depth
|
|
82
|
+
class_counts = {}
|
|
83
|
+
for label in y:
|
|
84
|
+
class_counts[label] = class_counts.get(label, 0) + 1
|
|
85
|
+
|
|
86
|
+
if len(class_counts) == 1 or depth >= max_depth or len(X) == 0:
|
|
87
|
+
node.label = max(class_counts, key=class_counts.get)
|
|
88
|
+
return node
|
|
89
|
+
|
|
90
|
+
# Try to find best split
|
|
91
|
+
parent_entropy = entropy(class_counts)
|
|
92
|
+
n_features = len(X[0]) if X else 0
|
|
93
|
+
best_gain = 0.0
|
|
94
|
+
best_feature = None
|
|
95
|
+
best_threshold = None
|
|
96
|
+
|
|
97
|
+
for feature in range(n_features):
|
|
98
|
+
# Try each unique value as threshold
|
|
99
|
+
thresholds = sorted(set(X[i][feature] for i in range(len(X))))
|
|
100
|
+
|
|
101
|
+
for i in range(len(thresholds) - 1):
|
|
102
|
+
threshold = (thresholds[i] + thresholds[i + 1]) / 2.0
|
|
103
|
+
|
|
104
|
+
# Split data
|
|
105
|
+
left_indices = [j for j in range(len(X)) if X[j][feature] <= threshold]
|
|
106
|
+
right_indices = [j for j in range(len(X)) if X[j][feature] > threshold]
|
|
107
|
+
|
|
108
|
+
if len(left_indices) == 0 or len(right_indices) == 0:
|
|
109
|
+
continue
|
|
110
|
+
|
|
111
|
+
# Compute entropy of children
|
|
112
|
+
left_counts = {}
|
|
113
|
+
right_counts = {}
|
|
114
|
+
|
|
115
|
+
for idx in left_indices:
|
|
116
|
+
left_counts[y[idx]] = left_counts.get(y[idx], 0) + 1
|
|
117
|
+
for idx in right_indices:
|
|
118
|
+
right_counts[y[idx]] = right_counts.get(y[idx], 0) + 1
|
|
119
|
+
|
|
120
|
+
left_entropy = entropy(left_counts)
|
|
121
|
+
right_entropy = entropy(right_counts)
|
|
122
|
+
|
|
123
|
+
gain = information_gain(parent_entropy, [
|
|
124
|
+
(len(left_indices), left_entropy),
|
|
125
|
+
(len(right_indices), right_entropy)
|
|
126
|
+
])
|
|
127
|
+
|
|
128
|
+
if gain > best_gain:
|
|
129
|
+
best_gain = gain
|
|
130
|
+
best_feature = feature
|
|
131
|
+
best_threshold = threshold
|
|
132
|
+
|
|
133
|
+
# If no good split found, make leaf
|
|
134
|
+
if best_feature is None:
|
|
135
|
+
node.label = max(class_counts, key=class_counts.get)
|
|
136
|
+
return node
|
|
137
|
+
|
|
138
|
+
# Split and recurse
|
|
139
|
+
left_indices = [j for j in range(len(X)) if X[j][best_feature] <= best_threshold]
|
|
140
|
+
right_indices = [j for j in range(len(X)) if X[j][best_feature] > best_threshold]
|
|
141
|
+
|
|
142
|
+
X_left = [X[i] for i in left_indices]
|
|
143
|
+
y_left = [y[i] for i in left_indices]
|
|
144
|
+
X_right = [X[i] for i in right_indices]
|
|
145
|
+
y_right = [y[i] for i in right_indices]
|
|
146
|
+
|
|
147
|
+
node.feature = best_feature
|
|
148
|
+
node.threshold = best_threshold
|
|
149
|
+
node.left = build_tree(X_left, y_left, max_depth, depth + 1)
|
|
150
|
+
node.right = build_tree(X_right, y_right, max_depth, depth + 1)
|
|
151
|
+
|
|
152
|
+
return node
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def predict_tree(x: List[float], node: TreeNode) -> int:
|
|
156
|
+
"""Predict class for a single sample."""
|
|
157
|
+
if node.label is not None:
|
|
158
|
+
return node.label
|
|
159
|
+
|
|
160
|
+
if x[node.feature] <= node.threshold:
|
|
161
|
+
return predict_tree(x, node.left)
|
|
162
|
+
else:
|
|
163
|
+
return predict_tree(x, node.right)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
if __name__ == "__main__":
|
|
167
|
+
random.seed(42)
|
|
168
|
+
|
|
169
|
+
# Generate synthetic classification data
|
|
170
|
+
n_samples = 50
|
|
171
|
+
X = []
|
|
172
|
+
y = []
|
|
173
|
+
|
|
174
|
+
# Class 0: x1 < 2.5
|
|
175
|
+
for _ in range(n_samples // 2):
|
|
176
|
+
x1 = random.uniform(0, 2.5)
|
|
177
|
+
x2 = random.uniform(0, 5)
|
|
178
|
+
X.append([x1, x2])
|
|
179
|
+
y.append(0)
|
|
180
|
+
|
|
181
|
+
# Class 1: x1 >= 2.5
|
|
182
|
+
for _ in range(n_samples // 2):
|
|
183
|
+
x1 = random.uniform(2.5, 5)
|
|
184
|
+
x2 = random.uniform(0, 5)
|
|
185
|
+
X.append([x1, x2])
|
|
186
|
+
y.append(1)
|
|
187
|
+
|
|
188
|
+
# Build tree
|
|
189
|
+
tree = build_tree(X, y, max_depth=5)
|
|
190
|
+
|
|
191
|
+
# Test on training data
|
|
192
|
+
preds = [predict_tree(X[i], tree) for i in range(len(X))]
|
|
193
|
+
accuracy = sum(preds[i] == y[i] for i in range(len(X))) / len(X)
|
|
194
|
+
|
|
195
|
+
assert accuracy >= 0.95, f"Accuracy = {accuracy} is too low"
|
|
196
|
+
|
|
197
|
+
print(f"DECISION_TREE_ID3 PASS: accuracy = {accuracy:.3f}")
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"""
|
|
2
|
+
OPTIMIZATION: Gradient Descent with Momentum
|
|
3
|
+
|
|
4
|
+
Core idea: Vanilla gradient descent oscillates in narrow valleys; momentum accumulates
|
|
5
|
+
velocity across iterations, smoothing the path and converging faster. Compare vanilla GD
|
|
6
|
+
vs momentum GD on a 2D quadratic bowl.
|
|
7
|
+
|
|
8
|
+
When to use: Convex optimization with non-isotropic (elongated) loss landscapes; standard
|
|
9
|
+
in neural network training to accelerate convergence and reduce oscillation.
|
|
10
|
+
"""
|
|
11
|
+
# △ AURA Pattern Library — © Reality Optimizer ⟦AE1.PMRGG3ZCHIRFEZLBNRUXI6JAJ5YHI2LNNF5GK4RCFQRG2IR2EJAUKTKBKJFTCIRMEJXCEORCGARCYITQNFSCEORCEIWCE5DNEI5CEQKVKJASAUDBOR2GK4TOEBGGSYTSMFZHSIRMEJ3CEORRPWYSJPXO⟧
|
|
12
|
+
#
|
|
13
|
+
_AURA_MARK = "AE1.PMRGG3ZCHIRFEZLBNRUXI6JAJ5YHI2LNNF5GK4RCFQRG2IR2EJAUKTKBKJFTCIRMEJXCEORCGARCYITQNFSCEORCEIWCE5DNEI5CEQKVKJASAUDBOR2GK4TOEBGGSYTSMFZHSIRMEJ3CEORRPWYSJPXO"
|
|
14
|
+
|
|
15
|
+
import math
|
|
16
|
+
import random
|
|
17
|
+
from typing import Tuple, List
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def quadratic_bowl(x: float, y: float) -> float:
|
|
21
|
+
"""2D quadratic bowl: f(x,y) = 100*x^2 + y^2. Global minimum at (0, 0)."""
|
|
22
|
+
return 100 * x**2 + y**2
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def gradient_bowl(x: float, y: float) -> Tuple[float, float]:
|
|
26
|
+
"""Gradient of quadratic_bowl: (df/dx, df/dy)."""
|
|
27
|
+
return (200 * x, 2 * y)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class AuraInputError(ValueError):
|
|
33
|
+
"""All input-contract violations, reported together (accumulate-then-raise)."""
|
|
34
|
+
def __init__(self, violations):
|
|
35
|
+
self.violations = violations
|
|
36
|
+
super().__init__("input contract violated:\n " + "\n ".join(violations))
|
|
37
|
+
|
|
38
|
+
def _aura_validate_momentum_gd(learning_rate, momentum, tolerance):
|
|
39
|
+
v = []
|
|
40
|
+
if isinstance(learning_rate, (int, float)) and learning_rate <= 0:
|
|
41
|
+
v.append(f"AURA-E009: learning_rate must be > 0, got {learning_rate}")
|
|
42
|
+
if isinstance(learning_rate, (int, float)) and learning_rate <= 0:
|
|
43
|
+
v.append(f"AURA-E001: learning_rate must be > 0, got {learning_rate}")
|
|
44
|
+
if isinstance(momentum, (int, float)) and momentum <= 0:
|
|
45
|
+
v.append(f"AURA-E009: momentum must be > 0, got {momentum}")
|
|
46
|
+
if isinstance(tolerance, (int, float)) and not math.isfinite(tolerance):
|
|
47
|
+
v.append(f"AURA-E008: tolerance must be finite, got {tolerance}")
|
|
48
|
+
if isinstance(tolerance, (int, float)) and tolerance <= 0:
|
|
49
|
+
v.append(f"AURA-E009: tolerance must be > 0, got {tolerance}")
|
|
50
|
+
if v:
|
|
51
|
+
raise AuraInputError(v)
|
|
52
|
+
|
|
53
|
+
def _aura_validate_vanilla_gd(learning_rate, tolerance):
|
|
54
|
+
v = []
|
|
55
|
+
if isinstance(learning_rate, (int, float)) and learning_rate <= 0:
|
|
56
|
+
v.append(f"AURA-E009: learning_rate must be > 0, got {learning_rate}")
|
|
57
|
+
if isinstance(learning_rate, (int, float)) and learning_rate <= 0:
|
|
58
|
+
v.append(f"AURA-E001: learning_rate must be > 0, got {learning_rate}")
|
|
59
|
+
if isinstance(tolerance, (int, float)) and not math.isfinite(tolerance):
|
|
60
|
+
v.append(f"AURA-E008: tolerance must be finite, got {tolerance}")
|
|
61
|
+
if isinstance(tolerance, (int, float)) and tolerance <= 0:
|
|
62
|
+
v.append(f"AURA-E009: tolerance must be > 0, got {tolerance}")
|
|
63
|
+
if v:
|
|
64
|
+
raise AuraInputError(v)
|
|
65
|
+
|
|
66
|
+
def vanilla_gd(
|
|
67
|
+
x: float,
|
|
68
|
+
y: float,
|
|
69
|
+
learning_rate: float = 0.005,
|
|
70
|
+
tolerance: float = 1e-6,
|
|
71
|
+
max_iters: int = 10000,
|
|
72
|
+
) -> Tuple[int, float]:
|
|
73
|
+
"""
|
|
74
|
+
Vanilla gradient descent.
|
|
75
|
+
Returns (iterations to convergence, final function value).
|
|
76
|
+
"""
|
|
77
|
+
_aura_validate_vanilla_gd(learning_rate, tolerance)
|
|
78
|
+
for i in range(max_iters):
|
|
79
|
+
fx = quadratic_bowl(x, y)
|
|
80
|
+
if fx < tolerance:
|
|
81
|
+
return i, fx
|
|
82
|
+
|
|
83
|
+
gx, gy = gradient_bowl(x, y)
|
|
84
|
+
x -= learning_rate * gx
|
|
85
|
+
y -= learning_rate * gy
|
|
86
|
+
|
|
87
|
+
return max_iters, quadratic_bowl(x, y)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def momentum_gd(
|
|
91
|
+
x: float,
|
|
92
|
+
y: float,
|
|
93
|
+
learning_rate: float = 0.005,
|
|
94
|
+
momentum: float = 0.9,
|
|
95
|
+
tolerance: float = 1e-6,
|
|
96
|
+
max_iters: int = 10000,
|
|
97
|
+
) -> Tuple[int, float]:
|
|
98
|
+
"""
|
|
99
|
+
Gradient descent with momentum.
|
|
100
|
+
Maintains velocity (vx, vy) accumulated from past gradients.
|
|
101
|
+
Returns (iterations to convergence, final function value).
|
|
102
|
+
"""
|
|
103
|
+
_aura_validate_momentum_gd(learning_rate, momentum, tolerance)
|
|
104
|
+
vx, vy = 0.0, 0.0
|
|
105
|
+
|
|
106
|
+
for i in range(max_iters):
|
|
107
|
+
fx = quadratic_bowl(x, y)
|
|
108
|
+
if fx < tolerance:
|
|
109
|
+
return i, fx
|
|
110
|
+
|
|
111
|
+
gx, gy = gradient_bowl(x, y)
|
|
112
|
+
# Momentum update: v_new = momentum * v_old + lr * gradient
|
|
113
|
+
vx = momentum * vx + learning_rate * gx
|
|
114
|
+
vy = momentum * vy + learning_rate * gy
|
|
115
|
+
x -= vx
|
|
116
|
+
y -= vy
|
|
117
|
+
|
|
118
|
+
return max_iters, quadratic_bowl(x, y)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
if __name__ == "__main__":
|
|
122
|
+
random.seed(42)
|
|
123
|
+
|
|
124
|
+
# Start from same point for fair comparison
|
|
125
|
+
x0, y0 = 10.0, 10.0
|
|
126
|
+
|
|
127
|
+
iters_vanilla, fx_vanilla = vanilla_gd(x0, y0)
|
|
128
|
+
iters_momentum, fx_momentum = momentum_gd(x0, y0)
|
|
129
|
+
|
|
130
|
+
# Check convergence assertions
|
|
131
|
+
assert fx_vanilla < 1e-6, f"Vanilla GD did not converge: {fx_vanilla}"
|
|
132
|
+
assert fx_momentum < 1e-6, f"Momentum GD did not converge: {fx_momentum}"
|
|
133
|
+
|
|
134
|
+
# Momentum should converge faster (fewer iterations)
|
|
135
|
+
assert (
|
|
136
|
+
iters_momentum < iters_vanilla
|
|
137
|
+
), f"Momentum ({iters_momentum}) not faster than vanilla ({iters_vanilla})"
|
|
138
|
+
|
|
139
|
+
print(
|
|
140
|
+
f"gradient_descent_momentum.py: vanilla_iters={iters_vanilla} momentum_iters={iters_momentum} PASS"
|
|
141
|
+
)
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"""
|
|
2
|
+
k-Means Clustering (from scratch).
|
|
3
|
+
|
|
4
|
+
Core idea: Partition data into k clusters by iteratively assigning samples
|
|
5
|
+
to the nearest centroid and updating centroids to be the mean of assigned samples.
|
|
6
|
+
Repeat until convergence (centroids stop moving).
|
|
7
|
+
|
|
8
|
+
When to use: Unsupervised clustering; exploratory analysis; identifying natural groups.
|
|
9
|
+
"""
|
|
10
|
+
# △ AURA Pattern Library — © Reality Optimizer ⟦AE1.PMRGG3ZCHIRFEZLBNRUXI6JAJ5YHI2LNNF5GK4RCFQRG2IR2EJAUKTKBKJFTCIRMEJXCEORCGARCYITQNFSCEORCEIWCE5DNEI5CEQKVKJASAUDBOR2GK4TOEBGGSYTSMFZHSIRMEJ3CEORRPWYSJPXO⟧
|
|
11
|
+
#
|
|
12
|
+
_AURA_MARK = "AE1.PMRGG3ZCHIRFEZLBNRUXI6JAJ5YHI2LNNF5GK4RCFQRG2IR2EJAUKTKBKJFTCIRMEJXCEORCGARCYITQNFSCEORCEIWCE5DNEI5CEQKVKJASAUDBOR2GK4TOEBGGSYTSMFZHSIRMEJ3CEORRPWYSJPXO"
|
|
13
|
+
|
|
14
|
+
import random
|
|
15
|
+
import math
|
|
16
|
+
from typing import List, Tuple
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def euclidean_distance(p1: List[float], p2: List[float]) -> float:
|
|
20
|
+
"""Compute Euclidean distance between two points."""
|
|
21
|
+
return math.sqrt(sum((p1[i] - p2[i]) ** 2 for i in range(len(p1))))
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def kmeans(
|
|
25
|
+
X: List[List[float]],
|
|
26
|
+
k: int,
|
|
27
|
+
max_iterations: int = 100,
|
|
28
|
+
tolerance: float = 1e-4
|
|
29
|
+
) -> Tuple[List[List[float]], List[int]]:
|
|
30
|
+
"""
|
|
31
|
+
Fit k-means clustering.
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
X: list of data points (each a feature vector)
|
|
35
|
+
k: number of clusters
|
|
36
|
+
max_iterations: maximum number of iterations
|
|
37
|
+
tolerance: convergence threshold for centroid movement
|
|
38
|
+
|
|
39
|
+
Returns:
|
|
40
|
+
(centroids, assignments): final centroids and cluster assignments for each sample
|
|
41
|
+
"""
|
|
42
|
+
n_samples = len(X)
|
|
43
|
+
n_features = len(X[0]) if X else 0
|
|
44
|
+
|
|
45
|
+
# Initialize centroids: randomly select k samples
|
|
46
|
+
indices = random.sample(range(n_samples), k)
|
|
47
|
+
centroids = [X[i][:] for i in indices]
|
|
48
|
+
|
|
49
|
+
for iteration in range(max_iterations):
|
|
50
|
+
# Assign samples to nearest centroid
|
|
51
|
+
assignments = []
|
|
52
|
+
for i in range(n_samples):
|
|
53
|
+
distances = [euclidean_distance(X[i], centroids[j]) for j in range(k)]
|
|
54
|
+
assignments.append(distances.index(min(distances)))
|
|
55
|
+
|
|
56
|
+
# Compute new centroids
|
|
57
|
+
new_centroids = []
|
|
58
|
+
for j in range(k):
|
|
59
|
+
cluster_points = [X[i] for i in range(n_samples) if assignments[i] == j]
|
|
60
|
+
if cluster_points:
|
|
61
|
+
centroid = [sum(p[f] for p in cluster_points) / len(cluster_points)
|
|
62
|
+
for f in range(n_features)]
|
|
63
|
+
else:
|
|
64
|
+
# Empty cluster: keep old centroid
|
|
65
|
+
centroid = centroids[j][:]
|
|
66
|
+
new_centroids.append(centroid)
|
|
67
|
+
|
|
68
|
+
# Check convergence: sum of centroid movements
|
|
69
|
+
movement = sum(euclidean_distance(centroids[j], new_centroids[j]) for j in range(k))
|
|
70
|
+
centroids = new_centroids
|
|
71
|
+
|
|
72
|
+
if movement < tolerance:
|
|
73
|
+
break
|
|
74
|
+
|
|
75
|
+
# Final assignment
|
|
76
|
+
assignments = []
|
|
77
|
+
for i in range(n_samples):
|
|
78
|
+
distances = [euclidean_distance(X[i], centroids[j]) for j in range(k)]
|
|
79
|
+
assignments.append(distances.index(min(distances)))
|
|
80
|
+
|
|
81
|
+
return centroids, assignments
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def intra_cluster_distance(
|
|
85
|
+
X: List[List[float]],
|
|
86
|
+
centroids: List[List[float]],
|
|
87
|
+
assignments: List[int]
|
|
88
|
+
) -> float:
|
|
89
|
+
"""Compute average distance from points to their centroid (inertia)."""
|
|
90
|
+
total_dist = 0.0
|
|
91
|
+
for i in range(len(X)):
|
|
92
|
+
c = assignments[i]
|
|
93
|
+
total_dist += euclidean_distance(X[i], centroids[c])
|
|
94
|
+
return total_dist / len(X) if X else 0.0
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
if __name__ == "__main__":
|
|
98
|
+
random.seed(42)
|
|
99
|
+
|
|
100
|
+
# Generate synthetic data: 3 well-separated clusters
|
|
101
|
+
n_per_cluster = 20
|
|
102
|
+
X = []
|
|
103
|
+
|
|
104
|
+
# Cluster 0: around (0, 0)
|
|
105
|
+
for _ in range(n_per_cluster):
|
|
106
|
+
X.append([random.gauss(0, 0.5), random.gauss(0, 0.5)])
|
|
107
|
+
|
|
108
|
+
# Cluster 1: around (5, 0)
|
|
109
|
+
for _ in range(n_per_cluster):
|
|
110
|
+
X.append([random.gauss(5, 0.5), random.gauss(0, 0.5)])
|
|
111
|
+
|
|
112
|
+
# Cluster 2: around (2.5, 4)
|
|
113
|
+
for _ in range(n_per_cluster):
|
|
114
|
+
X.append([random.gauss(2.5, 0.5), random.gauss(4, 0.5)])
|
|
115
|
+
|
|
116
|
+
# Fit k-means
|
|
117
|
+
centroids, assignments = kmeans(X, k=3, max_iterations=100)
|
|
118
|
+
|
|
119
|
+
# Evaluate: most points should be in the correct cluster
|
|
120
|
+
# Cluster 0: points 0-19, Cluster 1: points 20-39, Cluster 2: points 40-59
|
|
121
|
+
correct = 0
|
|
122
|
+
for i in range(len(X)):
|
|
123
|
+
true_cluster = i // n_per_cluster
|
|
124
|
+
# Find which predicted cluster matches (may be permuted)
|
|
125
|
+
# For now just check that points in same true cluster are assigned to same predicted cluster
|
|
126
|
+
pass
|
|
127
|
+
|
|
128
|
+
# Check intra-cluster distance is small (tight clusters)
|
|
129
|
+
intra_dist = intra_cluster_distance(X, centroids, assignments)
|
|
130
|
+
assert intra_dist < 2.0, f"Intra-cluster distance = {intra_dist} is too high"
|
|
131
|
+
|
|
132
|
+
# Check that we have 3 distinct centroids
|
|
133
|
+
centroid_dists = []
|
|
134
|
+
for i in range(3):
|
|
135
|
+
for j in range(i + 1, 3):
|
|
136
|
+
centroid_dists.append(euclidean_distance(centroids[i], centroids[j]))
|
|
137
|
+
assert min(centroid_dists) > 2.0, "Centroids are too close together"
|
|
138
|
+
|
|
139
|
+
print(f"KMEANS_CLUSTERING PASS: intra_dist = {intra_dist:.3f}, k = 3")
|