From 3fb5b6cf9d03b3aea2f6a798706b4c5bcce1b8ac Mon Sep 17 00:00:00 2001 From: Fabian Hofmann Date: Wed, 18 Dec 2024 11:54:55 +0100 Subject: [PATCH] fix: support more than one initial letters in variable and constraint naming (#397) --- doc/release_notes.rst | 8 +++++--- linopy/common.py | 13 +++++++++++++ linopy/solvers.py | 5 ++++- 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/doc/release_notes.rst b/doc/release_notes.rst index c8f40bc4..87b16fc0 100644 --- a/doc/release_notes.rst +++ b/doc/release_notes.rst @@ -1,13 +1,15 @@ Release Notes ============= -.. Upcoming Version -.. ---------------- +Upcoming Version +---------------- + +* Solution files that following a different naming scheme of variables and constraints using more than on initial letter in the prefix (e.g. `col123`, `row456`) are now supported. Version 0.4.3 -------------- -* When creating slices for variables and constraints (important for the `solve` function), the slicing is now fixed in case now dimension to slice is available. +* When creating slices for variables and constraints (important for the `solve` function), the slicing is now fixed in case no dimension to slice is available. * Added a pandas priority attribute. With this change, the operation with pandas objects is now prioritizing linopy objects over pandas objects. This is useful when the using linopy objects in arithmetic operations with pandas objects, e.g. `a * x` where `a` is a pandas Series/DataFrame and `x` is a linopy variable. * The method :meth:`model.to_file ` now includes a progress argument to enable or disable the progress bar while writing. diff --git a/linopy/common.py b/linopy/common.py index 676dbb5a..42f6c3ce 100644 --- a/linopy/common.py +++ b/linopy/common.py @@ -547,6 +547,19 @@ def _remap(array, mapping): return mapping[array.ravel()].reshape(array.shape) +def count_initial_letters(word: str): + """ + Count the number of initial letters in a word. + """ + count = 0 + for char in word: + if char.isalpha(): + count += 1 + else: + break + return count + + def replace_by_map(ds, mapping): """ Replace values in a DataArray by a one-dimensional mapping. diff --git a/linopy/solvers.py b/linopy/solvers.py index efe29500..e89a6a95 100644 --- a/linopy/solvers.py +++ b/linopy/solvers.py @@ -21,6 +21,7 @@ import pandas as pd from pandas.core.series import Series +from linopy.common import count_initial_letters from linopy.constants import ( Result, Solution, @@ -138,7 +139,9 @@ def set_int_index(series: Series) -> Series: """ Convert string index to int index. """ - series.index = series.index.str[1:].astype(int) + if not series.empty: + cutoff = count_initial_letters(str(series.index[0])) + series.index = series.index.str[cutoff:].astype(int) return series