Skip to content
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

Cryptic error when importing lmfit #314

Closed
caenrigen opened this issue Mar 23, 2021 · 0 comments · Fixed by #315
Closed

Cryptic error when importing lmfit #314

caenrigen opened this issue Mar 23, 2021 · 0 comments · Fixed by #315

Comments

@caenrigen
Copy link
Contributor

caenrigen commented Mar 23, 2021

With the latest 0.12.0/0.12.1 release we run into a strange issue that seems totally unrelated that depends on the order of the imports of the lmfit and adaptive:

The following fails:

import adaptive  # >=0.12.0
import lmfit
import numpy as np

def cos_func(t, amplitude, frequency, phase, offset):
    """A simple cosine function"""
    return amplitude * np.cos(2 * np.pi * frequency * t + phase) + offset

mod = lmfit.Model(cos_func)
mod.set_param_hint('amplitude', value=1, vary=True)
mod.set_param_hint('frequency', value=0.2)
mod.set_param_hint('phase', value=0, vary=True)
mod.set_param_hint('offset', value=0, vary=False)
params = mod.make_params()
fit_res = mod.fit(np.cos(np.linspace(0, 5, 10)), t=np.linspace(0, 5, 10), params=mod.make_params())

fit_res.plot_fit(show_init=True)

lmfit.model.save_modelresult(fit_res, 'fit_res.json')

throwing

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-3-fb6b7cf4fb53> in <module>
     17 fit_res.plot_fit(show_init=True)
     18 
---> 19 lmfit.model.save_modelresult(fit_res, 'fit_res.json')
        global lmfit.model.save_modelresult = <function save_modelresult at 0x12be17830>
        global fit_res = <lmfit.model.ModelResult object at 0x12df5c610>

/usr/local/anaconda3/envs/dclab/lib/python3.7/site-packages/lmfit/model.py in save_modelresult(modelresult=<lmfit.model.ModelResult object>, fname='fit_res.json')
   1258     """
   1259     with open(fname, 'w') as fout:
-> 1260         modelresult.dump(fout)
        modelresult.dump = <bound method ModelResult.dump of <lmfit.model.ModelResult object at 0x12df5c610>>
        fout = <_io.TextIOWrapper name='fit_res.json' mode='w' encoding='UTF-8'>
   1261 
   1262 

/usr/local/anaconda3/envs/dclab/lib/python3.7/site-packages/lmfit/model.py in dump(self=<lmfit.model.ModelResult object>, fp=<_io.TextIOWrapper name='fit_res.json' mode='w' encoding='UTF-8'>, **kws={})
   1668 
   1669         """
-> 1670         return fp.write(self.dumps(**kws))
        fp.write = <built-in method write of _io.TextIOWrapper object at 0x12ae46210>
        self.dumps = <bound method ModelResult.dumps of <lmfit.model.ModelResult object at 0x12df5c610>>
        kws = {}
   1671 
   1672     def loads(self, s, funcdefs=None, **kws):

/usr/local/anaconda3/envs/dclab/lib/python3.7/site-packages/lmfit/model.py in dumps(self=<lmfit.model.ModelResult object>, **kws={})
   1623         out['params'] = [p.__getstate__() for p in self.params.values()]
   1624         out['unique_symbols'] = {key: encode4js(pasteval.symtable[key])
-> 1625                                  for key in pasteval.user_defined_symbols()}
        global key = undefined
        global pasteval.user_defined_symbols = undefined
   1626 
   1627         for attr in ('aborted', 'aic', 'best_values', 'bic', 'chisqr',

/usr/local/anaconda3/envs/dclab/lib/python3.7/site-packages/lmfit/model.py in <dictcomp>(.0=<set_iterator object>)
   1623         out['params'] = [p.__getstate__() for p in self.params.values()]
   1624         out['unique_symbols'] = {key: encode4js(pasteval.symtable[key])
-> 1625                                  for key in pasteval.user_defined_symbols()}
        key = 'wofz'
        global pasteval.user_defined_symbols = undefined
   1626 
   1627         for attr in ('aborted', 'aic', 'best_values', 'bic', 'chisqr',

/usr/local/anaconda3/envs/dclab/lib/python3.7/site-packages/lmfit/jsonutils.py in encode4js(obj=<ufunc 'wofz'>)
     93         else:
     94             val = None
---> 95             importer = find_importer(obj)
        importer = None
        global find_importer = <function find_importer at 0x1083cf170>
        obj = <ufunc 'wofz'>
     96         return dict(__class__='Callable', __name__=obj.__name__,
     97                     pyversion=pyvers, value=val, importer=importer)

/usr/local/anaconda3/envs/dclab/lib/python3.7/site-packages/lmfit/jsonutils.py in find_importer(obj=<ufunc 'wofz'>)
     25         if modname.startswith('__main__'):
     26             continue
---> 27         t = getattr(module, oname, None)
        t = None
        global getattr = undefined
        module = <module 'adaptive.learner.integrator_coeffs' from '/usr/local/anaconda3/envs/dclab/lib/python3.7/site-packages/adaptive/learner/integrator_coeffs.py'>
        oname = 'wofz'
     28         if t is obj:
     29             return modname

/usr/local/anaconda3/envs/dclab/lib/python3.7/site-packages/adaptive/learner/integrator_coeffs.py in __getattr__(attr='wofz')
    188 
    189 def __getattr__(attr):
--> 190     return _coefficients()[attr]
        global _coefficients = <functools._lru_cache_wrapper object at 0x1260d40f0>
        attr = 'wofz'

KeyError: 'wofz'

BUT this seems to work fine:

import lmfit
import adaptive  # >=0.12.0
import numpy as np

def cos_func(t, amplitude, frequency, phase, offset):
    """A simple cosine function"""
    return amplitude * np.cos(2 * np.pi * frequency * t + phase) + offset

mod = lmfit.Model(cos_func)
mod.set_param_hint('amplitude', value=1, vary=True)
mod.set_param_hint('frequency', value=0.2)
mod.set_param_hint('phase', value=0, vary=True)
mod.set_param_hint('offset', value=0, vary=False)
params = mod.make_params()
fit_res = mod.fit(np.cos(np.linspace(0, 5, 10)), t=np.linspace(0, 5, 10), params=mod.make_params())

fit_res.plot_fit(show_init=True)

lmfit.model.save_modelresult(fit_res, 'fit_res.json')

Any idea what is happening? This fails on python 3.7 and also on python 3.8 (on the readthedocs.com)

basnijholt added a commit that referenced this issue Mar 23, 2021
raise an AttributeError when attribute doesn't exists, closes #314
kel85uk pushed a commit to quantify-os/quantify-core that referenced this issue Mar 31, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant