Skip to content

Commit 3f8e106

Browse files
committed
[math] Throw exception when RootFinder is constructed with invalid algo.
When MathMore cannot be loaded, the tutorial exampleFunction.py used to crash. Here, an exception is added thrown in the constructor, which can be caught in the Python tutorial.
1 parent d6d6000 commit 3f8e106

File tree

2 files changed

+16
-18
lines changed

2 files changed

+16
-18
lines changed

math/mathcore/src/RootFinder.cxx

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -41,11 +41,15 @@ RootFinder::RootFinder(RootFinder::EType type) :
4141
fSolver(nullptr)
4242
{
4343
// constructor passing type (default is kBRENT)
44-
SetMethod(type);
44+
const bool success = SetMethod(type);
45+
if (!success)
46+
throw std::runtime_error("ROOT::Math::RootFinder: ROOT was built without the requested algorithm");
4547
}
4648

4749
bool RootFinder::SetMethod(RootFinder::EType type)
4850
{
51+
fSolver = nullptr;
52+
4953
// set method - Use the plug-in manager if method is implemented in MathMore
5054
if ( type == RootFinder::kBRENT )
5155
{
@@ -125,16 +129,16 @@ bool RootFinder::SetMethod(RootFinder::EType type)
125129
return false;
126130
}
127131

128-
fSolver = reinterpret_cast<ROOT::Math::IRootFinderMethod *>( h->ExecPlugin(0) );
129-
assert(fSolver != nullptr);
132+
fSolver = reinterpret_cast<ROOT::Math::IRootFinderMethod *>(h->ExecPlugin(0));
130133
}
131-
else {
134+
135+
#endif
136+
137+
if (!fSolver) {
132138
MATH_ERROR_MSG("RootFinder::SetMethod","Error loading RootFinderMethod");
133139
return false;
134140
}
135141

136-
#endif
137-
138142
return true;
139143
}
140144

tutorials/math/exampleFunction.py

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -69,25 +69,19 @@ def RosenbrockFunction(xx):
6969

7070
def g(x): return 2 * x
7171

72-
gradFunc = ROOT.Math.GradFunctor1D(f, g)
73-
74-
#check if ROOT has mathmore
75-
prevLevel = ROOT.gErrorIgnoreLevel
76-
ROOT.gErrorIgnoreLevel=ROOT.kFatal
77-
ret = ROOT.gSystem.Load("libMathMore")
78-
ROOT.gErrorIgnoreLevel=prevLevel
79-
if (ret < 0) :
80-
print("ROOT has not Mathmore")
81-
print("derivative value at x = 1", gradFunc.Derivative(1) )
82-
83-
else :
72+
# GSL_Newton is part of ROOT's MathMore library, which is not always active.
73+
# Let's therefore run this in a try block:
74+
try:
75+
gradFunc = ROOT.Math.GradFunctor1D(f, g)
8476
rf = ROOT.Math.RootFinder(ROOT.Math.RootFinder.kGSL_NEWTON)
8577
rf.SetFunction(gradFunc, 3)
8678
rf.Solve()
8779
value = rf.Root()
8880
print("Found root value x0 : f(x0) = 0 : ", value)
8981
if (value != 1):
9082
print("Error finding a ROOT of function f(x)=x^2-1")
83+
except Exception as e:
84+
print(e)
9185

9286

9387
print("\n\nUse GradFunctor for making a function object implementing f(x,y) and df(x,y)/dx and df(x,y)/dy")

0 commit comments

Comments
 (0)