diff --git a/CHANGELOG.md b/CHANGELOG.md index 4daaf48c2..a8cf9fe0b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased ### Added +- Added the following methods with tests: `nodesSharePath()`, `nodesGetCommonAncestor()`, `getFocusDepth()`, `getRootNode()`, `wasNodeLastBranchParent()` - Added `getCountedSols()` to retrieve the solutions collected by `count()` (#906) - Added docstrings to the bundled stubs in release wheels for Python 3.10 and later. - Added more type annotations and deprecation markers to the stubs. diff --git a/src/pyscipopt/scip.pxd b/src/pyscipopt/scip.pxd index 277789ce9..d298abc12 100644 --- a/src/pyscipopt/scip.pxd +++ b/src/pyscipopt/scip.pxd @@ -755,6 +755,8 @@ cdef extern from "scip/scip.h": # Node Methods SCIP_NODE* SCIPgetFocusNode(SCIP* scip) SCIP_NODE* SCIPgetCurrentNode(SCIP* scip) + SCIP_Bool SCIPnodesSharePath(SCIP_NODE* node1, SCIP_NODE* node2) + SCIP_NODE* SCIPnodesGetCommonAncestor(SCIP_NODE* node1, SCIP_NODE* node2) SCIP_NODE* SCIPnodeGetParent(SCIP_NODE* node) SCIP_Longint SCIPnodeGetNumber(SCIP_NODE* node) int SCIPnodeGetDepth(SCIP_NODE* node) @@ -2168,6 +2170,9 @@ cdef extern from "scip/pub_lp.h": cdef extern from "scip/scip_tree.h": SCIP_RETCODE SCIPgetOpenNodesData(SCIP* scip, SCIP_NODE*** leaves, SCIP_NODE*** children, SCIP_NODE*** siblings, int* nleaves, int* nchildren, int* nsiblings) + int SCIPgetFocusDepth(SCIP* scip) + SCIP_NODE* SCIPgetRootNode(SCIP* scip) + SCIP_Bool SCIPwasNodeLastBranchParent(SCIP* scip, SCIP_NODE* node) SCIP_RETCODE SCIPgetChildren(SCIP* scip, SCIP_NODE*** children, int* nchildren) SCIP_Longint SCIPgetNChildren(SCIP* scip) SCIP_NODE* SCIPgetBestChild(SCIP* scip) diff --git a/src/pyscipopt/scip.pxi b/src/pyscipopt/scip.pxi index a849a30b3..2fffa2dd2 100644 --- a/src/pyscipopt/scip.pxi +++ b/src/pyscipopt/scip.pxi @@ -3459,6 +3459,32 @@ cdef class Model: """ return Node.create(SCIPgetFocusNode(self._scip)) + def getFocusDepth(self): + """ + Gets depth of the focus node, or -1 if no focus node exists. + The focus node is the currently processed node in the branching tree, excluding the nodes of the probing path. + + Returns + ------- + int + The depth of the focus node, or -1 if no focus node exists. + + """ + return SCIPgetFocusDepth(self._scip) + + def getRootNode(self): + """ + Gets the root node of the tree, or None if no root node exists. + + Returns + ------- + Node or None + The root node of the search tree, or None if no root node exists + (e.g., after the problem has been solved to optimality). + + """ + return Node.create(SCIPgetRootNode(self._scip)) + def getCurrentNode(self): """ Retrieve current node. @@ -3470,6 +3496,68 @@ cdef class Model: """ return Node.create(SCIPgetCurrentNode(self._scip)) + def wasNodeLastBranchParent(self, Node node=None): + """ + Checks whether the node was the parent in the most recent branching of the tree. + + Parameters + ---------- + node : Node or None + A node of this model, or None to check the focus node. + + Returns + ------- + bool + Whether the node was the last branching parent. False if no branching + has occurred or no focus node exists when node is None. + + """ + cdef SCIP_NODE* scip_node = NULL + if node is not None: + scip_node = node.scip_node + return bool(SCIPwasNodeLastBranchParent(self._scip, scip_node)) + + def nodesSharePath(self, Node node1 not None, Node node2 not None): + """ + Checks for two nodes whether they share the same root path, i.e., whether one is an ancestor of the other. + If node1 and node2 are the same node, True is returned. + + Parameters + ---------- + node1 : Node + First node to compare. + node2 : Node + Second node to compare. + + Returns + ------- + bool + Whether the nodes share a root path. + + """ + return bool(SCIPnodesSharePath(node1.scip_node, node2.scip_node)) + + def nodesGetCommonAncestor(self, Node node1 not None, Node node2 not None): + """ + Finds the common ancestor node of two given nodes, or None if no common ancestor is found. + If node1 and node2 are the same node, that node is returned. + + Parameters + ---------- + node1 : Node + First node to compare. + node2 : Node + Second node to compare. + + Returns + ------- + Node or None + The common ancestor closest to the given nodes, or None if no common ancestor is found + (e.g., if the nodes belong to different trees). + + """ + return Node.create(SCIPnodesGetCommonAncestor(node1.scip_node, node2.scip_node)) + def getGap(self): """ Retrieve the gap, diff --git a/src/pyscipopt/scip.pyi b/src/pyscipopt/scip.pyi index 85b000c32..2a68274a5 100644 --- a/src/pyscipopt/scip.pyi +++ b/src/pyscipopt/scip.pyi @@ -1261,6 +1261,7 @@ class Model: def getConsVals(self, constraint: Constraint) -> list[float] | None: ... def getConsVars(self, constraint: Constraint) -> list[Variable] | None: ... def getConss(self, transformed: bool = True) -> list[Constraint]: ... + def getFocusDepth(self) -> int: ... def getFocusNode(self) -> Node | None: ... def getCountedSols(self) -> list[dict[str, int]]: ... def getCurrentNode(self) -> Node | None: ... @@ -1378,6 +1379,7 @@ class Model: def getReadingTime(self) -> float: ... def getResultantAnd(self, and_cons: Constraint) -> Variable: ... def getRhs(self, cons: Constraint) -> float: ... + def getRootNode(self) -> Node | None: ... def getRowActivity(self, row: Row) -> float: ... def getRowDualSol(self, row: Row) -> float: ... def getRowLPActivity(self, row: Row) -> float: ... @@ -1630,6 +1632,8 @@ class Model: def markDoNotAggrVar(self, var: Variable) -> None: ... def markDoNotMultaggrVar(self, var: Variable) -> None: ... def newProbingNode(self) -> None: ... + def nodesGetCommonAncestor(self, node1: Node, node2: Node) -> Node | None: ... + def nodesSharePath(self, node1: Node, node2: Node) -> bool: ... def optimize(self) -> None: ... def optimizeNogil(self) -> None: ... def presolve(self) -> None: ... @@ -1765,6 +1769,7 @@ class Model: self, var: Variable, valdelta: float, objdelta: float, weight: float ) -> None: ... def version(self) -> float: ... + def wasNodeLastBranchParent(self, node: Node | None = None) -> bool: ... def writeBestSol( self, filename: StrOrBytesPath = "origprob.sol", diff --git a/tests/test_node.py b/tests/test_node.py index bf2b4dbf2..783580af9 100644 --- a/tests/test_node.py +++ b/tests/test_node.py @@ -101,3 +101,44 @@ def test_getFocusNode_and_getCurrentNode(): m.includeEventhdlr(ProbingNodeChecker(), "Probing Node Checker", "test if getFocusNode and getCurrentNode work correctly") m.optimize() + +def test_nodesSharePath(): + m = random_mip_1(small=True, node_lim=1) + m.optimize() + + root = m.getCurrentNode() + assert root is not None + + # create two children of the root node + child1 = m.createChild(0, m.getLocalEstimate()) + child2 = m.createChild(0, m.getLocalEstimate()) + + for node in (root, child1, child2): + assert m.nodesSharePath(node, node) is True + + for child in (child1, child2): + assert m.nodesSharePath(root, child) is True + assert m.nodesSharePath(child, root) is True + + assert m.nodesSharePath(child1, child2) is False + assert m.nodesSharePath(child2, child1) is False + +def test_nodesGetCommonAncestor(): + m = random_mip_1(small=True, node_lim=1) + m.optimize() + + root = m.getCurrentNode() + assert root is not None + + child1 = m.createChild(0, m.getLocalEstimate()) + child2 = m.createChild(0, m.getLocalEstimate()) + + for node in (root, child1, child2): + assert m.nodesGetCommonAncestor(node, node) == node + + for child in (child1, child2): + assert m.nodesGetCommonAncestor(root, child) == root + assert m.nodesGetCommonAncestor(child, root) == root + + assert m.nodesGetCommonAncestor(child1, child2) == root + assert m.nodesGetCommonAncestor(child2, child1) == root diff --git a/tests/test_node_methods.py b/tests/test_node_methods.py index 58125b58a..a94a5dd64 100644 --- a/tests/test_node_methods.py +++ b/tests/test_node_methods.py @@ -1,5 +1,5 @@ from helpers.utils import random_mip_1 -from pyscipopt import Eventhdlr, SCIP_EVENTTYPE, SCIP_RESULT +from pyscipopt import Eventhdlr, Model, SCIP_EVENTTYPE, SCIP_RESULT, SCIP_STAGE class MaxDepthTracker(Eventhdlr): def __init__(self): @@ -181,3 +181,97 @@ def test_getNStrongbranchLPIterations(): assert sb_iters >= 0, f"Expected non-negative strong branching iterations, got {sb_iters}" assert sb_iters <= total_lp_iters, f"Strong branching iterations {sb_iters} should not exceed total LP iterations {total_lp_iters}" + + +def test_getFocusDepth(): + m = random_mip_1(small=True, node_lim=1) + m.presolve() + assert m.getFocusDepth() == -1 + + m.optimize() + focus = m.getFocusNode() + assert focus is not None + assert m.getFocusDepth() == focus.getDepth() == m.getDepth() == 0 + + m.startProbing() + m.newProbingNode() + m.newProbingNode() + assert m.getProbingDepth() == 2 + assert m.getDepth() > focus.getDepth() + assert m.getFocusDepth() == focus.getDepth() + m.endProbing() + + assert m.getFocusDepth() == m.getDepth() == focus.getDepth() + + +def test_getRootNode(): + m = random_mip_1(small=True, node_lim=1) + m.optimize() + + root = m.getFocusNode() + assert root is not None + assert root.getDepth() == 0 + assert root.getParent() is None + + m.setParam("limits/nodes", 10) + m.optimize() + + assert m.getRootNode() == root + assert m.getFocusNode() != root + + +class LastBranchParentTracker(Eventhdlr): + def __init__(self): + self.branched_depths = set() + + def eventinit(self): + self.model.catchEvent(SCIP_EVENTTYPE.NODEBRANCHED, self) + + def eventexit(self): + self.model.dropEvent(SCIP_EVENTTYPE.NODEBRANCHED, self) + + def eventexec(self, event): + node = event.getNode() + assert node == self.model.getFocusNode() + assert self.model.wasNodeLastBranchParent() is True + assert self.model.wasNodeLastBranchParent(node=node) is True + + self.branched_depths.add(node.getDepth()) + children = self.model.getChildren() + assert children + for child in children: + assert self.model.wasNodeLastBranchParent(child) is False + + parent = node.getParent() + if parent is not None: + # An older branching parent must be False after a new branching. + assert self.model.wasNodeLastBranchParent(parent) is False + + +def test_wasNodeLastBranchParent(): + m = random_mip_1(small=True, node_lim=30) + m.hideOutput() + tracker = LastBranchParentTracker() + m.includeEventhdlr(tracker, "last_branch_parent", "Check the last branching parent") + + m.presolve() + assert m.getStage() == SCIP_STAGE.PRESOLVED + assert m.wasNodeLastBranchParent() is False + + m.optimize() + + # to make sure that branchings occurred + assert any(depth > 0 for depth in tracker.branched_depths) + + +def test_wasNodeLastBranchParent_solved_without_branching(): + m = Model() + m.hideOutput() + x = m.addVar(vtype="B", obj=1) + m.addCons(x >= 1) + m.optimize() + + assert m.getStage() == SCIP_STAGE.SOLVED + assert m.getStatus() == "optimal" + assert m.wasNodeLastBranchParent() is False + assert m.wasNodeLastBranchParent(None) is False