forked from diffpy/diffpy.srfit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparameter.py
More file actions
388 lines (312 loc) · 11.2 KB
/
parameter.py
File metadata and controls
388 lines (312 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
#!/usr/bin/env python
##############################################################################
#
# diffpy.srfit by DANSE Diffraction group
# Simon J. L. Billinge
# (c) 2008 The Trustees of Columbia University
# in the City of New York. All rights reserved.
#
# File coded by: Chris Farrow
#
# See AUTHORS.txt for a list of people who contributed.
# See LICENSE_DANSE.txt for license information.
#
##############################################################################
"""Parameter classes.
Parameters encapsulate an adjustable parameter within SrFit.
"""
# IDEA - Add onConstrain, onRestrain, onVary so that adaptors to Parameters
# can have more fine control over the construction of FitRecipes.
# IDEA - Add tags to parameters so they can be easily retrieved.
# IDEA - Consider scaling parameters to avoid precision issues in optimizers.
__all__ = ["Parameter", "ParameterProxy", "ParameterAdapter"]
from functools import wraps
import numpy
from diffpy.srfit.equation.literals import Argument
from diffpy.srfit.exceptions import SrFitError
from diffpy.srfit.fitbase.validatable import Validatable
from diffpy.srfit.interface import _parameter_interface
from diffpy.srfit.util.argbinders import bind2nd
from diffpy.srfit.util.nameutils import validateName
from diffpy.utils._deprecator import build_deprecation_message, deprecated
parameter_base = "diffpy.srfit.fitbase.Parameter"
removal_version = "4.0.0"
setValue_dep_msg = build_deprecation_message(
parameter_base, "setValue", "set_value", removal_version
)
class Parameter(_parameter_interface, Argument, Validatable):
"""Parameter class.
Attributes
----------
name
A name for this Parameter.
const
A flag indicating whether this is considered a constant.
_value
The value of the Parameter. Modified with 'set_value'.
value
Property for 'getValue' and 'set_value'.
constrained
A flag indicating if the Parameter is constrained
(default False).
bounds
A 2-list defining the bounds on the Parameter. This can be
used by some optimizers when the Parameter is varied. See
FitRecipe.get_bounds_pairs and FitRecipe.convert_bounds_to_restraints.
"""
def __init__(self, name, value=None, const=False):
"""Initialization.
Attributes
----------
name
The name of this Parameter (must be a valid attribute
identifier)
value
The initial value of this Parameter (default 0).
const
A flag inticating whether the Parameter is a constant (like
pi).
Raises ValueError if the name is not a valid attribute identifier
"""
self.constrained = False
self.bounds = [-numpy.inf, +numpy.inf]
validateName(name)
Argument.__init__(self, name, value, const)
return
def set_value(self, val):
"""Set the value of the Parameter and the bounds.
Attributes
----------
val
The value to assign.
lb
The lower bounds for the bounds list. If this is None
(default), then the lower bound will not be alterered.
ub
The upper bounds for the bounds list. If this is None
(default), then the upper bound will not be alterered.
Returns
-------
self
Returns self so that mutators can be chained.
"""
Argument.set_value(self, val)
return self
@deprecated(setValue_dep_msg)
def setValue(self, val):
"""This function has been deprecated and will be removed in
version 4.0.0.
Please use diffpy.srfit.fitbase.Parameter.set_value instead.
"""
return self.set_value(val)
def setConst(self, const=True, value=None):
"""Toggle the Parameter as constant.
Attributes
----------
const
Flag indicating if the parameter is constant (default
True).
value
An optional value for the parameter (default None). If this
is not None, then the parameter will get a new value,
constant or otherwise.
Returns
-------
self
Returns self so that mutators can be chained.
"""
self.const = bool(const)
if value is not None:
self.set_value(value)
return self
def boundRange(self, lb=None, ub=None):
"""Set lower and upper bound of the Parameter.
Attributes
----------
lb
The lower bound for the bounds list.
ub
The upper bound for the bounds list.
Returns
-------
self
Returns self so that mutators can be chained.
"""
if lb is not None:
self.bounds[0] = lb
if ub is not None:
self.bounds[1] = ub
return self
def boundWindow(self, lr=0, ur=None):
"""Create bounds centered on the current value of the Parameter.
Attributes
----------
lr
The radius of the lower bound (default 0). The lower bound is
computed as value - lr.
ur
The radius of the upper bound. The upper bound is computed as
value + ur. If this is None (default), then the value of the
lower radius is used.
Returns
-------
self
Returns self so that mutators can be chained.
"""
val = self.getValue()
lb = val - lr
if ur is None:
ur = lr
ub = val + ur
self.bounds = [lb, ub]
return self
def _validate(self):
"""Validate my state.
This validates that value is not None.
Raises SrFitError if validation fails.
"""
if self.value is None:
raise SrFitError("value of '%s' is None" % self.name)
return
# End class Parameter
class ParameterProxy(Parameter):
"""A Parameter proxy for another parameter.
This allows for the same parameter to have multiple names.
Attributes
----------
name
A name for this ParameterProxy. Names should be unique within a
RecipeOrganizer and should be valid attribute names.
par
The Parameter this is a proxy for.
"""
def __init__(self, name, par):
"""Initialization.
Attributes
----------
name
The name of this ParameterProxy.
par
The Parameter this is a proxy for.
Raises ValueError if the name is not a valid attribute identifier
"""
validateName(name)
self.name = name
self.par = par
return
# define properties to use attributes of the proxied Parameter -----------
@property
def constrained(self):
"""A flag indicating if the proxied Parameter is constrained."""
return self.par.constrained
@constrained.setter
def constrained(self, value):
self.par.constrained = bool(value)
return
@property
def bounds(self):
"""List of lower and upper bounds of the proxied Parameter.
This can be used by some optimizers when the Parameter is
varied. See FitRecipe.get_bounds_pairs and
FitRecipe.convert_bounds_to_restraints.
"""
return self.par.bounds
@bounds.setter
def bounds(self, value):
self.par.bounds = value
return
@property
def _observers(self):
return self.par._observers
# wrap Parameter methods to use the target object ------------------------
@wraps(Parameter.set_value)
def set_value(self, val):
return self.par.set_value(val)
@wraps(Parameter.getValue)
def getValue(self):
return self.par.getValue()
@wraps(Parameter.setConst)
def setConst(self, const=True, value=None):
return self.par.setConst(const, value)
@wraps(Parameter.boundRange)
def boundRange(self, lb=None, ub=None):
return self.par.boundRange(lb, ub)
@wraps(Parameter.boundWindow)
def boundWindow(self, lr=0, ur=None):
return self.par.boundWindow(lr, ur)
def _validate(self):
"""Validate my state.
This validates that value and par are not None.
Raises SrFitError if validation fails.
"""
if self.par is None:
raise SrFitError("par is None")
self.par._validate()
return
# End class ParameterProxy
class ParameterAdapter(Parameter):
"""An adapter for parameter-like objects.
This class wraps an object as a Parameter. The getValue and
set_value methods defer to the data of the wrapped object.
"""
def __init__(self, name, obj, getter=None, setter=None, attr=None):
"""Wrap an object as a Parameter.
Attributes
----------
name
The name of this Parameter.
obj
The object to be wrapped.
getter
The unbound function that can be used to access the
attribute containing the parameter value. getter(obj)
should return the Parameter value. If getter is None
(default), it is assumed that an attribute is accessed
via attr. If attr is also specified, then the Parameter
value will be accessed via getter(obj, attr).
setter
The unbound function that can be used to modify the
attribute containing the parameter value.
setter(obj, value) should set the attribute to the
passed value. If setter is None (default), it is assumed
that an attribute is accessed via attr. If attr is also
specified, then the Parameter value will be set via
setter(obj, attr, value).
attr
The name of the attribute that contains the value of the
parameter. If attr is None (default), then both getter and
setter must be specified.
Raises ValueError if exactly one of getter or setter is not None, or if
getter, setter and attr are all None.
"""
if getter is None and setter is None and attr is None:
raise ValueError("Specify attribute access")
if [getter, setter].count(None) == 1:
raise ValueError("Specify both getter and setter")
self.obj = obj
self.getter = getter
self.setter = setter
self.attr = attr
if attr is not None:
if getter is None:
self.getter = bind2nd(getattr, self.attr)
else:
self.getter = bind2nd(getter, self.attr)
if setter is None:
self.setter = bind2nd(setattr, self.attr)
else:
self.setter = bind2nd(setter, self.attr)
value = self.getValue()
Parameter.__init__(self, name, value)
return
def getValue(self):
"""Get the value of the Parameter."""
return self.getter(self.obj)
def set_value(self, value):
"""Set the value of the Parameter."""
if value != self.getValue():
self.setter(self.obj, value)
self.notify()
return self
# End class ParameterAdapter
# End of file