@@ -328,3 +328,73 @@ def eval(x, a, b):
328328 assert m .b .fixed is False
329329 assert m .bounds == {'a' : (1 , None ), 'b' : (2 , None )}
330330 assert m .fixed == {'a' : True , 'b' : False }
331+
332+
333+ def test_fit_with_fixed_and_bound_constraints ():
334+ """
335+ Regression test for https://github.com/astropy/astropy/issues/2235
336+
337+ Currently doesn't test that the fit is any *good*--just that parameters
338+ stay within their given constraints.
339+ """
340+
341+ m = models .Gaussian1D (amplitude = 3 , mean = 4 , stddev = 1 ,
342+ bounds = {'mean' : (4 , 5 )},
343+ fixed = {'amplitude' : True })
344+ x = np .linspace (0 , 10 , 10 )
345+ y = np .exp (- x ** 2 / 2 )
346+
347+ f = fitting .LevMarLSQFitter ()
348+ fitted_1 = f (m , x , y )
349+ assert fitted_1 .mean >= 4
350+ assert fitted_1 .mean <= 5
351+ assert fitted_1 .amplitude == 3.0
352+
353+ m .amplitude .fixed = False
354+ fitted_2 = f (m , x , y )
355+ # It doesn't matter anymore what the amplitude ends up as so long as the
356+ # bounds constraint was still obeyed
357+ assert fitted_1 .mean >= 4
358+ assert fitted_1 .mean <= 5
359+
360+
361+ def test_fit_with_bound_constraints_estimate_jacobian ():
362+ """
363+ Regression test for https://github.com/astropy/astropy/issues/2400
364+
365+ Checks that bounds constraints are obeyed on a custom model that does not
366+ define fit_deriv (and thus its Jacobian must be estimated for non-linear
367+ fitting).
368+ """
369+
370+ class MyModel (Fittable1DModel ):
371+ a = Parameter (default = 1 )
372+ b = Parameter (default = 2 )
373+
374+ @staticmethod
375+ def eval (x , a , b ):
376+ return a * x + b
377+
378+ m_real = MyModel (a = 1.5 , b = - 3 )
379+ x = np .arange (100 )
380+ y = m_real (x )
381+
382+ m = MyModel ()
383+ f = fitting .LevMarLSQFitter ()
384+ fitted_1 = f (m , x , y )
385+
386+ # This fit should be trivial so even without constraints on the bounds it
387+ # should be right
388+ assert np .allclose (fitted_1 .a , 1.5 )
389+ assert np .allclose (fitted_1 .b , - 3 )
390+
391+ m2 = MyModel ()
392+ m2 .a .bounds = (- 2 , 2 )
393+ f2 = fitting .LevMarLSQFitter ()
394+ fitted_2 = f2 (m2 , x , y )
395+ assert np .allclose (fitted_1 .a , 1.5 )
396+ assert np .allclose (fitted_1 .b , - 3 )
397+
398+ # Check that the estimated Jacobian was computed (it doesn't matter what
399+ # the values are so long as they're not all zero.
400+ assert np .any (f2 .fit_info ['fjac' ] != 0 )
0 commit comments