1
$\begingroup$

This question of how to fit a sum Gaussians, where the number of Gaussians is to be determined, to data is answered nicely already by Fittting data with combination of an unknown number of Gaussians, but including constraints seems difficult. Here is an attempt:

g[x_, xo_, σ_, a_] := {a Exp[-((x - xo)^2/(2 σ^2))]/(σ Sqrt[2 π]), a > 0} 

When running the code at the link with this change get the following error:

NonlinearModelFit::eqineq: Constraints in {(a[1]>0)+(a[2]>0)} are not all equality or inequality constraints. With the exception of integer domain constraints for linear programming, domain constraints or constraints with Unequal (!=) are not supported.

How to add constraints?

$\endgroup$
1
  • $\begingroup$ Can you show the exact code used which gives you the error message? Your constraint {(a[1]>0)+(a[2]>0)} does not look correct (the plus sign should be a comma, perhaps). $\endgroup$
    – bill s
    Commented Oct 26, 2019 at 18:43

1 Answer 1

1
$\begingroup$

This is how you can generate an expression with constraints in the appropriate form:

gmodel[n_Integer] := Module[{forms, cons},
  {forms, cons} = Transpose@Table[g[x, Sequence @@ kvar[i]], {i, 1, n}];
  {Total[forms], Sequence @@ cons}
  ]

gmodel[3]

Mathematica graphics

This assumes that we're using the definition of g given in your question, and all the other definitions needed from the answer to the linked question by rhermans.

When I run this on his example, I get a warning message saying that AIC assumes an unconstrained model and the fitting doesn't seem to work. But that's another problem, this should solve the problem of how to provide constraints.

$\endgroup$
2
  • 1
    $\begingroup$ The other required constraints are that the $\sigma$ values need to be positive. That can be accomplished by modifying a > 0 to a > 0 && \[Sigma] > 0. And to be picky I'd call the AIC message a warning rather than an error. $\endgroup$
    – JimB
    Commented Oct 27, 2019 at 0:02
  • $\begingroup$ @JimB Good point, I agree about calling it a warning message. I changed that in the answer. $\endgroup$
    – C. E.
    Commented Oct 27, 2019 at 7:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.