Search code examples
pythonjupyter-notebookjupyter-labpatsy

TypeError: 'DesignMatrix' object is not callable


I am trying to create B-splines with the patsy package on a ipynb notebook on JupyterLab:

from patsy import dmatrix

bs = dmatrix("bs(x, df=50, degree=1) - 1", {"x": x})
axes[0].plot(x, bs)
axes[0].set_title("Basis functions")

plt.show()

This works fine the first time I run it. But when I try to rerun this cell again, it fails with the following error:


-----------------------------------------------------
TypeError                                 Traceback (most recent call last)
/opt/conda/lib/python3.8/site-packages/patsy/compat.py in call_and_wrap_exc(msg, origin, f, *args, **kwargs)
     35     try:
---> 36         return f(*args, **kwargs)
     37     except Exception as e:

/opt/conda/lib/python3.8/site-packages/patsy/eval.py in eval(self, expr, source_name, inner_namespace)
    164         code = compile(expr, source_name, "eval", self.flags, False)
--> 165         return eval(code, {}, VarLookupDict([inner_namespace]
    166                                             + self._namespaces))

<string> in <module>

TypeError: 'DesignMatrix' object is not callable

The above exception was the direct cause of the following exception:

PatsyError                                Traceback (most recent call last)
<ipython-input-6-6ed4ba95a384> in <module>
      2 
      3 _, axes = plt.subplots(2, figsize=(16, 16))
----> 4 bs = dmatrix("bs(x, df=50, degree=1) - 1", {"x": x})
      5 axes[0].plot(x, bs)
      6 axes[0].set_title("Basis functions")

/opt/conda/lib/python3.8/site-packages/patsy/highlevel.py in dmatrix(formula_like, data, eval_env, NA_action, return_type)
    288     """
    289     eval_env = EvalEnvironment.capture(eval_env, reference=1)
--> 290     (lhs, rhs) = _do_highlevel_design(formula_like, data, eval_env,
    291                                       NA_action, return_type)
    292     if lhs.shape[1] != 0:

/opt/conda/lib/python3.8/site-packages/patsy/highlevel.py in _do_highlevel_design(formula_like, data, eval_env, NA_action, return_type)
    162     def data_iter_maker():
    163         return iter([data])
--> 164     design_infos = _try_incr_builders(formula_like, data_iter_maker, eval_env,
    165                                       NA_action)
    166     if design_infos is not None:

/opt/conda/lib/python3.8/site-packages/patsy/highlevel.py in _try_incr_builders(formula_like, data_iter_maker, eval_env, NA_action)
     64     if isinstance(formula_like, ModelDesc):
     65         assert isinstance(eval_env, EvalEnvironment)
---> 66         return design_matrix_builders([formula_like.lhs_termlist,
     67                                        formula_like.rhs_termlist],
     68                                       data_iter_maker,

/opt/conda/lib/python3.8/site-packages/patsy/build.py in design_matrix_builders(termlists, data_iter_maker, eval_env, NA_action)
    691     # on some data to find out what type of data they return.
    692     (num_column_counts,
--> 693      cat_levels_contrasts) = _examine_factor_types(all_factors,
    694                                                    factor_states,
    695                                                    data_iter_maker,

/opt/conda/lib/python3.8/site-packages/patsy/build.py in _examine_factor_types(factors, factor_states, data_iter_maker, NA_action)
    441     for data in data_iter_maker():
    442         for factor in list(examine_needed):
--> 443             value = factor.eval(factor_states[factor], data)
    444             if factor in cat_sniffers or guess_categorical(value):
    445                 if factor not in cat_sniffers:

/opt/conda/lib/python3.8/site-packages/patsy/eval.py in eval(self, memorize_state, data)
    562 
    563     def eval(self, memorize_state, data):
--> 564         return self._eval(memorize_state["eval_code"],
    565                           memorize_state,
    566                           data)

/opt/conda/lib/python3.8/site-packages/patsy/eval.py in _eval(self, code, memorize_state, data)
    545     def _eval(self, code, memorize_state, data):
    546         inner_namespace = VarLookupDict([data, memorize_state["transforms"]])
--> 547         return call_and_wrap_exc("Error evaluating factor",
    548                                  self,
    549                                  memorize_state["eval_env"].eval,

/opt/conda/lib/python3.8/site-packages/patsy/compat.py in call_and_wrap_exc(msg, origin, f, *args, **kwargs)
     41                                  origin)
     42             # Use 'exec' to hide this syntax from the Python 2 parser:
---> 43             exec("raise new_exc from e")
     44         else:
     45             # In python 2, we just let the original exception escape -- better

/opt/conda/lib/python3.8/site-packages/patsy/compat.py in <module>

PatsyError: Error evaluating factor: TypeError: 'DesignMatrix' object is not callable
    bs(x, df=50, degree=1) - 1
    ^^^^^^^^^^^^^^^^^^^^^^

Solution

  • Ends up it was because of myself overriding the variable bs hence overriding the bs function inside the patsy string.

    This is why eval is an antipattern as usual...