Repository navigation
Expand file tree
/
Copy pathoptimize.py
More file actions
471 lines (393 loc) · 16.7 KB
/
Copy pathoptimize.py
File metadata and controls
471 lines (393 loc) · 16.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
# WriterAgent - AI Writing Assistant for LibreOffice
# Copyright (c) 2026 KeithCu (modifications and relicensing)
#
# SPDX-License-Identifier: GPL-3.0-or-later
"""Trusted venv optimize compute — runs in user venv worker."""
from __future__ import annotations
from collections import Counter
import math
from typing import Any
from plugin.scripting.calc_functions_common import (
ANALYSIS_DATA_TABLE_ROWS,
)
from plugin.scripting.helper_registry import helper
from plugin.scripting.venv.coerce import (
auto_numeric,
coerce_bool,
coerce_optional_float,
coerce_str_list,
resolve_df,
table_from_df,
)
from plugin.scripting.venv.results import HelperError, catch_helper_error, error_result
from plugin.scripting.venv.trusted_dispatch import (
missing_package_error,
ok_result,
run_domain,
)
_BOUNDS_ERROR = "bounds must be one [low, high] pair or a list of one pair per variable"
def _is_bound_scalar(x: Any) -> bool:
import numpy as np
if x is None:
return True
if isinstance(x, bool):
return False
if isinstance(x, (int, float, np.integer, np.floating)):
return math.isfinite(float(x))
return False
def _is_bound_pair(item: Any) -> bool:
return (
isinstance(item, (list, tuple))
and len(item) == 2
and _is_bound_scalar(item[0])
and _is_bound_scalar(item[1])
)
def _linprog_bounds(bounds: Any, n_vars: int) -> Any:
if bounds is None:
return None
# A length-2 sequence of scalars is one pair for every variable, including when n_vars == 2.
if _is_bound_pair(bounds):
return (bounds[0], bounds[1])
if (
isinstance(bounds, (list, tuple))
and len(bounds) == n_vars
and all(_is_bound_pair(item) for item in bounds)
):
return [(item[0], item[1]) for item in bounds]
raise HelperError("INVALID_PARAM", _BOUNDS_ERROR)
def _constraint_bounds(b: Any, n_constraints: int) -> Any:
"""One RHS per constraint column, or None when ``b`` cannot be aligned.
``b`` is a column on the same grid as the variables, so its length is the
row count. That equals the constraint count only for a square tableau.
The template default ``a_cols=["a1"]`` is one constraint on many variable
rows: those rows repeat the same bound, and that number is the RHS.
When the lengths differed, the old fallback transposed the coefficient
matrix and set ``b_ub`` to zeros, discarding the user's bounds. ``linprog``
then failed with ``OPTIMIZATION_FAILED``.
"""
import numpy as np
values = np.asarray(b, dtype=float).reshape(-1)
if values.shape[0] == n_constraints:
return values
if n_constraints == 1 and values.size > 0 and bool(np.allclose(values, values[0])):
return values[:1].copy()
return None
def _with_flags(result: dict[str, Any], flags: list[str]) -> dict[str, Any]:
# An empty list must not create a flags key. Callers treat a missing key as none.
if flags:
result["flags"] = flags
return result
@helper("optimize")
@catch_helper_error
def linear_programming(
data: Any,
*,
c_col: Any,
a_cols: Any,
b_col: Any,
bounds: Any = (0, None),
maximize: Any = False,
headers: bool = True,
header_row: int = 0,
sheet_hint: str | None = None,
) -> dict[str, Any]:
"""Solve a linear program with ``scipy.optimize.linprog``.
Each row is a variable (``c`` is its objective coefficient). Each name in
``a_cols`` is one ``A_ub x <= b`` constraint across those variables.
``b`` must supply one bound per constraint column. A single constraint
column may repeat that same bound on every row.
``bounds`` may be one pair for every variable or one pair per original row;
pairs for rows dropped as non-numeric are ignored.
"""
helper = "linear_programming"
import numpy as np
import pandas as pd
try:
from scipy import optimize as scipy_optimize
except ImportError:
return missing_package_error(helper, "scipy")
for name, raw in (("c_col", c_col), ("b_col", b_col)):
if not isinstance(raw, str) or not raw.strip():
return error_result("INVALID_PARAM", f"{name} must be a string, got {raw!r}", helper=helper)
c_col, b_col = c_col.strip(), b_col.strip()
a_cols_list = coerce_str_list(a_cols, name="a_cols")
if not a_cols_list:
return error_result("INVALID_PARAM", "a_cols is required", helper=helper)
all_lp_cols = [c_col, b_col, *a_cols_list]
duplicates = [col_name for col_name, count in Counter(all_lp_cols).items() if count > 1]
if duplicates:
names = ", ".join(duplicates)
return error_result(
"INVALID_PARAM",
f"c_col, b_col, and a_cols must name distinct columns; repeated: {names}",
helper=helper,
)
maximize_val = coerce_bool(maximize, name="maximize", default=False)
coerced = resolve_df(data, headers=headers, header_row=header_row, sheet_hint=sheet_hint)
df = coerced.df
available = [str(c) for c in df.columns]
needed_cols = [c_col, b_col] + a_cols_list
missing = [c for c in needed_cols if c not in df.columns]
if missing:
return error_result(
"UNKNOWN_COLUMN",
f"Columns not found: {', '.join(missing)}. Available: {', '.join(available)}",
helper=helper,
)
numeric_df = df[needed_cols].apply(pd.to_numeric, errors="coerce")
# Bounds may be one pair per original row; keep the mask that dropped
# non-numeric rows so the pairs stay aligned.
keep_mask = numeric_df.notna().all(axis=1)
clean_df = numeric_df[keep_mask]
if clean_df.empty:
return error_result("INSUFFICIENT_DATA", "No data for linear programming", helper=helper)
# Objective coefficients, one per variable row.
c = clean_df[c_col].to_numpy(dtype=float)
if maximize_val:
c = -c
# a-columns are constraints, so transpose to linprog's (constraints, variables).
coeff = clean_df[a_cols_list].to_numpy(dtype=float)
n_constraints = int(coeff.shape[1])
A_ub = coeff.T
b_ub = _constraint_bounds(clean_df[b_col].to_numpy(dtype=float), n_constraints)
if b_ub is None:
return error_result(
"SHAPE_MISMATCH",
(
"linear_programming constraint shapes do not match: "
f"{len(c)} variable rows and {n_constraints} constraint column(s) "
f"({', '.join(str(name) for name in a_cols_list)}). "
"Each row is a variable and each a-column is a <= constraint, so b "
"needs one bound per constraint column. A single constraint column "
"may repeat that same bound on every row. Mismatched b is rejected "
"instead of being replaced with zeros."
),
helper=helper,
details={
"n_variables": int(len(c)),
"n_constraints": n_constraints,
"n_rows": int(len(clean_df)),
},
)
if (
isinstance(bounds, (list, tuple))
and len(bounds) == len(keep_mask)
and all(isinstance(item, (list, tuple)) for item in bounds)
):
bounds = [item for item, keep in zip(bounds, keep_mask) if bool(keep)]
lp_bounds = _linprog_bounds(bounds, len(c))
try:
res = scipy_optimize.linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=lp_bounds)
except Exception as e:
return error_result("OPTIMIZATION_FAILED", str(e), helper=helper)
if not res.success:
code = {2: "INFEASIBLE", 3: "UNBOUNDED"}.get(int(res.status), "OPTIMIZATION_FAILED")
return error_result(code, res.message, helper=helper, details={"solver_status": int(res.status)})
solution_df = pd.DataFrame({
"variable_index": range(len(res.x)),
"optimal_value": np.round(res.x, 4)
})
table = table_from_df(solution_df, name="lp_solution", max_rows=ANALYSIS_DATA_TABLE_ROWS)
metrics = {
"objective_value": float(-res.fun) if maximize_val else float(res.fun),
"status": res.message,
"iterations": int(res.nit)
}
return ok_result(helper, metrics=metrics, tables=[table], metadata=coerced.metadata)
@helper("optimize")
@catch_helper_error
def optimize_portfolio(
data: Any,
*,
returns_col: Any = None,
target_return: Any = None,
risk_free_rate: Any = 0.0,
headers: bool = True,
header_row: int = 0,
sheet_hint: str | None = None,
) -> dict[str, Any]:
"""Long-only minimum-variance portfolio optimization.
Weights are in [0, 1] and sum to 1. target_return is an optional
per-period equality constraint. risk_free_rate does not affect weights;
not annualized; no short sales. When returns_col is omitted, date-named
columns and monotonic unique integer columns are skipped, and each skip
is a flags entry.
"""
helper = "optimize_portfolio"
import numpy as np
import pandas as pd
try:
from scipy import optimize as scipy_optimize
except ImportError:
return missing_package_error(helper, "scipy")
returns_col_list = coerce_str_list(returns_col, name="returns_col")
target_return_val = coerce_optional_float(target_return, name="target_return")
rf_val = coerce_optional_float(risk_free_rate, name="risk_free_rate") or 0.0
coerced = resolve_df(data, headers=headers, header_row=header_row, sheet_hint=sheet_hint)
df = coerced.df
flags: list[str] = []
numeric_cols = auto_numeric(df, returns_col_list, flags)
if not numeric_cols or len(numeric_cols) < 2:
return _with_flags(
error_result("INSUFFICIENT_DATA", "Need at least two numeric columns (assets).", helper=helper),
flags,
)
returns_raw = df[numeric_cols].apply(pd.to_numeric, errors="coerce")
n_before_drop = len(returns_raw)
returns = returns_raw.dropna()
dropped_rows = n_before_drop - len(returns)
if dropped_rows > 0:
flags.append(f"Dropped {dropped_rows} return rows with a missing value")
if len(returns) < 2:
return error_result("INSUFFICIENT_DATA", "Need at least two complete return rows.", helper=helper)
cov_matrix = returns.cov().to_numpy()
mean_returns = returns.mean().to_numpy()
scale = float(np.mean(np.diag(cov_matrix)))
if not np.isfinite(cov_matrix).all() or not math.isfinite(scale) or scale <= 0:
return error_result("INSUFFICIENT_DATA", "Return covariance is not positive.", helper=helper)
scaled_cov = cov_matrix / scale
num_assets = len(numeric_cols)
# Objective: Minimize scaled portfolio variance
def scaled_portfolio_variance(weights: Any) -> Any:
return weights.T @ scaled_cov @ weights
constraints: list[dict[str, Any]] = [
{"type": "eq", "fun": lambda x: np.sum(x) - 1.0}
]
if target_return_val is not None:
constraints.append({
"type": "eq",
"fun": lambda x: np.sum(mean_returns * x) - target_return_val
})
bounds = tuple((0.0, 1.0) for _unused in range(num_assets))
min_mean = float(np.min(mean_returns))
max_mean = float(np.max(mean_returns))
init_guess = np.array(num_assets * [1.0 / num_assets])
if target_return_val is not None:
if target_return_val < min_mean - 1e-12 or target_return_val > max_mean + 1e-12:
return error_result(
"INFEASIBLE_TARGET",
f"target_return {target_return_val} is outside the achievable long-only "
f"range [{min_mean}, {max_mean}].",
helper=helper,
details={"min_mean_return": min_mean, "max_mean_return": max_mean},
)
# Equal weights violate the target equality. Two assets at the mean
# extremes sum to 1 and hit the target exactly, which is a feasible start.
if max_mean > min_mean:
top = min(1.0, max(0.0, (target_return_val - min_mean) / (max_mean - min_mean)))
init_guess = np.zeros(num_assets)
init_guess[int(np.argmax(mean_returns))] = top
init_guess[int(np.argmin(mean_returns))] += 1.0 - top
# Portfolio objective: daily variances sit under SLSQP's default ftol,
# so the equal-weight start is reported as optimal (nit == 1, about 34%
# more volatility on a four-asset daily book). Scaling makes the objective
# O(1); ftol=1e-12 covers a still-flat direction. Volatility uses the
# original covariance because result.fun is scaled.
try:
result = scipy_optimize.minimize(
scaled_portfolio_variance,
init_guess,
method="SLSQP",
bounds=bounds,
constraints=constraints,
options={"ftol": 1e-12},
)
except Exception as e:
return error_result("OPTIMIZATION_FAILED", str(e), helper=helper)
if not result.success:
return error_result("OPTIMIZATION_FAILED", result.message, helper=helper)
raw_weights = result.x
expected_return = float(np.sum(mean_returns * raw_weights))
variance = float(raw_weights.T @ cov_matrix @ raw_weights)
expected_volatility = float(math.sqrt(max(variance, 0.0)))
sharpe_ratio = float((expected_return - rf_val) / expected_volatility) if expected_volatility > 0 else 0.0
weights_df = pd.DataFrame({
"asset": numeric_cols,
"weight": np.round(raw_weights, 4)
})
table = table_from_df(weights_df, name="portfolio_weights", max_rows=ANALYSIS_DATA_TABLE_ROWS)
metrics = {
"expected_return": expected_return,
"expected_volatility": expected_volatility,
"sharpe_ratio": sharpe_ratio,
}
return _with_flags(
ok_result(helper, metrics=metrics, tables=[table], metadata=coerced.metadata),
flags,
)
@helper("optimize")
@catch_helper_error
def solve_scheduling_problem(
data: Any,
*,
cost_cols: Any = None,
headers: bool = True,
header_row: int = 0,
sheet_hint: str | None = None,
) -> dict[str, Any]:
"""Solve an assignment problem (e.g. workers to tasks) using linear_sum_assignment.
When cost_cols is omitted, date-named columns and monotonic unique integer
columns are skipped, and each skip is a flags entry.
"""
helper = "solve_scheduling_problem"
import pandas as pd
try:
from scipy import optimize as scipy_optimize
except ImportError:
return missing_package_error(helper, "scipy")
cost_cols_list = coerce_str_list(cost_cols, name="cost_cols")
coerced = resolve_df(data, headers=headers, header_row=header_row, sheet_hint=sheet_hint)
df = coerced.df
flags: list[str] = []
numeric_cols = auto_numeric(df, cost_cols_list, flags)
if not numeric_cols:
return _with_flags(
error_result("INSUFFICIENT_DATA", "Need numeric columns for cost matrix.", helper=helper),
flags,
)
df_cost = df[numeric_cols].apply(pd.to_numeric, errors="coerce")
df_clean = df_cost.dropna()
if df_clean.empty:
return error_result("INSUFFICIENT_DATA", "Need numeric columns for cost matrix.", helper=helper)
n_rows = len(df_clean)
n_cols = len(numeric_cols)
unassigned_rows = max(0, n_rows - n_cols)
unassigned_columns = max(0, n_cols - n_rows)
if unassigned_rows > 0:
flags.append(f"{unassigned_rows} rows were not assigned because there are more rows than columns")
if unassigned_columns > 0:
if unassigned_columns == 1:
flags.append("1 column was not assigned because there are more columns than rows")
else:
flags.append(f"{unassigned_columns} columns were not assigned because there are more columns than rows")
cost_matrix = df_clean.to_numpy(dtype=float)
try:
row_ind, col_ind = scipy_optimize.linear_sum_assignment(cost_matrix)
except Exception as e:
return error_result("OPTIMIZATION_FAILED", str(e), helper=helper)
total_cost = float(cost_matrix[row_ind, col_ind].sum())
kept_index = list(df_clean.index)
assigned_row_labels = [kept_index[i] for i in row_ind]
assignment_df = pd.DataFrame({
"row_index": assigned_row_labels,
"assigned_column": [numeric_cols[i] for i in col_ind],
"cost": cost_matrix[row_ind, col_ind]
})
table = table_from_df(assignment_df, name="optimal_assignment", max_rows=ANALYSIS_DATA_TABLE_ROWS)
metrics = {
"total_cost": total_cost,
"assignments": len(row_ind),
"unassigned_rows": unassigned_rows,
"unassigned_columns": unassigned_columns,
}
return _with_flags(
ok_result(helper, metrics=metrics, tables=[table], metadata=coerced.metadata),
flags,
)
def run_optimize(
spec: dict[str, Any] | str,
data: Any,
context: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Spec-driven dispatcher — single trusted entry for host RPC."""
return run_domain("optimize", spec, data, context=context)