nunly 0.3.0__tar.gz

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.
Files changed (46) hide show
  1. nunly-0.3.0/.github/workflows/tests.yml +12 -0
  2. nunly-0.3.0/.gitignore +8 -0
  3. nunly-0.3.0/LICENSE +21 -0
  4. nunly-0.3.0/PKG-INFO +65 -0
  5. nunly-0.3.0/README.md +38 -0
  6. nunly-0.3.0/pyproject.toml +35 -0
  7. nunly-0.3.0/src/nunpy/__init__.py +57 -0
  8. nunly-0.3.0/src/nunpy/clustering.py +136 -0
  9. nunly-0.3.0/src/nunpy/codebook.py +245 -0
  10. nunly-0.3.0/src/nunpy/labs_code/activation_functions.py +124 -0
  11. nunly-0.3.0/src/nunpy/labs_code/lab01_numpy_basics.py +150 -0
  12. nunly-0.3.0/src/nunpy/labs_code/lab02_batch_gradient_descent.py +107 -0
  13. nunly-0.3.0/src/nunpy/labs_code/lab03_linear_regression.py +66 -0
  14. nunly-0.3.0/src/nunpy/labs_code/lab04_logistic_regression.py +78 -0
  15. nunly-0.3.0/src/nunpy/labs_code/lab05_forward_propagation.py +161 -0
  16. nunly-0.3.0/src/nunpy/labs_code/lab06_backward_propagation.py +175 -0
  17. nunly-0.3.0/src/nunpy/labs_code/lab07_tensorflow_keras.py +84 -0
  18. nunly-0.3.0/src/nunpy/labs_code/lab08_pca.py +82 -0
  19. nunly-0.3.0/src/nunpy/labs_code/lab09_image_pca.py +129 -0
  20. nunly-0.3.0/src/nunpy/labs_code/lab10_lda.py +101 -0
  21. nunly-0.3.0/src/nunpy/labs_code/lab11_kmeans.py +57 -0
  22. nunly-0.3.0/src/nunpy/labs_code/lab12_agglomerative.py +59 -0
  23. nunly-0.3.0/src/nunpy/labs_code/lab13_svm_svc.py +128 -0
  24. nunly-0.3.0/src/nunpy/labs_code/lab14_concrete.py +269 -0
  25. nunly-0.3.0/src/nunpy/regression.py +284 -0
  26. nunly-0.3.0/src/nunpy/theory/activation_functions.md +23 -0
  27. nunly-0.3.0/src/nunpy/theory/agglomerative.md +8 -0
  28. nunly-0.3.0/src/nunpy/theory/backward_propagation.md +64 -0
  29. nunly-0.3.0/src/nunpy/theory/batch_gradient_descent.md +63 -0
  30. nunly-0.3.0/src/nunpy/theory/concrete_regression.md +8 -0
  31. nunly-0.3.0/src/nunpy/theory/cross_validation.md +10 -0
  32. nunly-0.3.0/src/nunpy/theory/forward_propagation.md +43 -0
  33. nunly-0.3.0/src/nunpy/theory/image_pca.md +22 -0
  34. nunly-0.3.0/src/nunpy/theory/kmeans.md +10 -0
  35. nunly-0.3.0/src/nunpy/theory/knn.md +8 -0
  36. nunly-0.3.0/src/nunpy/theory/lda.md +20 -0
  37. nunly-0.3.0/src/nunpy/theory/linear_regression.md +35 -0
  38. nunly-0.3.0/src/nunpy/theory/logistic_regression.md +48 -0
  39. nunly-0.3.0/src/nunpy/theory/machine_learning.md +42 -0
  40. nunly-0.3.0/src/nunpy/theory/neural_network.md +42 -0
  41. nunly-0.3.0/src/nunpy/theory/numpy_basics.md +7 -0
  42. nunly-0.3.0/src/nunpy/theory/pca.md +24 -0
  43. nunly-0.3.0/src/nunpy/theory/svm.md +8 -0
  44. nunly-0.3.0/src/nunpy/theory/tensorflow_keras.md +21 -0
  45. nunly-0.3.0/tests/test_codebook.py +71 -0
  46. nunly-0.3.0/tests/test_toolkit.py +94 -0
