Skip to content

Commit 1df6b30

Browse files
finozzifaFabianHofmann
authored andcommitted
Expose the knitro context (#600)
* code: expose knitro context and modify _extract_values * doc: update release_notes.rst * code: include pre-commit checks
1 parent 1b08d2b commit 1df6b30

File tree

2 files changed

+16
-5
lines changed

2 files changed

+16
-5
lines changed

doc/release_notes.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@ Release Notes
44
Upcoming Version
55
----------------
66

7+
* Expose the knitro context to allow for more flexible use of the knitro python API.
8+
9+
710
Version 0.6.4
811
--------------
912

linopy/solvers.py

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1745,7 +1745,7 @@ def get_solver_solution() -> Solution:
17451745
return Result(status, solution, m)
17461746

17471747

1748-
KnitroResult = namedtuple("KnitroResult", "reported_runtime")
1748+
KnitroResult = namedtuple("KnitroResult", "knitro_context reported_runtime")
17491749

17501750

17511751
class Knitro(Solver[None]):
@@ -1808,7 +1808,13 @@ def _extract_values(
18081808
if n == 0:
18091809
return pd.Series(dtype=float)
18101810

1811-
values = get_values_fn(kc, n - 1)
1811+
try:
1812+
# Compatible with KNITRO >= 15
1813+
values = get_values_fn(kc)
1814+
except TypeError:
1815+
# Fallback for older wrappers requiring explicit indices
1816+
values = get_values_fn(kc, list(range(n)))
1817+
18121818
names = list(get_names_fn(kc))
18131819
return pd.Series(values, index=names, dtype=float)
18141820

@@ -1931,12 +1937,14 @@ def get_solver_solution() -> Solution:
19311937
knitro.KN_write_mps_file(kc, path_to_string(solution_fn))
19321938

19331939
return Result(
1934-
status, solution, KnitroResult(reported_runtime=reported_runtime)
1940+
status,
1941+
solution,
1942+
KnitroResult(knitro_context=kc, reported_runtime=reported_runtime),
19351943
)
19361944

19371945
finally:
1938-
with contextlib.suppress(Exception):
1939-
knitro.KN_free(kc)
1946+
# Intentionally keep the Knitro context alive; do not free `kc` here.
1947+
pass
19401948

19411949

19421950
mosek_bas_re = re.compile(r" (XL|XU)\s+([^ \t]+)\s+([^ \t]+)| (LL|UL|BS)\s+([^ \t]+)")

0 commit comments

Comments
 (0)