1

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?

C. E.
  • 70,533
  • 6
  • 140
  • 264
neurosci
  • 73
  • 4
  • 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). – bill s Oct 26 '19 at 18:43

1 Answers1

1

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.

C. E.
  • 70,533
  • 6
  • 140
  • 264
  • 1
    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. – JimB Oct 27 '19 at 00:02
  • @JimB Good point, I agree about calling it a warning message. I changed that in the answer. – C. E. Oct 27 '19 at 07:22