diff --git a/doc/whatsnew.rst b/doc/whatsnew.rst index 02ade391..141ed501 100644 --- a/doc/whatsnew.rst +++ b/doc/whatsnew.rst @@ -21,6 +21,7 @@ Bug fixes/enhancements: - make sure variable ``spercent`` is always defined in ``params_html_table`` functions (reported by @MySlientWind; Issue #768, PR #770) - always initialize the variables ``success`` and ``covar`` the ``MinimizerResult`` (reported by Marc W. Pound; PR #771) - build package following PEP517/PEP518; use ``pyproject.toml`` and ``setup.cfg``; leave ``setup.py`` for now (PR #777) +- components used to create a ``CompositeModel`` can now have different independent variables (@Julian-Hochhaus; Discussion #787; PR #788)) Deprecations: diff --git a/lmfit/model.py b/lmfit/model.py index 5df5b0f1..81acdd93 100644 --- a/lmfit/model.py +++ b/lmfit/model.py @@ -1094,7 +1094,7 @@ def __init__(self, left, right, op, **kws): Notes ----- - The two models must use the same independent variable. + The two models can use different independent variables. """ if not isinstance(left, Model): @@ -1116,9 +1116,11 @@ def __init__(self, left, right, op, **kws): "use distinct names.") raise NameError(msg) - # we assume that all the sub-models have the same independent vars + # the unique ``independent_vars`` of the left and right model are + # combined to ``independent_vars`` of the ``CompositeModel`` if 'independent_vars' not in kws: - kws['independent_vars'] = self.left.independent_vars + ivars = self.left.independent_vars + self.right.independent_vars + kws['independent_vars'] = list(np.unique(ivars)) if 'nan_policy' not in kws: kws['nan_policy'] = self.left.nan_policy diff --git a/tests/test_model.py b/tests/test_model.py index ffafef26..1bb227b8 100644 --- a/tests/test_model.py +++ b/tests/test_model.py @@ -1247,6 +1247,21 @@ def test_wrapped_model_func(self): self.assertTrue(abs(result.params['a'].value - 2.0) < 0.05) self.assertTrue(abs(result.params['b'].value - 3.0) < 0.41) + def test_different_independent_vars_composite_modeld(self): + """Regression test for different independent variables in CompositeModel. + + See: https://github.com/lmfit/lmfit-py/discussions/787 + + """ + def two_independent_vars(y, z, a): + return a * y + z + + BackgroundModel = Model(two_independent_vars, + independent_vars=["y", "z"], prefix="yz_") + PeakModel = Model(gaussian, independent_vars=["x"], prefix="x_") + CompModel = BackgroundModel + PeakModel + assert CompModel.independent_vars == ['x', 'y', 'z'] + class TestLinear(CommonTests, unittest.TestCase):