pyROOT: problem passing member function to TF1


I’ve made this simple piece of code:

from ROOT import *
class A(object):
  def __init__(self):
    self.b = 0
  def myFun(self, t, par):
    return t[0]

a = A()
f = TF1('Test', a.myFun, 0, 10, 1)
print('AAA' , f.Eval(2))

which used to run with earlier versions of ROOT but now it’s no longer working.
Error message:

Traceback (most recent call last):
  File "testTF1.py", line 12, in <module>
    print('AAA' , f.Eval(2))
TypeError: double TF1::Eval(double x, double y = 0, double z = 0, double t = 0) =>
    TypeError: callable was deleted

Is there a workaround?
Many thanks

  • Mauro.

ROOT Version: 6.22.0
Platform: Mac OS 10.15.6
Compiler: Apple clang version 11.0.3 (clang-1103.0.32.62)


Hi Mauro,

This could be a bug, I’ll investigate.

In the meantime, you can use this slightly different solution, where I make the object itself callable:

import ROOT

class A(object):
  def __init__(self):
    self.b = 0

  def __call__(self, t, par):
    return t[0]

a = A()
f = ROOT.TF1('Test', a, 0, 10, 1)

print('AAA' , f.Eval(2))

or you can also do this, using a plain function:

import ROOT

def myFun(t, par):
  return t[0]

f = ROOT.TF1('Test', myFun, 0, 10, 1)

print('AAA' , f.Eval(2))

Hi Enric,
ok, thanks for the solution.
I’ll make my object callable
Cheers,

  • Mauro.

Hi,

Coming back to your original code, if you construct the TF1 like this:

f = TF1('Test', a.myFun, 0, 10, 1)

The a.myFun object is not alive anymore when you call Eval, and that could trigger the error you see. But if you do:

myfun = a.myFun
f = TF1('Test', myfun, 0, 10, 1)

myfun keeps a reference to the method and the error is gone.

Hi @etejedor,
many thanks.
Indeed it works.

The strange thing is that I used to run my code with ROOT 6.18 and I didn’t have any problem.
The problem showed up when I moved to ROOT 6.22

The other strange thing is that I can use f.GetNpar()

...
f = TF1('Test', a.myFun, 0, 10, 1)
print('AAA', f.GetNpar())
print('AAA' , f.Eval(2))
...

and f.GetNpar() works.

Thanks again.
Cheers,

  • Mauro.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.