tradespace 0.1.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.
tradespace/__init__.py ADDED
@@ -0,0 +1,30 @@
1
+ """Hyperbolic trade space: learn the shape of a design trade space (the posynomial invariant form).
2
+
3
+ A scikit-learn estimator that fits a posynomial frontier to a table of conditioned metrics and
4
+ reports which of them trade off and how steeply.
5
+
6
+ Documentation: https://dynamicalsystemsgroup.github.io/tradespace/docs/
7
+ """
8
+
9
+ from .datasets import make_configured_frontier_data, make_frontier_data
10
+ from .estimator import HyperbolicTradeSpace
11
+ from .preconditioning import LogAffinePreconditioner, frontier_in_original_units
12
+ from .predictive import TradeSpaceRegressor
13
+ from .tensions import design_tensions, tension_matrix, trade_off_report
14
+ from .tuning import select_temperature
15
+
16
+ __version__ = "0.1.0"
17
+
18
+ __all__ = [
19
+ "HyperbolicTradeSpace",
20
+ "LogAffinePreconditioner",
21
+ "TradeSpaceRegressor",
22
+ "__version__",
23
+ "design_tensions",
24
+ "frontier_in_original_units",
25
+ "make_configured_frontier_data",
26
+ "make_frontier_data",
27
+ "select_temperature",
28
+ "tension_matrix",
29
+ "trade_off_report",
30
+ ]
@@ -0,0 +1,152 @@
1
+ """Invertible chart of log-metric space: ``log V`` and ``d - 1`` log-ratio coordinates ``Z``.
2
+
3
+ With ``u = log m`` and a basis ``B`` of shape ``(d-1, d)`` whose rows span ``1^perp`` (``B 1 = 0``),
4
+ ``Z = B u`` is blind to the common shift ``u + c 1`` (a shift along the diagonal) and ``log V = w.u
5
+ - beta`` carries the scale. For the ILR (Helmert) basis ``B B^T = I`` (orthonormal rows), so ``u =
6
+ B^T Z + (log V + beta - w.B^T Z) 1``; the ALR basis is invertible but not orthonormal.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import numpy as np
12
+
13
+ __all__ = ["alr_basis", "from_frontier_coordinates", "helmert_basis", "to_frontier_coordinates"]
14
+
15
+
16
+ def helmert_basis(d):
17
+ """Helmert (ILR) basis: rows ``(1,..,1,-k,0,..)/sqrt(k(k+1))`` for ``k = 1..d-1``.
18
+
19
+ Parameters
20
+ ----------
21
+ d : int
22
+ Number of metrics, ``d >= 1``.
23
+
24
+ Returns
25
+ -------
26
+ ndarray of shape (d-1, d)
27
+ ``B B^T = I`` and ``B 1 = 0`` (orthonormal rows spanning the zero-sum subspace). For
28
+ ``d = 1`` the shape is ``(0, 1)``.
29
+
30
+ Examples
31
+ --------
32
+ >>> import numpy as np
33
+ >>> B = helmert_basis(3)
34
+ >>> bool(np.allclose(B @ B.T, np.eye(2))), bool(np.allclose(B.sum(axis=1), 0))
35
+ (True, True)
36
+ """
37
+ if d < 1:
38
+ raise ValueError("d must be >= 1")
39
+ B = np.zeros((d - 1, d))
40
+ for k in range(1, d):
41
+ B[k - 1, :k] = 1.0
42
+ B[k - 1, k] = -float(k)
43
+ B[k - 1] /= np.sqrt(k * (k + 1.0))
44
+ return B
45
+
46
+
47
+ def alr_basis(d):
48
+ """Additive log-ratio basis with the last metric as reference: ``Z_j = u_j - u_d``.
49
+
50
+ Parameters
51
+ ----------
52
+ d : int
53
+ Number of metrics, ``d >= 1``.
54
+
55
+ Returns
56
+ -------
57
+ ndarray of shape (d-1, d)
58
+ ``[I | -1]``; ``B 1 = 0`` but ``B B^T != I`` (not orthonormal).
59
+
60
+ Examples
61
+ --------
62
+ >>> alr_basis(3).tolist()
63
+ [[1.0, 0.0, -1.0], [0.0, 1.0, -1.0]]
64
+ """
65
+ if d < 1:
66
+ raise ValueError("d must be >= 1")
67
+ return np.hstack([np.eye(d - 1), -np.ones((d - 1, 1))])
68
+
69
+
70
+ def to_frontier_coordinates(U, w, beta, B):
71
+ """Map log metrics to chart coordinates ``(Z, log V)``.
72
+
73
+ Parameters
74
+ ----------
75
+ U : ndarray of shape (n, d)
76
+ Log metrics; rows with ``-inf`` (zero metrics) give ``Z = nan`` and ``log V = -inf``.
77
+ w : ndarray of shape (d,)
78
+ Exponents on the simplex.
79
+ beta : float
80
+ Offset.
81
+ B : ndarray of shape (d-1, d)
82
+ Chart basis.
83
+
84
+ Returns
85
+ -------
86
+ Z : ndarray of shape (n, d-1)
87
+ ``U @ B.T``.
88
+ log_v : ndarray of shape (n,)
89
+ ``U @ w - beta``.
90
+
91
+ Examples
92
+ --------
93
+ >>> import numpy as np
94
+ >>> U = np.array([[0.0, 1.0], [2.0, 2.0]])
95
+ >>> Z, lv = to_frontier_coordinates(
96
+ ... U, np.array([0.5, 0.5]), 0.5, helmert_basis(2))
97
+ >>> Z.round(4).tolist(), lv.round(4).tolist()
98
+ ([[-0.7071], [0.0]], [0.0, 1.5])
99
+ """
100
+ U = np.atleast_2d(np.asarray(U, dtype=float))
101
+ w = np.asarray(w, dtype=float)
102
+ bad = (-np.inf == U).any(axis=1)
103
+ Uf = np.where(bad[:, None], 0.0, U)
104
+ Z = Uf @ B.T
105
+ log_v = Uf @ w - beta
106
+ Z[bad] = np.nan
107
+ log_v[bad] = -np.inf
108
+ return Z, log_v
109
+
110
+
111
+ def from_frontier_coordinates(Z, log_v, w, beta, B):
112
+ """Inverse of ``to_frontier_coordinates``: ``u = C Z + (log V + beta - w.C Z) 1``.
113
+
114
+ Parameters
115
+ ----------
116
+ Z : ndarray of shape (n, d-1)
117
+ log_v : ndarray of shape (n,)
118
+ w : ndarray of shape (d,)
119
+ Exponents on the simplex (``sum w = 1``).
120
+ beta : float
121
+ B : ndarray of shape (d-1, d)
122
+
123
+ Returns
124
+ -------
125
+ ndarray of shape (n, d)
126
+ Log metrics ``U``. Rows with non-finite ``Z`` or ``log V`` are returned as ``nan``.
127
+
128
+ Notes
129
+ -----
130
+ ``C = pinv(B)`` (``B^T`` for ILR) satisfies ``B C = I``, and ``u - C Z`` lies in
131
+ ``span(1)``; the scale is fixed by ``w.u = log V + beta``.
132
+
133
+ Examples
134
+ --------
135
+ >>> import numpy as np
136
+ >>> B, w = helmert_basis(3), np.array([0.2, 0.3, 0.5])
137
+ >>> U = np.array([[0.1, -0.4, 0.7]])
138
+ >>> Z, lv = to_frontier_coordinates(U, w, 0.2, B)
139
+ >>> bool(np.allclose(from_frontier_coordinates(Z, lv, w, 0.2, B), U))
140
+ True
141
+ """
142
+ Z = np.asarray(Z, dtype=float).reshape(np.size(log_v), np.shape(B)[0])
143
+ log_v = np.atleast_1d(np.asarray(log_v, dtype=float))
144
+ w = np.asarray(w, dtype=float)
145
+ d = w.size
146
+ bad = ~np.isfinite(log_v) | ~np.isfinite(Z).all(axis=1)
147
+ Zf = np.where(bad[:, None], 0.0, Z)
148
+ base = Zf @ np.linalg.pinv(B).T if d > 1 else np.zeros((Z.shape[0], 1))
149
+ shift = np.where(bad, 0.0, log_v) + beta - base @ w
150
+ U = base + shift[:, None]
151
+ U[bad] = np.nan
152
+ return U
tradespace/datasets.py ADDED
@@ -0,0 +1,258 @@
1
+ """Synthetic frontier data with a planted monomial frontier."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+ from sklearn.utils import check_random_state
7
+
8
+ from .coordinates import from_frontier_coordinates, helmert_basis
9
+
10
+ __all__ = ["make_configured_frontier_data", "make_frontier_data"]
11
+
12
+
13
+ def _planted_exponents(exponents, d, rng):
14
+ if exponents is None:
15
+ # bounded away from the boundary: every w_j >= 0.5/d
16
+ return 0.5 * rng.dirichlet(np.ones(d)) + 0.5 / d
17
+ w = np.asarray(exponents, dtype=float)
18
+ if w.shape != (d,) or np.any(w < 0) or abs(w.sum() - 1.0) > 1e-9:
19
+ raise ValueError("exponents must be a nonnegative vector of length n_features summing to 1")
20
+ return w
21
+
22
+
23
+ def _planted_terms(exponents, n_terms, d, rng, min_apart=0.3, tries=1000):
24
+ if exponents is not None:
25
+ W = np.asarray(exponents, dtype=float)
26
+ if W.shape != (n_terms, d) or np.any(W < 0) or not np.allclose(W.sum(axis=1), 1.0):
27
+ raise ValueError(
28
+ "exponents must be (n_terms, n_features), nonnegative, rows summing to 1"
29
+ )
30
+ return W
31
+ for _ in range(tries):
32
+ W = rng.dirichlet(np.ones(d), n_terms)
33
+ if np.abs(W[:, None] - W[None]).sum(-1)[np.triu_indices(n_terms, 1)].min() >= min_apart:
34
+ return W
35
+ raise ValueError(f"no {n_terms} exponent vectors {min_apart} apart (L1) found in d={d}")
36
+
37
+
38
+ def _frontier_mask(n, fraction, rng):
39
+ if not 0.0 < fraction <= 1.0:
40
+ raise ValueError("frontier_fraction must be in (0, 1]")
41
+ mask = np.zeros(n, dtype=bool)
42
+ mask[rng.permutation(n)[: max(1, round(fraction * n))]] = True
43
+ return mask
44
+
45
+
46
+ def _identifiable(mask, term, log_v, noise, d, rng):
47
+ """Put at least ``d + 1`` frontier rows on every planted term (extra rows, drawn from rng)."""
48
+ for k in range(int(term.max()) + 1):
49
+ own = term == k
50
+ extra = np.flatnonzero(own & ~mask)
51
+ need = d + 1 - int((own & mask).sum())
52
+ if need > 0:
53
+ if need > extra.size:
54
+ raise ValueError(
55
+ f"term {k} has {own.sum()} rows, fewer than n_features + 1 = {d + 1}; "
56
+ "increase n_samples"
57
+ )
58
+ pick = rng.permutation(extra)[:need]
59
+ mask[pick] = True
60
+ log_v[pick] = noise * rng.standard_normal(need)
61
+
62
+
63
+ def make_frontier_data(
64
+ n_samples,
65
+ n_features,
66
+ exponents=None,
67
+ log_offset=0.0,
68
+ frontier_fraction=0.3,
69
+ interior_scale=1.0,
70
+ noise=0.0,
71
+ random_state=None,
72
+ n_terms=1,
73
+ ):
74
+ """Sample metrics around a planted monomial frontier ``prod m_j^{w_j} = e^{beta}``.
75
+
76
+ Parameters
77
+ ----------
78
+ n_samples : int
79
+ Number of rows.
80
+ n_features : int
81
+ Number of metrics ``d`` (``d = 1`` gives a single column and no ``Z``).
82
+ exponents : array-like of shape (n_features,) or (n_terms, n_features), optional
83
+ Planted exponents on the simplex (one row per term for ``n_terms > 1``). Default for
84
+ ``n_terms = 1``: a seeded random point with every ``w_j >= 0.5/d``. Default for
85
+ ``n_terms = K > 1``: K Dirichlet(1) draws, redrawn (at most 1000 tries, then
86
+ ``ValueError``) until every pair is at least 0.3 apart in L1.
87
+ log_offset : float, default=0.0
88
+ Planted ``beta``.
89
+ frontier_fraction : float, default=0.3
90
+ Fraction of rows placed on the frontier (``log V`` equal to ``noise * N(0,1)``).
91
+ interior_scale : float, default=1.0
92
+ Interior rows have ``log V = -Exp(interior_scale)`` (mean depth ``interior_scale``).
93
+ noise : float, default=0.0
94
+ Standard deviation of the log-V noise of frontier rows.
95
+ random_state : int, RandomState or None, default=None
96
+ Seed.
97
+ n_terms : int, default=1
98
+ Number of planted monomials K. ``1`` reproduces the one-term frontier exactly; ``K > 1``
99
+ plants the envelope ``Phi(u) = max_k (w_k . u - beta)`` and puts ``log V = Phi(u)``.
100
+
101
+ Returns
102
+ -------
103
+ X : ndarray of shape (n_samples, n_features)
104
+ Strictly positive metrics.
105
+ info : dict
106
+ Keys ``exponents`` (shape ``(d,)`` at K = 1, ``(K, d)`` otherwise), ``log_offset``,
107
+ ``basis`` (ILR chart), ``frontier_mask``, ``Z``, ``log_v``, ``noise``, ``interior_scale``;
108
+ for ``n_terms > 1`` also ``term``, an integer array of shape ``(n_samples,)`` holding
109
+ ``argmax_k w_k . log x`` (the term each row lies on or under).
110
+
111
+ Notes
112
+ -----
113
+ For ``n_terms > 1`` every planted term gets at least ``n_features + 1`` frontier rows
114
+ (identifiability: a term with fewer frontier rows than dimensions is not determined by them).
115
+ If a term falls short after the draw, further rows of that term, chosen by the seeded
116
+ generator, are moved onto the frontier (so the frontier fraction can slightly exceed
117
+ ``frontier_fraction``); a term with too few rows overall raises ``ValueError``.
118
+
119
+ ``Z ~ N(0, I)`` and the rows are mapped back through the ILR chart; the frontier is
120
+ identifiable when the Z-hull of the frontier rows contains 0. For K > 1 the
121
+ rows are ``u = C Z + s 1`` with ``s = log V + beta - max_k w_k . C Z`` (the K-term form of
122
+ ``from_frontier_coordinates``; ``sum w_k = 1`` makes ``Phi(u) = log V`` exact).
123
+
124
+ Examples
125
+ --------
126
+ >>> X, info = make_frontier_data(200, 3, random_state=0)
127
+ >>> X.shape, bool((X > 0).all()), round(float(info["exponents"].sum()), 6)
128
+ ((200, 3), True, 1.0)
129
+ >>> X, info = make_frontier_data(200, 4, n_terms=3, random_state=0)
130
+ >>> info["exponents"].shape, int(info["term"].max()) < 3
131
+ ((3, 4), True)
132
+ """
133
+ if n_samples < 1 or n_features < 1 or n_terms < 1:
134
+ raise ValueError("n_samples, n_features and n_terms must be >= 1")
135
+ if noise < 0 or interior_scale <= 0:
136
+ raise ValueError("noise must be >= 0 and interior_scale > 0")
137
+ rng = check_random_state(random_state)
138
+ d = int(n_features)
139
+ if n_terms == 1:
140
+ w = _planted_exponents(exponents, d, rng)
141
+ else:
142
+ w = _planted_terms(exponents, n_terms, d, rng)
143
+ B = helmert_basis(d)
144
+ mask = _frontier_mask(n_samples, frontier_fraction, rng)
145
+ Z = rng.standard_normal((n_samples, d - 1))
146
+ log_v = np.where(
147
+ mask,
148
+ noise * rng.standard_normal(n_samples),
149
+ -rng.exponential(interior_scale, n_samples),
150
+ )
151
+ if n_terms == 1:
152
+ U = from_frontier_coordinates(Z, log_v, w, log_offset, B)
153
+ else:
154
+ base = Z @ np.linalg.pinv(B).T
155
+ term, top = (base @ w.T).argmax(axis=1), (base @ w.T).max(axis=1)
156
+ _identifiable(mask, term, log_v, noise, d, rng)
157
+ U = base + (log_v + log_offset - top)[:, None]
158
+ X = np.exp(U)
159
+ info = {
160
+ "exponents": w,
161
+ "log_offset": float(log_offset),
162
+ "basis": B,
163
+ "frontier_mask": mask,
164
+ "Z": Z,
165
+ "log_v": log_v,
166
+ "noise": float(noise),
167
+ "interior_scale": float(interior_scale),
168
+ }
169
+ if n_terms > 1:
170
+ info["term"] = term
171
+ return X, info
172
+
173
+
174
+ def make_configured_frontier_data(
175
+ n_samples,
176
+ n_features,
177
+ n_config,
178
+ exponents=None,
179
+ log_offset=0.0,
180
+ frontier_fraction=0.3,
181
+ interior_scale=1.0,
182
+ nonlinearity=0.1,
183
+ noise=0.0,
184
+ random_state=None,
185
+ ):
186
+ """Frontier data whose metrics are a known smooth map of a configuration.
187
+
188
+ Parameters
189
+ ----------
190
+ n_samples, n_features : int
191
+ Rows and metrics ``d``.
192
+ n_config : int
193
+ Number of configuration variables, ``>= 2``.
194
+ exponents, log_offset, frontier_fraction, noise, random_state :
195
+ As in ``make_frontier_data``.
196
+ interior_scale : float, default=1.0
197
+ Depth scale: ``log V = -interior_scale * (c . g)^2`` for a fixed unit vector ``g``;
198
+ frontier rows are projected onto ``c . g = 0`` so they lie exactly on the frontier.
199
+ nonlinearity : float, default=0.1
200
+ Amplitude of the nonlinear term in ``Z(c) = c A + nonlinearity * sin(c A2)``.
201
+
202
+ Returns
203
+ -------
204
+ X_config : ndarray of shape (n_samples, n_config)
205
+ Configurations ``c ~ N(0, I)`` (frontier rows projected).
206
+ Y_metrics : ndarray of shape (n_samples, n_features)
207
+ Strictly positive metrics ``exp(from_frontier_coordinates(Z(c), log V(c) + noise))``.
208
+ info : dict
209
+ As in ``make_frontier_data`` (without noise-free redundancy), plus ``config_map``: a
210
+ callable ``c -> (Z, log_v)`` giving the noise-free truth for any configuration, and
211
+ ``Z``, ``log_v`` of the training rows (noise included in ``log_v`` for frontier rows).
212
+
213
+ Examples
214
+ --------
215
+ >>> C, Y, info = make_configured_frontier_data(100, 3, 4, random_state=1)
216
+ >>> C.shape, Y.shape, bool((Y > 0).all())
217
+ ((100, 4), (100, 3), True)
218
+ >>> Z, lv = info["config_map"](C)
219
+ >>> bool(abs(lv[info["frontier_mask"]]).max() < 1e-12)
220
+ True
221
+ """
222
+ if n_samples < 1 or n_features < 1:
223
+ raise ValueError("n_samples and n_features must be >= 1")
224
+ if n_config < 2:
225
+ raise ValueError("n_config must be >= 2")
226
+ if noise < 0 or interior_scale <= 0:
227
+ raise ValueError("noise must be >= 0 and interior_scale > 0")
228
+ rng = check_random_state(random_state)
229
+ d, k = int(n_features), int(n_config)
230
+ w = _planted_exponents(exponents, d, rng)
231
+ B = helmert_basis(d)
232
+ mask = _frontier_mask(n_samples, frontier_fraction, rng)
233
+ g = rng.standard_normal(k)
234
+ g /= np.linalg.norm(g)
235
+ A = rng.standard_normal((k, d - 1))
236
+ A2 = rng.standard_normal((k, d - 1))
237
+ C = rng.standard_normal((n_samples, k))
238
+ C[mask] -= np.outer(C[mask] @ g, g)
239
+
240
+ def config_map(c):
241
+ c = np.atleast_2d(np.asarray(c, dtype=float))
242
+ return c @ A + nonlinearity * np.sin(c @ A2), -interior_scale * (c @ g) ** 2
243
+
244
+ Z, log_v = config_map(C)
245
+ log_v = log_v + np.where(mask, noise * rng.standard_normal(n_samples), 0.0)
246
+ Y = np.exp(from_frontier_coordinates(Z, log_v, w, log_offset, B))
247
+ info = {
248
+ "exponents": w,
249
+ "log_offset": float(log_offset),
250
+ "basis": B,
251
+ "frontier_mask": mask,
252
+ "Z": Z,
253
+ "log_v": log_v,
254
+ "noise": float(noise),
255
+ "interior_scale": float(interior_scale),
256
+ "config_map": config_map,
257
+ }
258
+ return C, Y, info