-
Notifications
You must be signed in to change notification settings - Fork 222
update variable type #1783
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
update variable type #1783
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -35,6 +35,27 @@ class VType(str, Enum): | |
| SEMI_CONTINUOUS = VType.SEMI_CONTINUOUS | ||
|
|
||
|
|
||
| def _to_vtype(value): | ||
| """ | ||
| Coerces a variable type to a :py:class:`VType` member. | ||
| Besides VType members, the single character codes are accepted as ``str`` | ||
| or ``bytes``. | ||
| """ | ||
| if isinstance(value, VType): | ||
| return value | ||
| try: | ||
| # UnicodeDecodeError and the enum lookup failure are both ValueError. | ||
| return VType( | ||
| value.decode() if isinstance(value, (bytes, bytearray)) else value | ||
| ) | ||
| except ValueError: | ||
| valid = ", ".join(repr(t.value) for t in VType) | ||
| raise ValueError( | ||
| f"Invalid variable type {value!r}. Expected a VType member or " | ||
| f"one of {valid}." | ||
| ) from None | ||
|
|
||
|
|
||
| class CType(str, Enum): | ||
| """ | ||
| The sense of a constraint is either LE, GE or EQ. | ||
|
|
@@ -94,8 +115,10 @@ class Variable: | |
| ---------- | ||
| VariableName : str | ||
| Name of the Variable. | ||
| VariableType : CONTINUOUS, INTEGER, or SEMI_CONTINUOUS | ||
| Variable type. | ||
| VariableType : VType | ||
| Variable type, always normalized to a :py:class:`VType` member | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. "always normalized" is redundant with the ": VType" comment above. |
||
| (CONTINUOUS, INTEGER, or SEMI_CONTINUOUS). Assigning a ``str`` or | ||
| ``bytes`` character code converts it; anything else raises ValueError. | ||
| LB : float | ||
| Lower Bound of the Variable. | ||
| UB : float | ||
|
|
@@ -129,6 +152,14 @@ def __init__( | |
| self.VariableName = vname | ||
| self.MIPStart = float("nan") | ||
|
|
||
| @property | ||
| def VariableType(self): | ||
| return self._variable_type | ||
|
|
||
| @VariableType.setter | ||
| def VariableType(self, value): | ||
| self._variable_type = _to_vtype(value) | ||
|
Comment on lines
+155
to
+161
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win 🧩 Analysis chain🏁 Script executed: #!/bin/bash
set -euo pipefail
fd -HI -a -t f --regex '^(pyproject\.toml|setup\.cfg|tox\.ini|\.python-version|\.tool-versions)$' . -0 |
while IFS= read -r -d '' file; do
printf '\n== %s ==\n' "$file"
rg -n -i 'requires-python|python_requires|target-version|python_version|python' "$file" || true
done
ast-grep outline python/cuopt/cuopt/linear_programming/problem.py \
--items all --type function --match 'VariableType'Repository: NVIDIA/cuopt Length of output: 1680 🏁 Script executed: #!/bin/bash
set -euo pipefail
printf '%s\n' '== problem.py relevant sections =='
sed -n '1,245p' python/cuopt/cuopt/linear_programming/problem.py
printf '%s\n' '== related public property annotations =='
rg -n -U '`@property`\n|@[A-Za-z_][A-Za-z0-9_]*\.setter|def [A-Za-z_][A-Za-z0-9_]*\(self' \
python/cuopt/cuopt/linear_programming python/cuopt/cuopt | head -240Repository: NVIDIA/cuopt Length of output: 30483 🏁 Script executed: #!/bin/bash
set -euo pipefail
printf '%s\n' '== change scope =='
git diff --stat -- python/cuopt/cuopt/linear_programming/problem.py
git diff --unified=20 -- python/cuopt/cuopt/linear_programming/problem.py | sed -n '1,220p'
printf '%s\n' '== package and repository Python targets =='
sed -n '1,55p' pyproject.toml
sed -n '1,48p' python/cuopt/pyproject.toml
printf '%s\n' '== AST annotation check =='
python3 - <<'PY'
import ast
from pathlib import Path
path = Path("python/cuopt/cuopt/linear_programming/problem.py")
tree = ast.parse(path.read_text())
for node in ast.walk(tree):
if isinstance(node, ast.ClassDef) and node.name == "Variable":
for item in node.body:
if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)) and item.name == "VariableType":
print(
f"{path}:{item.lineno}: "
f"return={ast.unparse(item.returns) if item.returns else None}, "
f"args={[ast.unparse(a.annotation) if a.annotation else None for a in item.args.args]}"
)
PYRepository: NVIDIA/cuopt Length of output: 3004 Add type hints to Annotate the getter with 🤖 Prompt for AI AgentsSource: Coding guidelines |
||
|
|
||
| def getIndex(self): | ||
| """ | ||
| Get the index position of the variable in the problem. | ||
|
|
@@ -181,13 +212,15 @@ def getUpperBound(self): | |
| def setVariableType(self, val): | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nit: it's a bit confusing to have two styles of setters and getters for the same field (setVariableType/getVariableType and the the new property setter/getter above. |
||
| """ | ||
| Sets the variable type of the variable. | ||
| Variable types can be CONTINUOUS, INTEGER, or SEMI_CONTINUOUS. | ||
| Variable types can be CONTINUOUS, INTEGER, or SEMI_CONTINUOUS, or the | ||
| equivalent character code as ``str`` or ``bytes``. | ||
| Raises ValueError for any other value. | ||
| """ | ||
| self.VariableType = val | ||
|
|
||
| def getVariableType(self): | ||
| """ | ||
| Returns the type of the variable. | ||
| Returns the type of the variable as a :py:class:`VType` member. | ||
| """ | ||
| return self.VariableType | ||
|
|
||
|
|
@@ -2078,7 +2111,7 @@ def NumNZs(self): | |
| def IsMIP(self): | ||
| # Returns if the problem is a MIP problem. | ||
| for var in self.vars: | ||
| if var.VariableType in ("I", "S", b"I", b"S"): | ||
| if var.VariableType in (INTEGER, SEMI_CONTINUOUS): | ||
| return True | ||
| return False | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -160,6 +160,45 @@ def test_constraint_duplicate_terms_slack(): | |
| assert c.compute_slack() == pytest.approx(6.0) | ||
|
|
||
|
|
||
| def test_variable_type_is_normalized(): | ||
| prob = Problem() | ||
| from_enum = prob.addVariable(vtype=INTEGER) | ||
| from_str = prob.addVariable(vtype="I") | ||
| from_bytes = prob.addVariable(vtype=b"I") | ||
| default = prob.addVariable() | ||
|
|
||
| for var in (from_enum, from_str, from_bytes): | ||
| assert var.VariableType is VType.INTEGER | ||
| assert default.VariableType is VType.CONTINUOUS | ||
| assert prob.IsMIP | ||
|
|
||
| # Both the setter and direct assignment normalize. | ||
| from_str.setVariableType(b"S") | ||
| assert from_str.VariableType is VType.SEMI_CONTINUOUS | ||
| from_bytes.VariableType = "C" | ||
| assert from_bytes.VariableType is VType.CONTINUOUS | ||
|
|
||
| with pytest.raises(ValueError): | ||
| from_enum.setVariableType(7) | ||
|
|
||
|
|
||
| def test_variable_type_normalized_from_mps(tmp_path): | ||
| prob = Problem("mip") | ||
| x = prob.addVariable(lb=0.0, ub=10.0, vtype=INTEGER, name="x") | ||
| y = prob.addVariable(lb=0.0, ub=10.0, name="y") | ||
| prob.addConstraint(x + y <= 5, name="c") | ||
| prob.setObjective(x + y, sense=MAXIMIZE) | ||
|
|
||
| path = str(tmp_path / "mip.mps") | ||
| prob.writeMPS(path) | ||
|
|
||
| loaded = Problem.read(path) | ||
| types = [v.VariableType for v in loaded.getVariables()] | ||
| assert all(isinstance(t, VType) for t in types) | ||
| assert VType.INTEGER in types | ||
| assert loaded.IsMIP | ||
|
Comment on lines
+195
to
+199
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win Assert each variable type after the MPS round trip.
Assert the ordered result equals As per path instructions, “require assertions that validate behavior and edge cases rather than merely successful execution.” 🤖 Prompt for AI AgentsSource: Path instructions |
||
|
|
||
|
|
||
| def test_semi_continuous_variable(): | ||
| prob = Problem("Semi-continuous") | ||
| x = prob.addVariable(lb=5.0, ub=10.0, vtype=SEMI_CONTINUOUS, name="x") | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Restrict normalization to documented input types.
Line 51 accepts
bytearray, although the documented contract permits onlyVType,str, andbytes. For example,bytearray(b"I")now succeeds and producesVType.INTEGER.Remove
bytearrayfrom this branch, or document it as a supported public input type.As per path instructions, “Verify normalization accepts only the documented VType, string, and byte forms.”
🤖 Prompt for AI Agents
Source: Path instructions