@@ -0,0 +1,12 @@
1
+ name: tests
2
+ on: [push, pull_request]
3
+ jobs:
4
+ test:
5
+ runs-on: ubuntu-latest
6
+ steps:
7
+ - uses: actions/checkout@v4
8
+ - uses: actions/setup-python@v5
9
+ with:
10
+ python-version: "3.11"
11
+ - run: pip install -e ".[regression,dev]"
12
+ - run: pytest -q
nunly-0.3.0/.gitignore ADDED
@@ -0,0 +1,8 @@
1
+ __pycache__/
2
+ *.pyc
3
+ *.egg-info/
4
+ build/
5
+ dist/
6
+ .venv/
7
+ .pytest_cache/
8
+ .ipynb_checkpoints/
nunly-0.3.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Your Name
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
nunly-0.3.0/PKG-INFO ADDED
@@ -0,0 +1,65 @@
1
+ Metadata-Version: 2.5
2
+ Name: nunly
3
+ Version: 0.3.0
4
+ Summary: All FOML lab code (Labs 1-14) with run("pca") and help() code lookup, plus clustering and regression helpers.
5
+ Project-URL: Homepage, https://github.com/YOUR_USERNAME/nunpy
6
+ Author-email: Your Name <you@example.com>
7
+ License: MIT
8
+ License-File: LICENSE
9
+ Requires-Python: >=3.9
10
+ Requires-Dist: matplotlib
11
+ Requires-Dist: numpy
12
+ Requires-Dist: pandas
13
+ Requires-Dist: scikit-learn
14
+ Requires-Dist: scipy
15
+ Provides-Extra: cv
16
+ Requires-Dist: opencv-python; extra == 'cv'
17
+ Provides-Extra: deep
18
+ Requires-Dist: tensorflow; extra == 'deep'
19
+ Provides-Extra: dev
20
+ Requires-Dist: build; extra == 'dev'
21
+ Requires-Dist: pytest; extra == 'dev'
22
+ Requires-Dist: twine; extra == 'dev'
23
+ Provides-Extra: regression
24
+ Requires-Dist: statsmodels; extra == 'regression'
25
+ Requires-Dist: ucimlrepo; extra == 'regression'
26
+ Description-Content-Type: text/markdown
27
+
28
+ # nunpy
29
+
30
+ All FOML lab code (Labs 1-14) plus theory notes in one library.
31
+
32
+ ```python
33
+ from nunpy import *
34
+ run(pca) # code
35
+ theory(pca) # theory of one topic
36
+ theory() # ALL theory
37
+ learn(pca) # theory then code
38
+ run("lab9") # by lab number
39
+ topics() # list everything
40
+ search("eigen") # keyword search (code + theory)
41
+ help(nunpy) # everything
42
+ ```
43
+
44
+ | Lab | Topic key |
45
+ |---|---|
46
+ | 1 | numpy_basics |
47
+ | 2 | batch_gradient_descent |
48
+ | 3 | linear_regression |
49
+ | 4 | logistic_regression |
50
+ | 5 | forward_propagation |
51
+ | 6 | backward_propagation |
52
+ | 7 | tensorflow_keras |
53
+ | 8 | pca |
54
+ | 9 | image_pca |
55
+ | 10 | lda |
56
+ | 11 | kmeans |
57
+ | 12 | agglomerative |
58
+ | 13 | svm |
59
+ | 14 | concrete_regression |
60
+ | - | activation_functions |
61
+ | theory only | machine_learning, neural_network, knn, cross_validation |
62
+
63
+ Groups: pca_all, gd, regression, nn, cluster, dimred.
64
+
65
+ Install extras: `pip install "nunpy[regression,cv,deep]"`
nunly-0.3.0/README.md ADDED
@@ -0,0 +1,38 @@
1
+ # nunpy
2
+
3
+ All FOML lab code (Labs 1-14) plus theory notes in one library.
4
+
5
+ ```python
6
+ from nunpy import *
7
+ run(pca) # code
8
+ theory(pca) # theory of one topic
9
+ theory() # ALL theory
10
+ learn(pca) # theory then code
11
+ run("lab9") # by lab number
12
+ topics() # list everything
13
+ search("eigen") # keyword search (code + theory)
14
+ help(nunpy) # everything
15
+ ```
16
+
17
+ | Lab | Topic key |
18
+ |---|---|
19
+ | 1 | numpy_basics |
20
+ | 2 | batch_gradient_descent |
21
+ | 3 | linear_regression |
22
+ | 4 | logistic_regression |
23
+ | 5 | forward_propagation |
24
+ | 6 | backward_propagation |
25
+ | 7 | tensorflow_keras |
26
+ | 8 | pca |
27
+ | 9 | image_pca |
28
+ | 10 | lda |
29
+ | 11 | kmeans |
30
+ | 12 | agglomerative |
31
+ | 13 | svm |
32
+ | 14 | concrete_regression |
33
+ | - | activation_functions |
34
+ | theory only | machine_learning, neural_network, knn, cross_validation |
35
+
36
+ Groups: pca_all, gd, regression, nn, cluster, dimred.
37
+
38
+ Install extras: `pip install "nunpy[regression,cv,deep]"`
@@ -0,0 +1,35 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "nunly"
7
+ version = "0.3.0"
8
+ description = "All FOML lab code (Labs 1-14) with run(\"pca\") and help() code lookup, plus clustering and regression helpers."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "Your Name", email = "you@example.com" }]
13
+ dependencies = [
14
+ "numpy",
15
+ "pandas",
16
+ "matplotlib",
17
+ "scikit-learn",
18
+ "scipy",
19
+ ]
20
+
21
+ [project.optional-dependencies]
22
+ # needed only for load_concrete() and calculate_vif()
23
+ regression = ["ucimlrepo", "statsmodels"]
24
+ cv = ["opencv-python"]
25
+ deep = ["tensorflow"]
26
+ dev = ["pytest", "build", "twine"]
27
+
28
+ [project.urls]
29
+ Homepage = "https://github.com/YOUR_USERNAME/nunpy"
30
+
31
+ [tool.hatch.build.targets.wheel]
32
+ packages = ["src/nunpy"]
33
+
34
+ [tool.pytest.ini_options]
35
+ testpaths = ["tests"]
@@ -0,0 +1,57 @@
1
+ """nunpy: all FOML lab code (Labs 1-14) in one library."""
2
+
3
+ from .clustering import (
4
+ load_iris_df,
5
+ load_wine_df,
6
+ scale_features,
7
+ run_kmeans,
8
+ plot_clusters_2d,
9
+ plot_dendrogram,
10
+ run_agglomerative,
11
+ compare_linkages,
12
+ cluster_vs_actual,
13
+ )
14
+ from .regression import (
15
+ load_concrete,
16
+ clean_data,
17
+ engineer_features,
18
+ ORIGINAL_FEATURES,
19
+ ENGINEERED_REDUCED_FEATURES,
20
+ VIF_REDUCED_FEATURES,
21
+ select_feature_sets,
22
+ calculate_vif,
23
+ get_model_configs,
24
+ evaluate_models,
25
+ select_best_model,
26
+ plot_actual_vs_predicted,
27
+ plot_residuals,
28
+ predict_new_mix,
29
+ )
30
+
31
+ from .codebook import (
32
+ theory, learn,
33
+ run, execute, topics, search, show_all, build_doc, topic_objects, Topic,
34
+ )
35
+
36
+ __version__ = "0.3.0"
37
+
38
+ # every topic is also available as a name: ft.pca, ft.kmeans, ft.lda ...
39
+ _TOPICS = topic_objects()
40
+ globals().update(_TOPICS)
41
+
42
+ # help(nunpy) now lists every topic and prints all the code
43
+ __doc__ = build_doc()
44
+
45
+ __all__ = [
46
+ # clustering (Lab 11 + Lab 12)
47
+ "load_iris_df", "load_wine_df", "scale_features", "run_kmeans",
48
+ "plot_clusters_2d", "plot_dendrogram", "run_agglomerative",
49
+ "compare_linkages", "cluster_vs_actual",
50
+ # regression (Lab 14)
51
+ "load_concrete", "clean_data", "engineer_features",
52
+ "ORIGINAL_FEATURES", "ENGINEERED_REDUCED_FEATURES", "VIF_REDUCED_FEATURES",
53
+ "select_feature_sets", "calculate_vif", "get_model_configs",
54
+ "evaluate_models", "select_best_model", "plot_actual_vs_predicted",
55
+ "plot_residuals", "predict_new_mix",
56
+ ]
57
+ __all__ += ["run", "theory", "learn", "execute", "topics", "search", "show_all", *_TOPICS.keys()]
@@ -0,0 +1,136 @@
1
+ """Clustering helpers.
2
+
3
+ Lab 11: K-Means on the Wine dataset and on small 2-D arrays.
4
+ Lab 12: Hierarchical (agglomerative) clustering on the Iris dataset.
5
+ """
6
+
7
+ import numpy as np
8
+ import pandas as pd
9
+ import matplotlib.pyplot as plt
10
+ from sklearn.datasets import load_iris, load_wine
11
+ from sklearn.preprocessing import StandardScaler
12
+ from sklearn.cluster import KMeans, AgglomerativeClustering
13
+ from sklearn.metrics import silhouette_score
14
+ from scipy.cluster.hierarchy import linkage, dendrogram
15
+
16
+
17
+ # --------------------------------------------------------------------------
18
+ # Data loading
19
+ # --------------------------------------------------------------------------
20
+ def load_iris_df():
21
+ """Return (X as DataFrame, y as array) for the Iris dataset."""
22
+ iris = load_iris()
23
+ return pd.DataFrame(iris.data, columns=iris.feature_names), iris.target
24
+
25
+
26
+ def load_wine_df():
27
+ """Return (X as DataFrame, y as array) for the Wine dataset."""
28
+ wine = load_wine()
29
+ return pd.DataFrame(wine.data, columns=wine.feature_names), wine.target
30
+
31
+
32
+ # --------------------------------------------------------------------------
33
+ # Shared
34
+ # --------------------------------------------------------------------------
35
+ def scale_features(X):
36
+ """Standardise features (zero mean, unit variance).
37
+
38
+ Returns (X_scaled, fitted_scaler).
39
+ """
40
+ scaler = StandardScaler()
41
+ return scaler.fit_transform(X), scaler
42
+
43
+
44
+ def plot_clusters_2d(X, labels, x_index=0, y_index=1, xlabel="X1", ylabel="X2",
45
+ title="Clusters", cmap="viridis", centers=None, ax=None,
46
+ show=True):
47
+ """Scatter plot of two columns of X coloured by cluster label.
48
+
49
+ X can be a numpy array or a DataFrame. Pass ``centers`` (e.g.
50
+ ``kmeans.cluster_centers_``) to overlay centroids.
51
+ """
52
+ arr = X.to_numpy() if hasattr(X, "to_numpy") else np.asarray(X)
53
+ if ax is None:
54
+ _, ax = plt.subplots(figsize=(8, 5))
55
+ ax.scatter(arr[:, x_index], arr[:, y_index], c=labels, cmap=cmap)
56
+ if centers is not None:
57
+ c = np.asarray(centers)
58
+ ax.scatter(c[:, x_index], c[:, y_index], marker="X", s=200,
59
+ c="red", edgecolors="black", label="Centroids")
60
+ ax.legend()
61
+ ax.set_xlabel(xlabel)
62
+ ax.set_ylabel(ylabel)
63
+ ax.set_title(title)
64
+ if show:
65
+ plt.show()
66
+ return ax
67
+
68
+
69
+ # --------------------------------------------------------------------------
70
+ # Lab 11: K-Means
71
+ # --------------------------------------------------------------------------
72
+ def run_kmeans(X, n_clusters=3, scale=False, random_state=42, n_init=10):
73
+ """Fit K-Means.
74
+
75
+ Parameters
76
+ ----------
77
+ X : array-like or DataFrame
78
+ n_clusters : int
79
+ scale : bool
80
+ Standardise X before fitting (as done for the Wine data in Lab 11).
81
+
82
+ Returns
83
+ -------
84
+ model : fitted KMeans (use ``.labels_`` and ``.cluster_centers_``)
85
+ X_used : the data actually clustered (scaled if scale=True)
86
+ """
87
+ X_used = scale_features(X)[0] if scale else np.asarray(X)
88
+ model = KMeans(n_clusters=n_clusters, random_state=random_state,
89
+ n_init=n_init)
90
+ model.fit(X_used)
91
+ return model, X_used
92
+
93
+
94
+ # --------------------------------------------------------------------------
95
+ # Lab 12: Hierarchical clustering
96
+ # --------------------------------------------------------------------------
97
+ def plot_dendrogram(X, method="ward", figsize=(12, 6),
98
+ title="Agglomerative Clustering Dendrogram", show=True):
99
+ """Draw a dendrogram. Returns the linkage matrix Z."""
100
+ Z = linkage(X, method=method)
101
+ plt.figure(figsize=figsize)
102
+ dendrogram(Z)
103
+ plt.title(title)
104
+ plt.xlabel("Observations")
105
+ plt.ylabel("Merge Distance")
106
+ if show:
107
+ plt.show()
108
+ return Z
109
+
110
+
111
+ def run_agglomerative(X, n_clusters=3, linkage_method="ward"):
112
+ """Fit AgglomerativeClustering and return (model, labels)."""
113
+ model = AgglomerativeClustering(n_clusters=n_clusters,
114
+ linkage=linkage_method)
115
+ labels = model.fit_predict(X)
116
+ return model, labels
117
+
118
+
119
+ def compare_linkages(X, n_clusters=3,
120
+ methods=("single", "complete", "average", "ward")):
121
+ """Silhouette score for each linkage method.
122
+
123
+ The silhouette score ranges from -1 to 1; higher means better-separated
124
+ clusters. Returns a DataFrame with columns Linkage / Silhouette Score.
125
+ """
126
+ rows = []
127
+ for m in methods:
128
+ _, labels = run_agglomerative(X, n_clusters, m)
129
+ rows.append([m, silhouette_score(X, labels)])
130
+ return pd.DataFrame(rows, columns=["Linkage", "Silhouette Score"])
131
+
132
+
133
+ def cluster_vs_actual(y_true, labels):
134
+ """Crosstab of actual classes vs. predicted clusters."""
135
+ return pd.crosstab(np.asarray(y_true), np.asarray(labels),
136
+ rownames=["Actual Class"], colnames=["Cluster"])
@@ -0,0 +1,245 @@
1
+ """The code book: every lab's code AND theory, retrievable by name.
2
+
3
+ import nunpy as ft
4
+ ft.run("pca") # prints the PCA code
5
+ ft.run(ft.pca) # works without quotes too
6
+ ft.run("lab9") # by lab number
7
+ ft.theory("pca") # theory of one topic
8
+ ft.theory() # ALL theory
9
+ ft.learn("pca") # theory first, then code
10
+ ft.run("kmeans", execute=True)
11
+ ft.topics() # table of everything (code / theory columns)
12
+ ft.search("silhouette") # find a topic by keyword
13
+ ft.show_all() # print everything
14
+ help(ft) # same as show_all, inside Python's help viewer
15
+ """
16
+
17
+ import difflib
18
+ import re
19
+ from pathlib import Path
20
+
21
+ _CODE_DIR = Path(__file__).parent / "labs_code"
22
+ _THEORY_DIR = Path(__file__).parent / "theory"
23
+
24
+ GROUPS = {
25
+ "pca_all": ["pca", "image_pca"],
26
+ "gd": ["batch_gradient_descent", "linear_regression", "logistic_regression"],
27
+ "regression": ["linear_regression", "concrete_regression"],
28
+ "nn": ["forward_propagation", "backward_propagation", "tensorflow_keras", "activation_functions"],
29
+ "cluster": ["kmeans", "agglomerative"],
30
+ "dimred": ["pca", "image_pca", "lda"],
31
+ }
32
+
33
+
34
+ def _meta(text, keys=("TOPIC", "LAB", "TITLE", "TAGS", "NEEDS")):
35
+ out = {}
36
+ for line in text.splitlines()[:8]:
37
+ m = re.match(r"#\s*(\w+):\s*(.*)", line)
38
+ if m and m.group(1) in keys:
39
+ out[m.group(1)] = m.group(2).strip()
40
+ return out
41
+
42
+
43
+ def _load_code():
44
+ reg = {}
45
+ for p in sorted(_CODE_DIR.glob("*.py")):
46
+ text = p.read_text(encoding="utf-8")
47
+ m = _meta(text)
48
+ reg[m.get("TOPIC", p.stem)] = {"lab": m.get("LAB", ""), "title": m.get("TITLE", ""),
49
+ "tags": m.get("TAGS", ""), "file": p.name, "code": text}
50
+ return reg
51
+
52
+
53
+ def _load_theory():
54
+ reg = {}
55
+ for p in sorted(_THEORY_DIR.glob("*.md")):
56
+ text = p.read_text(encoding="utf-8")
57
+ m = _meta(text, ("TOPIC", "TITLE", "SOURCE"))
58
+ reg[m.get("TOPIC", p.stem)] = {"title": m.get("TITLE", ""), "text": text}
59
+ return reg
60
+
61
+
62
+ _REGISTRY = _load_code()
63
+ _THEORY = _load_theory()
64
+ _ALL = sorted(set(_REGISTRY) | set(_THEORY), key=lambda k: (int(_REGISTRY[k]["lab"] or 99)
65
+ if k in _REGISTRY and _REGISTRY[k]["lab"].isdigit() else 99, k))
66
+
67
+
68
+ class Topic:
69
+ """A named topic. Printing shows code (or theory if there is no code); calling runs the code."""
70
+
71
+ def __init__(self, name, keys):
72
+ self.name = name
73
+ self.keys = list(keys)
74
+
75
+ @property
76
+ def code(self):
77
+ return "\n\n".join(_REGISTRY[k]["code"] for k in self.keys if k in _REGISTRY)
78
+
79
+ @property
80
+ def theory(self):
81
+ return "\n\n".join(_THEORY[k]["text"] for k in self.keys if k in _THEORY)
82
+
83
+ def __repr__(self):
84
+ return self.code or self.theory
85
+
86
+ __str__ = __repr__
87
+
88
+ def __call__(self):
89
+ return execute(self)
90
+
91
+
92
+ def topic_objects():
93
+ """name -> Topic for every topic and group (exposed as ft.<name>)."""
94
+ objs = {k: Topic(k, [k]) for k in _ALL}
95
+ for g, keys in GROUPS.items():
96
+ objs[g] = Topic(g, keys)
97
+ return objs
98
+
99
+
100
+ def _norm(s):
101
+ return str(s).strip().lower().replace("-", "_").replace(" ", "_")
102
+
103
+
104
+ def _resolve(name):
105
+ if isinstance(name, Topic):
106
+ return name.keys
107
+ key = _norm(name)
108
+ if key in _ALL:
109
+ return [key]
110
+ if key in GROUPS:
111
+ return list(GROUPS[key])
112
+ m = re.fullmatch(r"(?:lab_?)?0*(\d+)", key)
113
+ if m:
114
+ keys = [k for k, v in _REGISTRY.items() if v["lab"] == m.group(1)]
115
+ if keys:
116
+ return keys
117
+ flat = key.replace("_", "")
118
+ hits = [k for k in _ALL if k.startswith(key) or key in k or flat in k.replace("_", "")
119
+ or (k in _REGISTRY and flat in re.sub(r"[\s_\-]", "", _REGISTRY[k]["tags"].lower()))]
120
+ if hits:
121
+ return hits
122
+ close = difflib.get_close_matches(key, _ALL + list(GROUPS), n=3)
123
+ raise KeyError(f"No topic '{name}'." + (f" Did you mean: {', '.join(close)}?" if close else "")
124
+ + " Use ft.topics() to see everything.")
125
+
126
+
127
+ def run(name=None, execute_code=False, execute=None):
128
+ """Print the code for a topic / group / lab number. Theory-only topics print their theory.
129
+
130
+ run("pca"), run("lab9"), run(ft.lda), run("kmeans", execute=True)
131
+ """
132
+ if name is None:
133
+ return topics()
134
+ if execute is not None:
135
+ execute_code = execute
136
+ keys = _resolve(name)
137
+ code = "\n\n".join(_REGISTRY[k]["code"] for k in keys if k in _REGISTRY)
138
+ if not code:
139
+ print("(no lab code for this topic - showing theory)\n")
140
+ print("\n\n".join(_THEORY[k]["text"] for k in keys if k in _THEORY))
141
+ return None
142
+ print(code)
143
+ if execute_code:
144
+ _exec(code)
145
+ return None
146
+
147
+
148
+ def theory(name=None):
149
+ """Print the theory notes for a topic / group. With no argument prints ALL theory."""
150
+ if name is None:
151
+ print("\n\n".join(f"{'=' * 78}\n{v['text']}" for v in _THEORY.values()))
152
+ return None
153
+ keys = _resolve(name)
154
+ text = "\n\n".join(_THEORY[k]["text"] for k in keys if k in _THEORY)
155
+ print(text or "No theory file for this topic yet. Try ft.run(...) for the code.")
156
+ return None
157
+
158
+
159
+ def learn(name):
160
+ """Theory first, then code, for a topic / group."""
161
+ keys = _resolve(name)
162
+ for k in keys:
163
+ if k in _THEORY:
164
+ print("=" * 78 + f"\nTHEORY: {k}\n" + "=" * 78)
165
+ print(_THEORY[k]["text"])
166
+ if k in _REGISTRY:
167
+ print("\n" + "=" * 78 + f"\nCODE: {k}\n" + "=" * 78)
168
+ print(_REGISTRY[k]["code"])
169
+ return None
170
+
171
+
172
+ def execute(name):
173
+ """Run the code of a topic and return the namespace it created."""
174
+ ns = {"__name__": "__main__"}
175
+ for k in _resolve(name):
176
+ if k in _REGISTRY:
177
+ _exec(_REGISTRY[k]["code"], ns)
178
+ return ns
179
+
180
+
181
+ def _exec(code, ns=None):
182
+ ns = ns if ns is not None else {"__name__": "__main__"}
183
+ exec(compile(code, "<nunpy>", "exec"), ns)
184
+ return ns
185
+
186
+
187
+ def topics():
188
+ """Print a table of every topic with code / theory flags."""
189
+ lines = [f"{'name':<24}{'lab':<5}{'code':<6}{'theory':<8}description", "-" * 90]
190
+ for k in _ALL:
191
+ v = _REGISTRY.get(k)
192
+ title = (v["title"] if v else _THEORY[k]["title"])
193
+ lines.append(f"{k:<24}{(v['lab'] if v else ''):<5}{'yes' if v else '-':<6}"
194
+ f"{'yes' if k in _THEORY else '-':<8}{title}")
195
+ lines.append("")
196
+ lines.append("groups: " + ", ".join(f"{g} ({len(ks)})" for g, ks in GROUPS.items()))
197
+ print("\n".join(lines))
198
+
199
+
200
+ def search(word):
201
+ """Find topics whose name, title, tags or theory contain ``word``."""
202
+ w = word.lower()
203
+ hits = []
204
+ for k in _ALL:
205
+ v = _REGISTRY.get(k, {})
206
+ blob = " ".join([k, v.get("title", ""), v.get("tags", ""),
207
+ _THEORY.get(k, {}).get("text", "")]).lower()
208
+ if w in blob:
209
+ hits.append(k)
210
+ title = v.get("title") or _THEORY[k]["title"]
211
+ print(f"{k:<24}{title}")
212
+ return hits
213
+
214
+
215
+ def show_all():
216
+ """Print the index, all theory and all code."""
217
+ print(_full_text())
218
+
219
+
220
+ def _index_text():
221
+ rows = []
222
+ for k in _ALL:
223
+ v = _REGISTRY.get(k)
224
+ tag = f"Lab {v['lab']}" if v and v["lab"] else "theory"
225
+ rows.append(f" {k:<24} {tag:<8} {(v['title'] if v else _THEORY[k]['title'])}")
226
+ grp = [f" {g:<12} -> {', '.join(ks)}" for g, ks in GROUPS.items()]
227
+ return "TOPICS\n" + "\n".join(rows) + "\n\nGROUPS\n" + "\n".join(grp)
228
+
229
+
230
+ def _full_text():
231
+ bar = "=" * 78
232
+ parts = [_index_text(), "\n\nTHEORY"]
233
+ for k, v in _THEORY.items():
234
+ parts.append(f"{bar}\n{v['text']}")
235
+ parts.append("\n\nCODE")
236
+ for k in _ALL:
237
+ if k in _REGISTRY:
238
+ v = _REGISTRY[k]
239
+ parts.append(f"{bar}\n{k} (Lab {v['lab']}) - {v['title']}\n{bar}\n{v['code']}")
240
+ return "\n\n".join(parts)
241
+
242
+
243
+ def build_doc():
244
+ """Text used as the package docstring so help(nunpy) shows everything."""
245
+ return (__doc__ or "").strip() + "\n\n" + _full_text()