forked from diffpy/diffpy.srfit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfitrecipe.py
More file actions
1755 lines (1482 loc) · 59.6 KB
/
fitrecipe.py
File metadata and controls
1755 lines (1482 loc) · 59.6 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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/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.
#
##############################################################################
"""FitRecipe class.
FitRecipes organize FitContributions, variables, Restraints and
Constraints to create a recipe of the system you wish to optimize. From
the client's perspective, the FitRecipe is a residual calculator. The
residual method does the work of updating variable values, which get
propagated to the Parameters of the underlying FitContributions via the
variables and Constraints. This class needs no special knowledge of the
type of FitContribution or data being used. Thus, it is suitable for
combining residual equations from various types of refinements into a
single residual.
Variables added to a FitRecipe can be tagged with string identifiers.
Variables can be later retrieved or manipulated by tag. The tag name
"__fixed" is reserved.
See the examples in the documentation for how to create an optimization
problem using FitRecipe.
"""
__all__ = ["FitRecipe"]
from collections import OrderedDict
from pathlib import Path
import matplotlib.pyplot as plt
from bg_mpl_stylesheets.styles import all_styles
from numpy import array, concatenate, dot, sqrt
import diffpy.srfit.util.inpututils as utils
from diffpy.srfit.fitbase.fithook import PrintFitHook
from diffpy.srfit.fitbase.parameter import ParameterProxy
from diffpy.srfit.fitbase.recipeorganizer import RecipeOrganizer
from diffpy.srfit.interface import _fitrecipe_interface
from diffpy.srfit.util.tagmanager import TagManager
from diffpy.utils._deprecator import build_deprecation_message, deprecated
plt.style.use(all_styles["bg-style"])
base = "diffpy.srfit.fitbase.FitRecipe"
removal_version = "4.0.0"
addcontrib_dep_msg = build_deprecation_message(
base, "addContribution", "add_contribution", removal_version
)
pushfithook_dep_msg = build_deprecation_message(
base, "pushFitHook", "push_fit_hook", removal_version
)
popfithook_dep_msg = build_deprecation_message(
base, "popFitHook", "pop_fit_hook", removal_version
)
getfithooks_dep_msg = build_deprecation_message(
base, "getFitHooks", "get_fit_hooks", removal_version
)
clearfithooks_dep_msg = build_deprecation_message(
base, "clearFitHooks", "clear_fit_hooks", removal_version
)
setweight_dep_msg = build_deprecation_message(
base, "setWeight", "set_weight", removal_version
)
addparset_dep_msg = build_deprecation_message(
base, "addParameterSet", "add_parameter_set", removal_version
)
removeParameterSet_dep_msg = build_deprecation_message(
base, "removeParameterSet", "remove_parameter_set", removal_version
)
scalarResidual_dep_msg = build_deprecation_message(
base, "scalarResidual", "scalar_residual", removal_version
)
addVar_dep_msg = build_deprecation_message(
base, "addVar", "add_variable", removal_version
)
delVar_dep_msg = build_deprecation_message(
base, "delVar", "delete_variable", removal_version
)
newVar_dep_msg = build_deprecation_message(
base, "newVar", "create_new_variable", removal_version
)
isFree_dep_msg = build_deprecation_message(
base, "isFree", "is_free", removal_version
)
getValues_dep_msg = build_deprecation_message(
base, "getValues", "get_values", removal_version
)
getNames_dep_msg = build_deprecation_message(
base, "getNames", "get_names", removal_version
)
getBounds_dep_msg = build_deprecation_message(
base, "getBounds", "get_bounds_pairs", removal_version
)
getBounds2_dep_msg = build_deprecation_message(
base, "getBounds2", "get_bounds_array", removal_version
)
boundsToRestraints_dep_msg = build_deprecation_message(
base, "boundsToRestraints", "convert_bounds_to_restraints", removal_version
)
class FitRecipe(_fitrecipe_interface, RecipeOrganizer):
"""FitRecipe class.
Attributes
----------
name : str
A name for this FitRecipe.
fithooks : list
The list of FitHook instances that can pass information out
of the system during a refinement. By default, this is
populated by a PrintFitHook instance.
_constraints : dict
The dictionary of Constraints, indexed by the constrained
Parameter. Constraints can be added using the
'constrain' method.
_oconstraints : list
The ordered list of the constraints from this and all
sub-components.
_calculators : dict
The managed dictionary of Calculators.
_contributions : OrderedDict
The managed OrderedDict of FitContributions.
_parameters : OrderedDict
The managed OrderedDict of parameters (in this case the
parameters are varied).
_parsets : dict
The managed dictionary of ParameterSets.
_eqfactory : diffpy.srfit.equation.builder.EquationFactory
The diffpy.srfit.equation.builder.EquationFactory
instance that is used to create constraints and
restraints from strings.
_restraintlist : list
The list of restraints from this and all sub-components.
_restraints : set
The set of Restraints. Restraints can be added using the
'restrain' or 'confine' methods.
_ready : bool
The flag indicating if all attributes are ready for the
calculation.
_tagmanager : TagManager
The TagManager instance for managing tags on Parameters.
_weights : list
The list of weighing factors for each FitContribution. The
weights are multiplied by the residual of the
FitContribution when determining the overall residual.
_fixedtag : str
"__fixed", used for tagging variables as fixed. Don't
use this tag unless you want issues.
Properties
----------
names : list
The variable names (read only). See get_names.
values : numpy.ndarray
The variable values (read only). See get_values.
fixednames : list
The names of the fixed refinable variables (read only).
fixedvalues : numpy.ndarray
The values of the fixed refinable variables (read only).
bounds : list of tuple
The bounds on parameters (read only). See get_bounds_pairs.
bounds2 : tuple of numpy.ndarray
The bounds on parameters (read only). See get_bounds_array.
"""
fixednames = property(
lambda self: [
v.name
for v in self._parameters.values()
if not (self.is_free(v) or self.is_constrained(v))
],
doc="names of the fixed refinable variables",
)
fixedvalues = property(
lambda self: array(
[
v.value
for v in self._parameters.values()
if not (self.is_free(v) or self.is_constrained(v))
]
),
doc="values of the fixed refinable variables",
)
bounds = property(lambda self: self.get_bounds_pairs())
bounds2 = property(lambda self: self.get_bounds_array())
def __init__(self, name="fit"):
"""Initialization."""
RecipeOrganizer.__init__(self, name)
self.fithooks = []
self.pushFitHook(PrintFitHook())
self._restraintlist = []
self._oconstraints = []
self._ready = False
self._fixedtag = "__fixed"
self._weights = []
self._tagmanager = TagManager()
self._parsets = {}
self._manage(self._parsets)
self._contributions = OrderedDict()
self._manage(self._contributions)
self.plot_options = {
"show_observed": True,
"show_fit": True,
"show_diff": True,
"offset_scale": 1.0,
"xmin": None,
"xmax": None,
"figsize": (8, 6),
"data_style": "o",
"fit_style": "-",
"diff_style": "-",
"data_color": None,
"fit_color": None,
"diff_color": None,
"data_label": "Observed",
"fit_label": "Calculated",
"diff_label": "Difference",
"xlabel": None,
"ylabel": None,
"title": None,
"legend": True,
"legend_loc": "best",
"grid": False,
"markersize": None,
"linewidth": None,
"alpha": 1.0,
"show": True,
}
return
def push_fit_hook(self, fithook, index=None):
"""Add a FitHook to be called within the residual method.
The hook is an object for reporting updates, or more fundamentally,
passing information out of the system during a refinement. See the
diffpy.srfit.fitbase.fithook.FitHook class for the required interface.
Added FitHooks will be called sequentially during refinement.
Parameters
----------
fithook : diffpy.srfit.fitbase.fithook.FitHook
The FitHook instance to add to the sequence.
index : int or None, optional
The index for inserting fithook into the list of fit hooks. If
this is None (default), the fithook is added to the end.
"""
if index is None:
index = len(self.fithooks)
self.fithooks.insert(index, fithook)
# Make sure the added FitHook gets its reset method called.
self._update_configuration()
return
@deprecated(pushfithook_dep_msg)
def pushFitHook(self, fithook, index=None):
"""This function has been deprecated and will be removed in version
4.0.0.
Please use diffpy.srfit.fitbase.FitRecipe.push_fit_hook instead.
"""
self.push_fit_hook(fithook, index)
return
def pop_fit_hook(self, fithook=None, index=-1):
"""Remove a FitHook by index or reference.
Parameters
----------
fithook : diffpy.srfit.fitbase.fithook.FitHook or None, optional
The FitHook instance to remove from the sequence. If this is
None (default), default to index.
index : int, optional
The index of FitHook instance to remove (default -1).
Raises
------
ValueError
If fithook is not None, but is not present in the sequence.
IndexError
If the sequence is empty or index is out of range.
"""
if fithook is not None:
self.fithooks.remove(fithook)
return
self.fithook.remove(index)
return
@deprecated(popfithook_dep_msg)
def popFitHook(self, fithook=None, index=-1):
"""This function has been deprecated and will be removed in version
4.0.0.
Please use diffpy.srfit.fitbase.FitRecipe.pop_fit_hook instead.
"""
self.pop_fit_hook(fithook, index)
return
def get_fit_hooks(self):
"""Get the sequence of FitHook instances."""
return self.fithooks[:]
@deprecated(getfithooks_dep_msg)
def getFitHooks(self):
"""This function has been deprecated and will be removed in version
4.0.0.
Please use diffpy.srfit.fitbase.FitRecipe.get_fit_hooks instead."""
return self.get_fit_hooks()
def clear_fit_hooks(self):
"""Clear the FitHook sequence."""
del self.fithooks[:]
return
@deprecated(clearfithooks_dep_msg)
def clearFitHooks(self):
"""This function has been deprecated and will be removed in version
4.0.0.
Please use diffpy.srfit.fitbase.FitRecipe.clear_fit_hooks instead."""
self.clear_fit_hooks()
return
def add_contribution(self, con, weight=1.0):
"""Add a FitContribution to the FitRecipe.
Parameters
----------
con : FitContribution
The FitContribution to be stored.
weight : float, optional
The weight of the FitContribution. Default is 1.0.
Raises
------
ValueError
If the FitContribution has no name or if the FitContribution has
the same name as some other managed object.
"""
self._add_object(con, self._contributions, True)
self._weights.append(weight)
return
@deprecated(addcontrib_dep_msg)
def addContribution(self, con, weight=1.0):
"""This function has been deprecated and will be removed in version
4.0.0.
Please use diffpy.srfit.fitbase.FitRecipe.add_contribution
instead.
"""
self.add_contribution(con, weight)
return
def set_weight(self, con, weight):
"""Set the weight of a FitContribution.
Parameters
----------
con : FitContribution
The FitContribution object whose weight is to be set.
weight : float
The weight value to assign to the specified FitContribution.
Returns
-------
None
"""
idx = list(self._contributions.values()).index(con)
self._weights[idx] = weight
return
@deprecated(setweight_dep_msg)
def setWeight(self, con, weight):
"""This function has been deprecated and will be removed in version
4.0.0.
Please use diffpy.srfit.fitbase.FitRecipe.set_weight instead."""
self.set_weight(con, weight)
return
def add_parameter_set(self, parset):
"""Add a ParameterSet to the hierarchy.
Parameters
----------
parset : ParameterSet
The ParameterSet to be stored.
Raises
------
ValueError
If the ParameterSet has no name or if the ParameterSet has the same
name as some other managed object.
"""
self._add_object(parset, self._parsets, True)
return
@deprecated(addparset_dep_msg)
def addParameterSet(self, parset):
"""This function has been deprecated and will be removed in version
4.0.0.
Please use diffpy.srfit.fitbase.FitRecipe.add_parameter_set instead.
"""
self.add_parameter_set(parset)
return
def remove_parameter_set(self, parset):
"""Remove a ParameterSet from the hierarchy.
This method removes the specified ParameterSet object from the internal
hierarchy of managed ParameterSets. If the provided ParameterSet is not
currently managed by this object, a ValueError will be raised.
Parameters:
-----------
parset : ParameterSet
The ParameterSet instance to be removed from the hierarchy.
Raises:
-------
ValueError
If the provided ParameterSet is not managed by this object.
"""
self._remove_object(parset, self._parsets)
return
@deprecated(removeParameterSet_dep_msg)
def removeParameterSet(self, parset):
"""This function has been deprecated and will be removed in version
4.0.0.
Please use diffpy.srfit.fitbase.FitRecipe.remove_parameter_set instead.
"""
self.remove_parameter_set(parset)
return
def residual(self, p=[]):
"""Calculate the vector residual to be optimized.
Parameters
----------
p : list or numpy.ndarray
The list of current variable values, provided in the same order
as the '_parameters' list. If p is an empty iterable (default),
then it is assumed that the parameters have already been
updated in some other way, and the explicit update within this
function is skipped.
The residual is by default the weighted concatenation of each
FitContribution's residual, plus the value of each restraint. The array
returned, denoted chiv, is such that
dot(chiv, chiv) = chi^2 + restraints.
"""
# Prepare, if necessary
self._prepare()
for fithook in self.fithooks:
fithook.precall(self)
# Update the variable parameters.
self._apply_values(p)
# Update the constraints. These are ordered such that the list only
# needs to be cycled once.
for con in self._oconstraints:
con.update()
# Calculate the bare chiv
chiv = concatenate(
[
wi * ci.residual().flatten()
for wi, ci in zip(self._weights, self._contributions.values())
]
)
# Calculate the point-average chi^2
w = dot(chiv, chiv) / len(chiv)
# Now we must append the restraints
penalties = [sqrt(res.penalty(w)) for res in self._restraintlist]
chiv = concatenate([chiv, penalties])
for fithook in self.fithooks:
fithook.postcall(self, chiv)
return chiv
def scalar_residual(self, p=[]):
"""Calculate the scalar residual to be optimized.
Parameters
----------
p : list or numpy.ndarray
The list of current variable values, provided in the same order
as the '_parameters' list. If p is an empty iterable (default),
then it is assumed that the parameters have already been
updated in some other way, and the explicit update within this
function is skipped.
The residual is by default the weighted concatenation of each
FitContribution's residual, plus the value of each restraint. The array
returned, denoted chiv, is such that
dot(chiv, chiv) = chi^2 + restraints.
"""
chiv = self.residual(p)
return dot(chiv, chiv)
@deprecated(scalarResidual_dep_msg)
def scalarResidual(self, p=[]):
"""This function has been deprecated and will be removed in version
4.0.0.
Please use diffpy.srfit.fitbase.FitRecipe.scalar_residual
instead.
"""
return self.scalar_residual(p)
def __call__(self, p=[]):
"""Same as scalar_residual method."""
return self.scalar_residual(p)
def _prepare(self):
"""Prepare for the residual calculation, if necessary.
This will prepare the data attributes to be used in the residual
calculation.
This updates the local restraints with those of the
contributions.
Raises
------
AttributeError
If there are variables without a value.
"""
# Only prepare if the configuration has changed within the recipe
# hierarchy.
if self._ready:
return
# Inform the fit hooks that we're updating things
for fithook in self.fithooks:
fithook.reset(self)
# Check Profiles
self.__verify_profiles()
# Check parameters
self.__verify_parameters()
# Update constraints and restraints.
self.__collect_constraints_and_restraints()
# We do this here so that the calculations that take place during the
# validation use the most current values of the parameters. In most
# cases, this will save us from recalculating them later.
for con in self._oconstraints:
con.update()
# Validate!
self._validate()
self._ready = True
return
def __verify_profiles(self):
"""Verify that each FitContribution has a Profile."""
# Check for profile values
for con in self._contributions.values():
if con.profile is None:
m = "FitContribution '%s' does not have a Profile" % con.name
raise AttributeError(m)
if (
con.profile.x is None
or con.profile.y is None
or con.profile.dy is None
):
m = "Profile for '%s' is missing data" % con.name
raise AttributeError(m)
return
def __verify_parameters(self):
"""Verify that all Parameters have values."""
# Get all parameters with a value of None
badpars = []
for par in self.iterate_over_parameters():
try:
par.getValue()
except ValueError:
badpars.append(par)
# Get the bad names
badnames = []
for par in badpars:
objlist = self._locate_managed_object(par)
names = [obj.name for obj in objlist]
badnames.append(".".join(names))
# Construct an error message, if necessary
m = ""
if len(badnames) == 1:
m = "%s is not defined or needs an initial value" % badnames[0]
elif len(badnames) > 0:
s1 = ",".join(badnames[:-1])
s2 = badnames[-1]
m = "%s and %s are not defined or need initial values" % (s1, s2)
if m:
raise AttributeError(m)
return
def __collect_constraints_and_restraints(self):
"""Collect the Constraints and Restraints from subobjects."""
from functools import cmp_to_key
from itertools import chain
rset = set(self._restraints)
cdict = {}
for org in chain(self._contributions.values(), self._parsets.values()):
rset.update(org._get_restraints())
cdict.update(org._get_constraints())
cdict.update(self._constraints)
# The order of the restraint list does not matter
self._restraintlist = list(rset)
# Reorder the constraints. Constraints are ordered such that a given
# constraint is placed before its dependencies.
self._oconstraints = list(cdict.values())
# Create a depth-1 map of the constraint dependencies
depmap = {}
for con in self._oconstraints:
depmap[con] = set()
# Now check the constraint's equation for constrained arguments
for arg in con.eq.args:
if arg in cdict:
depmap[con].add(cdict[arg])
# Turn the dependency map into multi-level map.
def _extendDeps(con):
deps = set(depmap[con])
for dep in depmap[con]:
deps.update(_extendDeps(dep))
return deps
for con in depmap:
depmap[con] = _extendDeps(con)
# Now sort the constraints based on the dependency map.
def cmp(x, y):
# x == y if neither of them have dependencies
if not depmap[x] and not depmap[y]:
return 0
# x > y if y is a dependency of x
# x > y if y has no dependencies
if y in depmap[x] or not depmap[y]:
return 1
# x < y if x is a dependency of y
# x < y if x has no dependencies
if x in depmap[y] or not depmap[x]:
return -1
# If there are dependencies, but there is no relationship, the
# constraints are equivalent
return 0
self._oconstraints.sort(key=cmp_to_key(cmp))
return
# Variable manipulation
def add_variable(
self, par, value=None, name=None, fixed=False, tag=None, tags=[]
):
"""Add a variable to be refined.
Parameters
----------
par : diffpy.srfit.fitbase.Parameter
The Parameter that will be varied during a fit.
value : float or None, optional
The initial value for the variable. If this is None
(default), then the current value of par will be used.
name : str or None, optional
The name for this variable. If name is None (default), then
the name of the parameter will be used.
fixed : bool, optional
Fix the variable so that it does not vary (default False).
tag : str or None, optional
The tag for the variable. This can be used to retrieve, fix
or free variables by tag (default None). Note that a
variable is automatically tagged with its name and "all".
tags : list of str, optional
The list of tags (default []). Both tag and tags can be
applied.
Returns
-------
ParameterProxy
ParameterProxy (variable) for the passed Parameter.
Raises
------
ValueError
If the name of the variable is already taken by
another managed object.
ValueError
If par is constant.
ValueError
If par is constrained.
"""
name = name or par.name
if par.const:
raise ValueError("The parameter '%s' is constant" % par)
if par.constrained:
raise ValueError("The parameter '%s' is constrained" % par)
var = ParameterProxy(name, par)
if value is not None:
var.set_value(value)
self._add_parameter(var)
if fixed:
self.fix(var)
# Tag with passed tags and by name
self._tagmanager.tag(var, var.name)
self._tagmanager.tag(var, "all")
self._tagmanager.tag(var, *tags)
if tag is not None:
self._tagmanager.tag(var, tag)
return var
@deprecated(addVar_dep_msg)
def addVar(
self, par, value=None, name=None, fixed=False, tag=None, tags=[]
):
"""This function has been deprecated and will be removed in version
4.0.0.
Please use diffpy.srfit.fitbase.FitRecipe.add_variable instead.
"""
return self.add_variable(par, value, name, fixed, tag, tags)
def delete_variable(self, var):
"""Remove a variable.
Note that constraints and restraints involving the variable are not
modified.
Parameters
----------
var : ParameterProxy
A variable of the FitRecipe.
Raises
------
ValueError
If var is not part of the FitRecipe.
"""
self._remove_parameter(var)
self._tagmanager.untag(var)
return
@deprecated(delVar_dep_msg)
def delVar(self, var):
"""This function has been deprecated and will be removed in version
4.0.0.
Please use diffpy.srfit.fitbase.FitRecipe.delete_variable instead.
"""
self.delete_variable(var)
return
def __delattr__(self, name):
if name in self._parameters:
self.delete_variable(self._parameters[name])
return
super(FitRecipe, self).__delattr__(name)
return
def create_new_variable(
self, name, value=None, fixed=False, tag=None, tags=[]
):
"""Create a new variable of the fit.
This method lets new variables be created that are not tied to a
Parameter. Orphan variables may cause a fit to fail, depending on the
optimization routine, and therefore should only be created to be used
in constraint or restraint equations.
Parameters
----------
name : str
The name of the variable. The variable will be able to be
used by this name in restraint and constraint equations.
value : float or None, optional
The initial value for the variable. If this is None
(default), then the variable will be given the value of the
first non-None-valued Parameter constrained to it. If this
fails, an error will be thrown when 'residual' is called.
fixed : bool, optional
Fix the variable so that it does not vary (default False).
The variable will still be managed by the FitRecipe.
tag : str or None, optional
The tag for the variable. This can be used to fix and free
variables by tag (default None). Note that a variable is
automatically tagged with its name and "all".
tags : list of str, optional
The list of tags (default []). Both tag and tags can be
applied.
Returns
-------
Parameter
The new variable (Parameter instance).
"""
# This will fix the Parameter
var = self._new_parameter(name, value)
# We may explicitly free it
if not fixed:
self.free(var)
# Tag with passed tags
self._tagmanager.tag(var, *tags)
if tag is not None:
self._tagmanager.tag(var, tag)
return var
@deprecated(newVar_dep_msg)
def newVar(self, name, value=None, fixed=False, tag=None, tags=[]):
"""This function has been deprecated and will be removed in version
4.0.0.
Please use diffpy.srfit.fitbase.FitRecipe.create_new_variable instead.
"""
return self.create_new_variable(name, value, fixed, tag, tags)
def _new_parameter(self, name, value, check=True):
"""Overloaded to tag variables.
See RecipeOrganizer._new_parameter
"""
par = RecipeOrganizer._new_parameter(self, name, value, check)
# tag this
self._tagmanager.tag(par, par.name)
self._tagmanager.tag(par, "all")
self.fix(par.name)
return par
def __get_var_and_check(self, var):
"""Get the actual variable from var.
Attributes
----------
var
A variable of the FitRecipe, or the name of a variable.
Returns the variable or None if the variable cannot be found in the
_parameters list.
"""
if isinstance(var, str):
var = self._parameters.get(var)
if var not in self._parameters.values():
raise ValueError("Passed variable is not part of the FitRecipe")
return var
def __get_vars_from_args(self, *args, **kw):
"""Get a list of variables from passed arguments.
This method accepts string or variable arguments. An argument of
"all" selects all variables. Keyword arguments must be parameter
names, followed by a value to assign to the fixed variable. This
method is used by the fix and free methods.
Raises ValueError if an unknown variable, name or tag is passed,
or if a tag is passed in a keyword.
"""
# Process args. Each variable is tagged with its name, so this is easy.
strargs = set([arg for arg in args if isinstance(arg, str)])
varargs = set(args) - strargs
# Check that the tags are valid
alltags = set(self._tagmanager.alltags())
badtags = strargs - alltags
if badtags:
names = ",".join(badtags)
raise ValueError("Variables or tags cannot be found (%s)" % names)
# Check that variables are valid
allvars = set(self._parameters.values())
badvars = varargs - allvars
if badvars:
names = ",".join(v.name for v in badvars)
raise ValueError("Variables cannot be found (%s)" % names)
# Make sure that we only have parameters in kw
kwnames = set(kw.keys())
allnames = set(self._parameters.keys())
badkw = kwnames - allnames
if badkw:
names = ",".join(badkw)
raise ValueError("Tags cannot be passed as keywords (%s)" % names)
# Now get all the objects referred to in the arguments.
varargs |= self._tagmanager.union(*strargs)
varargs |= self._tagmanager.union(*kw.keys())
return varargs
def fix(self, *args, **kw):
"""Fix one or more parameters by reference, name, or tag.
This method marks specified parameters as fixed, meaning they will not
be refined during the fitting process. By default, all parameters are
free (not fixed). Parameters can be specified using their references,
names, or tags. Additionally, keyword arguments can be used to assign
specific values to the fixed parameters.
Parameters
----------
*args : str or Parameter
The positional arguments specifying the parameters to fix.
These can be parameter objects, their names as strings, or
tags. The special string "all" can be used to select all
parameters.
**kw : dict
The keyword arguments where the keys are parameter names and
the values are the values to assign to the corresponding
fixed parameters.
Raises
------
ValueError:
If an unknown parameter, name, or tag is passed, or if a
tag is passed as a keyword argument.
Example
-------
::
# Fix a parameter by reference
recipe.fix(param1)
# Fix a parameter by name
recipe.fix("param2")
# Fix all parameters
recipe.fix("all")
# Fix parameters by tag
recipe.fix(tag="group1")
# Fix a parameter and assign it a value
recipe.fix(param3=10.0)
"""
# Check the inputs and get the variables from them
varargs = self.__get_vars_from_args(*args, **kw)