Skip to content

Commit c42998e

Browse files
committed
Address problems with constraints reported in astropy#1060 and astropy#1064
1 parent d830fd9 commit c42998e

4 files changed

Lines changed: 38 additions & 52 deletions

File tree

‎astropy/modeling/core.py‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -362,22 +362,28 @@ class ParametricModel(Model):
362362
problem.
363363
"""
364364
__metaclass__ = abc.ABCMeta
365-
365+
366366
def __init__(self, param_names, n_inputs, n_outputs, param_dim=1, fittable=True,
367-
fixed={}, tied={}, bounds={}, eqcons=[], ineqcons=[]):
367+
fixed=None, tied=None, bounds=None, eqcons=None, ineqcons=None):
368368
self.linear = True
369369
super(ParametricModel, self).__init__(param_names, n_inputs, n_outputs, param_dim=param_dim)
370370
self.fittable = fittable
371371
self._parameters = parameters.Parameters(self, self.param_names,
372372
param_dim=param_dim)
373+
# Initialize the constraints for each parameter
373374
_fixed = {}.fromkeys(self.param_names, False)
374375
_tied = {}.fromkeys(self.param_names, False)
375376
_bounds = {}.fromkeys(self.param_names, [-1.E12, 1.E12])
377+
if eqcons is None:
378+
eqcons = []
379+
if ineqcons is None:
380+
ineqcons = []
376381
self.constraints = constraints.Constraints(self, fixed=_fixed,
377382
tied=_tied,
378383
bounds=_bounds,
379384
eqcons=eqcons,
380385
ineqcons=ineqcons)
386+
# Set constraints
381387
if fixed:
382388
for name in fixed:
383389
par = getattr(self, name)
@@ -389,10 +395,9 @@ def __init__(self, param_names, n_inputs, n_outputs, param_dim=1, fittable=True,
389395
if bounds:
390396
for name in bounds:
391397
par = getattr(self, name)
392-
setattr(par, 'min', bounds[0])
393-
setattr(par, 'max', bounds[1])
394-
395-
398+
setattr(par, 'min', bounds[name][0])
399+
setattr(par, 'max', bounds[name][1])
400+
396401
def __repr__(self):
397402
try:
398403
degree = str(self.deg)

‎astropy/modeling/fitting.py‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -116,11 +116,9 @@ def fitpars(self, fps):
116116
any(self.model.constraints._tied.values()):
117117
self.model.constraints.fitpars = fps
118118
self._fitpars[:] = self.model.constraints.fitpars
119+
elif any([b != (-1E12, 1E12) for b in self.model.constraints.bounds.values()]):
120+
self._set_bounds(fps)
119121
else:
120-
try:
121-
self._set_bounds(fps)
122-
except NotImplementedError:
123-
pass
124122
self._fitpars[:] = fps
125123
self.model.parameters = fps
126124

‎astropy/modeling/functional_models.py‎

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -147,43 +147,35 @@ def __init__(self, amplitude, x_mean, y_mean, x_fwhm=None, y_fwhm=None,
147147
raise InputParameterError(
148148
"Either x_fwhm or x_stddev must be specified, or a "
149149
"covariance matrix.")
150-
151150
self._amplitude = parameters.Parameter('amplitude', amplitude,
152151
self, param_dim)
153-
154152
if cov_matrix is None:
155153
if x_stddev is None:
156154
x_stddev = 0.42466 * x_fwhm
157-
158155
if y_stddev is None:
159156
y_stddev = 0.42466 * y_fwhm
160-
161157
else:
162158
cov_matrix = np.array(cov_matrix)
163159
assert cov_matrix.shape == (2,2), "Covariance matrix must be 2D"
164-
165160
eig_vals, eig_vecs = np.linalg.eig(cov_matrix)
166161
x_stddev, y_stddev = np.sqrt(eig_vals)
167162
y_vec = eig_vecs[:,0]
168163
theta = np.arctan2(y_vec[1],y_vec[0])
169-
170164
self._x_stddev = parameters.Parameter('x_stddev', x_stddev,
171165
self, param_dim)
172166
self._y_stddev = parameters.Parameter('y_stddev', y_stddev,
173167
self, param_dim)
174-
175168
self._x_mean = parameters.Parameter('x_mean', x_mean, self, param_dim)
176169
self._y_mean = parameters.Parameter('y_mean', y_mean, self, param_dim)
177170
self._theta = parameters.Parameter('theta', theta, self, param_dim)
178-
179171
super(Gaussian2DModel, self).__init__(self.param_names, n_inputs=2, n_outputs=1,
180-
param_dim=param_dim)
172+
param_dim=param_dim, **cons)
181173
self.linear = False
182174
if jacobian_func:
183175
self.deriv = jacobian_func
184176
else:
185177
self.deriv = None
186-
178+
187179
def eval(self, x, y, p):
188180
return p[0] * np.exp(-(
189181
((np.cos(p[5])/p[1])**2 + (np.sin(p[5])/p[2])**2) * ((x-p[3])**2)

‎astropy/modeling/parameters.py‎

Lines changed: 23 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -32,15 +32,14 @@ def _tofloat(value):
3232
raise InputParameterError(
3333
"Expected parameter to be of numerical type, not boolean")
3434
elif isinstance(value, numbers.Number):
35-
#_value = np.array(value, dtype=np.float)
3635
_value = float(value)
3736
shape = ()
3837
else:
3938
raise InputParameterError(
4039
"Don't know how to convert parameter of {0} to "
4140
"float".format(type(value)))
4241
return _value, shape
43-
42+
4443
class Parameter(list):
4544
"""
4645
Wraps individual parameters.
@@ -66,17 +65,16 @@ class Parameter(list):
6665
if True the parameter is not varied during fitting
6766
tied: callable or False
6867
if callable is suplplied it provides a way to link to another parameter
69-
minvalue: float
68+
min: float
7069
the lower bound of a parameter
71-
maxvalue: float
70+
max: float
7271
the upper bound of a parameter
7372
"""
7473
def __init__(self, name, val, mclass, param_dim, fixed=False, tied=False,
75-
minvalue=None, maxvalue=None):
74+
min=None, max=None):
7675
self._param_dim = param_dim
7776
self._name = name
7877
if self._param_dim == 1:
79-
# number, list or array
8078
val, parshape = _tofloat(val)
8179
super(Parameter, self).__init__([val])
8280
else:
@@ -90,112 +88,105 @@ def __init__(self, name, val, mclass, param_dim, fixed=False, tied=False,
9088
except TypeError:
9189
raise InputParameterError("Expected a multivalued"
9290
" parameter {0}".format(self._name))
93-
94-
## if parshape == ():
95-
## # a list of numbers
96-
9791
for shape in [_tofloat(v)[1] for v in val]:
9892
assert shape == parshape, "Multiple values for the same" \
9993
" parameters should have the same shape"
100-
## else:
101-
## # a list of lists or a list of arrays
102-
## val = [_tofloat(v)[0] for v in val]
10394
super(Parameter, self).__init__(val)
10495
self.parshape = parshape
10596
self._mclass = mclass
10697
self._fixed = fixed
10798
self._tied = tied
108-
self._min = minvalue
109-
self._max = maxvalue
110-
99+
self._min = min
100+
self._max = max
101+
111102
@property
112103
def param_dim(self):
113104
"""
114105
Number of parameter sets
115106
"""
116107
return self._param_dim
117-
108+
118109
@param_dim.setter
119110
def param_dim(self, val):
120111
self._param_dim = val
121-
112+
122113
@property
123114
def mclass(self):
124115
"""
125116
An instance of `~astropy.modeling.core.ParametricModel`
126117
"""
127118
return self._mclass
128-
119+
129120
@mclass.setter
130121
def mclass(self, val):
131122
self._mclass = val
132-
123+
133124
@property
134125
def name(self):
135126
"""
136127
Parameter name
137128
"""
138129
return self._name
139-
130+
140131
@name.setter
141132
def name(self, val):
142133
self._name = val
143-
134+
144135
@property
145136
def fixed(self):
146137
"""
147138
Boolean indicating if the parameter is kept fixed during fitting.
148139
149140
"""
150141
return self._fixed
151-
142+
152143
@fixed.setter
153144
def fixed(self, val):
154145
assert isinstance(val, bool), "Fixed can be True or False"
155146
self._fixed = val
156147
self.mclass.constraints._fixed.update({self.name: val})
157148
self.mclass.constraints._update()
158-
149+
159150
@property
160151
def tied(self):
161152
"""
162153
Indicates that this parameter is linked to another one.
163154
A callable which provides the relationship of the two parameters.
164155
"""
165156
return self._tied
166-
157+
167158
@tied.setter
168159
def tied(self, val):
169-
assert callable(val), "Tied must be a callable"
160+
assert callable(val) or val == False, "Tied must be a callable"
170161
self._tied = val
171162
self.mclass.constraints._tied.update({self.name:val})
172163
self.mclass.constraints._update()
173-
164+
174165
@property
175166
def min(self):
176167
"""
177168
A value used as a lower bound when fitting a parameter.
178169
"""
179170
return self._min
180-
171+
181172
@min.setter
182173
def min(self, val):
183174
assert isinstance(val, numbers.Number), "Min value must be a number"
184175
self._min = float(val)
185-
self.mclass.constraints.set_range({self.name: (val, self.max or 1E12)})
186-
176+
self.mclass.constraints.set_range({self.name: (val, self.max)})
177+
187178
@property
188179
def max(self):
189180
"""
190181
A value used as an upper bound when fitting a parameter.
191182
"""
192183
return self._max
193-
184+
194185
@max.setter
195186
def max(self, val):
196187
assert isinstance(val, numbers.Number), "Max value must be a number"
197188
self._max = float(val)
198-
self.mclass.constraints.set_range({self.name: (self.min or -1E12, val)})
189+
self.mclass.constraints.set_range({self.name: (self.min, val)})
199190

200191
def __setslice__(self, i, j, val):
201192
super(Parameter, self).__setslice__(i, j, val)

0 commit comments

Comments
 (0)