forked from diffpy/diffpy.srmise
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodelcluster.py
1439 lines (1209 loc) · 53.6 KB
/
modelcluster.py
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
##############################################################################
#
# SrMise by Luke Granlund
# (c) 2014 trustees of the Michigan State University
# (c) 2024 trustees of Columbia University in the City of New York
# All rights reserved.
#
# File coded by: Luke Granlund
#
# See LICENSE.txt for license information.
#
##############################################################################
"""Defines ModelCluster class.
Classes
-------
ModelCluster: Associate a region of data to a model that describes it.
ModelCovariance: Helper class for model covariance.
"""
import logging
import re
import sys
import numpy as np
from diffpy.srmise import srmiselog
from diffpy.srmise.baselines import Baseline
from diffpy.srmise.modelparts import ModelParts
from diffpy.srmise.peaks import Peak, Peaks
from diffpy.srmise.srmiseerrors import (
SrMiseDataFormatError,
SrMiseEstimationError,
SrMiseFitError,
SrMiseUndefinedCovarianceError,
)
logger = logging.getLogger("diffpy.srmise")
class ModelCovariance(object):
"""Helper class preserves uncertainty info (full covariance matrix) for a fit model.
This object preserves a light-weight "frozen" version of a model which can be used
to interrogate the model about the uncertainties of its parameters.
Note that all parameters defined by a model, including fixed ones, are included in the
covariance matrix. Fixed parameters are defined to have 0 uncertainty.
Methods
-------
"""
def __init__(self, *args, **kwds):
"""Intialize object."""
self.cov = None # The raw covariance matrix
self.model = None # ModelParts instance, so both peaks and baseline (if present)
# Map i->[n1,n2,...] of the jth ModelPart to the n_i parameters in cov.
self.mmap = {}
# Map (i,j)->n of jth parameter of ith ModelPart to nth parameter in cov.
self.pmap = {}
# Map n->(i,j), inverse of pmap.
self.ipmap = {}
def clear(self):
"""Reset object."""
self.cov = None
self.model = None
self.mmap = {}
self.pmap = {}
self.ipmap = {}
def setcovariance(self, model, cov):
"""Set model and covariance.
Automatically initializes covariance matrix to full set of parameters in model, even
those listed as "fixed."
Parameters
----------
model - A ModelParts object
cov - The nxn covariance matrix for n model parameters. If the parameterization includes "fixed"
parameters not included in the covariance matrix, the matrix is expanded to include these
parameters with 0 uncertainty.
"""
tempcov = np.array(cov)
if tempcov.shape[0] != tempcov.shape[1]:
emsg = "Parameter 'cov' must be a square matrix."
raise ValueError(emsg)
if tempcov.shape[0] != model.npars(True) and tempcov.shape[0] != model.npars(False):
emsg = [
"Parameter 'cov' must be an nxn matrix, where n is equal to the number of free ",
"parameters in the model, or the total number of parameters (fixed and free) of ",
"the model.",
]
raise ValueError("".join(emsg))
self.model = model.copy()
# The free/fixed status of every parameter in the model
free = np.concatenate([m.free for m in self.model]).ravel()
# Create maps from model parts to index of corresponding covariance matrix row/column
n = 0
for i, m in enumerate(model):
self.mmap[i] = n + np.arange(m.npars(True))
for j, p in enumerate(m):
self.pmap[(i, j)] = n
self.ipmap[n] = (i, j)
n += 1
if n == tempcov.shape[0]:
# All free and fixed parameters already in passed covariance matrix
self.cov = tempcov
else:
# Create new covariance matrix, making sure to account for fixed pars
self.cov = np.matrix(np.zeros((n, n)))
i = 0
rawi = 0
for i in range(n):
j = 0
rawj = 0
if free[i]:
for j in range(n):
if free[j]:
self.cov[i, j] = cov[rawi, rawj]
rawj += 1
rawi += 1
def transform(self, in_format, out_format, **kwds):
"""Transform parameters and covariance matrix under specified change of variables.
By default this change applies to all parameters of the model. If the specified transformation
is invalid for a given ModelPart the original parameterization is maintained for that part.
This function assumes that the derivative of every variable under this change depends only on the
other parameters in its own part. Essentially, each model part has it own non-zero gradient matrix for
any change of variables, but the gradient matrix between different parts is 0.
Note that transformed parameters may mix previously fixed and free parameters, and consequently
the number of each kind is not necessarily preserved. The user is cautioned to interpret a transformed
covariance matrix carefully. For example, the apparent degrees of freedom in the transformed
covariance matrix may not coincide with the degrees of freedom during model fitting.
Parameters
----------
in_format - The current format of parameters
out_format - The new format for parameters
Keywords
--------
parts - Specify which model part, by index, to transform. Defaults to all parts. Alternately,
"peaks" to transform all but the last part, and "baseline" to convert only the last part.
"""
if self.cov is None:
emsg = "Cannot transform undefined covariance matrix."
raise SrMiseUndefinedCovarianceError(emsg)
if "parts" in kwds:
if kwds["parts"] == "peaks":
parts = range(len(self.model) - 1)
elif kwds["parts"] == "baseline":
parts = [-1]
else:
parts = kwds["parts"]
else:
parts = range(len(self.model))
# Calculate V_y = G Transpose(V_x) G
# where V_y is the covariance matrix in terms of the parameterization y,
# V_x is the current covariance matrix, and G is the gradient matrix of
# the variable transformation x->y. That is, G_ij = dy_i/dx_j.
#
# Since we assume that the parameterization of each ModelPart is independent
# of every other ModelPart, we create the full gradient matrix from the smaller
# gradient submatrices of each ModelPart.
g = np.identity(self.cov.shape[0])
for i in parts:
start = self.mmap[i][0]
stop = self.mmap[i][-1] + 1
p = self.model[i]
try:
subg = p.owner().transform_derivatives(p.pars, in_format, out_format)
except NotImplementedError:
logger.warning(
"Transformation gradient not implemented for part %i: %s. Ignoring transformation."
% (i, str(p))
)
subg = np.identity(p.npars(True))
except Exception as e:
logger.warning(
"Transformation gradient failed for part %i: %s. "
"Failed with message %s. Ignoring transformation." % (i, str(p), str(e))
)
subg = np.identity(p.npars(True))
# Now transform the parameters to match
try:
p.pars = p.owner().transform_parameters(p.pars, in_format, out_format)
except Exception as e:
logger.warning(
"Parameter transformation failed for part %i: %s. "
"Failed with message %s. Ignoring transformation." % (i, str(p), str(e))
)
subg = np.identity(p.npars(True))
# Update the global gradient matrix
g[start:stop, start:stop] = subg
g = np.matrix(g)
self.cov = np.array(g * np.matrix(self.cov).transpose() * g)
return
def getcorrelation(self, i, j):
"""Return the correlation between variables i and j, Corr_ij=Cov_ij/(sigma_i sigma_j)
The variables may be specified as integers, or as a two-component tuple of integers (l, m)
which indicate the mth parameter in peak l.
The standard deviation of fixed parameters is 0, in which case the correlation is
undefined, but return 0 for simplicity.
"""
if self.cov is None:
emsg = "Cannot get correlation on undefined covariance matrix."
raise SrMiseUndefinedCovarianceError(emsg)
# Map peak/parameter tuples to the proper index
i1 = self.pmap[i] if i in self.pmap else i
j1 = self.pmap[j] if j in self.pmap else j
if self.cov[i1, i1] == 0.0 or self.cov[j1, j1] == 0.0:
return 0.0 # Avoiding undefined quantities is sensible in this context.
else:
return self.cov[i1, j1] / (np.sqrt(self.cov[i1, i1]) * np.sqrt(self.cov[j1, j1]))
def getvalue(self, i):
"""Return value of parameter i.
The variable may be specified as an integer, or as a two-component tuple of integers (l, m)
which indicate the mth parameter of modelpart l.
"""
(l, m) = i if i in self.pmap else self.ipmap[i]
return self.model[l][m]
def getuncertainty(self, i):
"""Return uncertainty of parameter i.
The variable may be specified as an integer, or as a two-component tuple of integers (l, m)
which indicate the mth parameter of modelpart l.
"""
(l, m) = i if i in self.pmap else self.ipmap[i]
return np.sqrt(self.getcovariance(i, i))
def getcovariance(self, i, j):
"""Return the covariance between variables i and j.
The variables may be specified as integers, or as a two-component tuple of integers (l, m)
which indicate the mth parameter of modelpart l.
"""
if self.cov is None:
emsg = "Cannot get correlation on undefined covariance matrix."
raise SrMiseUndefinedCovarianceError(emsg)
# Map peak/parameter tuples to the proper index
i1 = self.pmap[i] if i in self.pmap else i
j1 = self.pmap[j] if j in self.pmap else j
return self.cov[i1, j1]
def get(self, i):
"""Return (value, uncertainty) tuple for parameter i.
The variable may be specified as an integer, or as a two-component tuple of integers (l, m)
which indicate the mth parameter of modelpart l.
"""
return (self.getvalue(i), self.getuncertainty(i))
def correlationwarning(self, threshold=0.8):
"""Report distinct variables with magnitude of correlation greater than threshold.
Returns a list of tuples (i, j, c), where i and j are tuples indicating
the modelpart and parameter indices of the correlated variables, and
c is their correlation.
Parameters
----------
threshold - A real number between 0 and 1.
"""
if self.cov is None:
emsg = "Cannot calculate correlation on undefined covariance matrix."
raise SrMiseUndefinedCovarianceError(emsg)
correlated = []
for i in range(self.cov.shape[0]):
for j in range(i + 1, self.cov.shape[0]):
c = self.getcorrelation(i, j)
if c and np.abs(c) > threshold: # filter out None values
correlated.append((self.ipmap[i], self.ipmap[j], c))
return correlated
def __str__(self):
"""Return string of value (uncertainty) pairs for all parameters."""
if self.model is None or self.cov is None:
return "Model and/or Covariance matrix undefined."
lines = []
for i, m in enumerate(self.model):
lines.append(" ".join([self.prettypar((i, j)) for j in range(len(m))]))
return "\n".join(lines)
def prettypar(self, i):
"""Return string 'value (uncertainty)' for parameter i.
The variable may be specified as an integer, or as a two-component tuple of integers (l, m)
which indicate the mth parameter of modelpart l.
"""
if self.model is None or self.cov is None:
return "Model and/or Covariance matrix undefined."
k = i if i in self.ipmap else self.pmap[i]
return "%.5e (%.5e)" % (self.getvalue(k), np.sqrt(self.getcovariance(k, k)))
# End of class ModelCovariance
class ModelCluster(object):
"""Associate a contiguous cluster of data with an appropriate model.
A ModelCluster instance is the basic unit of diffpy.srmise, combining data and
a model with the basic tools for controlling their interaction.
Methods
-------
addexternalpeaks: Add peaks to model, and their value to the data.
augment: Add peaks to model, only keeping those which improve model quality.
change_slice: Change the range of the data considered within cluster.
cleanfit: Remove extremely poor or non-contributing peaks from model.
contingent_fit: Fit model to data if size of cluster has significantly increased
since previous fit.
factory: Static method to recreate a ModelCluster from a string.
join_adjacent: Static method to combine two ModelClusters.
npars: Return total number of parameters in model.
replacepeaks: Add and/or delete peaks in model
deletepeak: Delete a single peak in model.
estimatepeak: Add single peak to model with no peaks.
fit: Fit the model to the data
plottable: Return list of arguments for convenient plotting with matplotlib
plottable_residual: Return list of argument for convenient plotting of residual
with matplotlib.
prune: Remove peaks from model which maximize quality.
reduce_to: If value(x)>y, change model to so that value(x)=y
quality: Return ModelEvaluator instance that calculates quality of model to data.
value: Return value of the model plus baseline
valuebl: Return value of the baseline
writestr: Return string representation of self.
"""
def __init__(self, model, *args, **kwds):
"""Intialize explicitly, or from existing ModelCluster.
Parameters [Explicit creation]
model - Peaks object, or None->empty model
baseline - Baseline object, or None->0
r_data - Numpy array of r coordinates
y_data - Numpy array of y values
y_error - Numpy array of uncertainties in y
cluster_slice - slice object defining the range of cluster. None->all data
error_method - an ErrorEvaluator subclass
peak_funcs - a sequence of PeakFunction instances
Parameters [Creation from existing ModelCluster]
model - ModelCluster instance, or sequence of ModelCluster instances
"""
self.last_fit_size = 0
self.slice = None
self.size = None
self.r_cluster = None
self.y_cluster = None
self.error_cluster = None
self.never_fit = None
if isinstance(model, ModelCluster):
orig = model
s = orig.slice
self.model = orig.model.copy()
if orig.baseline is None:
self.baseline = None
else:
self.baseline = orig.baseline.copy()
self.r_data = orig.r_data
self.y_data = orig.y_data
self.y_error = orig.y_error
self.change_slice(slice(s.start, s.stop, s.step))
self.error_method = orig.error_method
self.peak_funcs = list(orig.peak_funcs)
return
else: # Explicit creation
if model is None:
self.model = Peaks([])
else:
self.model = model
self.baseline = args[0]
self.r_data = args[1]
self.y_data = args[2]
self.y_error = args[3]
# Sets self.slice, self.size, self.r_cluster, self.y_cluster,
# and self.error_cluster.
if args[4] is None:
self.change_slice(slice(len(self.r_data)))
else:
self.change_slice(args[4])
self.error_method = args[5]
self.peak_funcs = args[6]
return
def copy(self):
"""Return copy of this ModelCluster.
Equivalent to ModelCluster(self)"""
return ModelCluster(self)
def addexternalpeaks(self, peaks):
"""Add peaks (and their value) to self.
Parameters
peaks - A Peaks object
"""
self.replacepeaks(peaks)
self.y_data += peaks.value(self.r_data)
self.y_cluster = self.y_data[self.slice]
def writestr(self, **kwds):
"""Return partial string representation.
Keywords
pfbaselist - List of peak function bases. Otherwise define list from self.
blfbaselist - List of baseline function bases. Otherwise define list from self.
"""
from diffpy.srmise.basefunction import BaseFunction
if "pfbaselist" in kwds:
pfbaselist = kwds["pfbaselist"]
writepf = False
else:
pfbaselist = [p.owner() for p in self.model]
pfbaselist.extend(self.peak_funcs)
pfbaselist = list(set(pfbaselist))
pfbaselist = BaseFunction.safefunctionlist(pfbaselist)
writepf = True
if "blfbaselist" in kwds:
blfbaselist = kwds["blfbaselist"]
writeblf = False
else:
blfbaselist = BaseFunction.safefunctionlist([self.baseline.owner()])
writeblf = True
lines = []
if self.peak_funcs is None:
lines.append("peak_funcs=None")
else:
lines.append("peak_funcs=%s" % repr([pfbaselist.index(p) for p in self.peak_funcs]))
if self.error_method is None:
lines.append("ModelEvaluator=None")
else:
lines.append("ModelEvaluator=%s" % self.error_method.__name__)
lines.append("slice=%s" % repr(self.slice))
# Indexed baseline functions (unless externally provided)
if writeblf:
lines.append("## BaselineFunctions")
for i, bf in enumerate(blfbaselist):
lines.append("# BaselineFunction %s" % i)
lines.append(bf.writestr(blfbaselist))
# Indexed peak functions (unless externally provided)
if writepf:
lines.append("## PeakFunctions")
for i, pf in enumerate(pfbaselist):
lines.append("# PeakFunction %s" % i)
lines.append(pf.writestr(pfbaselist))
lines.append("# BaselineObject")
if self.baseline is None:
lines.append("None")
else:
lines.append(self.baseline.writestr(blfbaselist))
lines.append("## ModelPeaks")
if self.model is None:
lines.append("None")
else:
for m in self.model:
lines.append("# ModelPeak")
lines.append(m.writestr(pfbaselist))
# Raw data in modelcluster.
lines.append("### start data")
lines.append("#L r y dy")
for i in range(len(self.r_data)):
lines.append("%g %g %g" % (self.r_data[i], self.y_data[i], self.y_error[i]))
datastring = "\n".join(lines) + "\n"
return datastring
@staticmethod
def factory(mcstr, **kwds):
"""Create ModelCluster from string.
Keywords
pfbaselist - List of peak function bases
blfbaselist - List of baseline function bases
"""
from diffpy.srmise.basefunction import BaseFunction
if "pfbaselist" in kwds:
readpf = False
pfbaselist = kwds["pfbaselist"]
else:
readpf = True
if "blfbaselist" in kwds:
readblf = False
blfbaselist = kwds["blfbaselist"]
else:
readblf = True
# The major components are:
# - Header
# - BaselineFunctions (optional)
# - Peakfunctions (optional)
# - BaselineObject
# - ModelPeaks
# - StartData
# find data section, and what information it contains
res = re.search(r"^#+ start data\s*(?:#.*\s+)*", mcstr, re.M)
if res:
start_data = mcstr[res.end() :].strip()
start_data_info = mcstr[res.start() : res.end()]
header = mcstr[: res.start()]
res = re.search(r"^(#+L.*)$", start_data_info, re.M)
if res:
start_data_info = start_data_info[res.start() : res.end()].strip()
hasr = False
hasy = False
hasdy = False
res = re.search(r"\br\b", start_data_info)
if res:
hasr = True
res = re.search(r"\by\b", start_data_info)
if res:
hasy = True
res = re.search(r"\bdy\b", start_data_info)
if res:
hasdy = True
# Model
res = re.search(r"^#+ ModelPeaks.*$", header, re.M)
if res:
model_peaks = header[res.end() :].strip()
header = header[: res.start()]
# Baseline Object
res = re.search(r"^#+ BaselineObject\s*(?:#.*\s+)*", header, re.M)
if res:
baselineobject = header[res.end() :].strip()
header = header[: res.start()]
# Peak functions
if readpf:
res = re.search(r"^#+ PeakFunctions.*$", header, re.M)
if res:
peakfunctions = header[res.end() :].strip()
header = header[: res.start()]
# Baseline functions
if readblf:
res = re.search(r"^#+ BaselineFunctions.*$", header, re.M)
if res:
baselinefunctions = header[res.end() :].strip()
header = header[: res.start()]
# Instantiating baseline functions
if readblf:
blfbaselist = []
res = re.split(r"(?m)^#+ BaselineFunction \d+\s*(?:#.*\s+)*", baselinefunctions)
for s in res[1:]:
blfbaselist.append(BaseFunction.factory(s, blfbaselist))
# Instantiating peak functions
if readpf:
pfbaselist = []
res = re.split(r"(?m)^#+ PeakFunction \d+\s*(?:#.*\s+)*", peakfunctions)
for s in res[1:]:
pfbaselist.append(BaseFunction.factory(s, pfbaselist))
# Instantiating header data
# peak_funcs
res = re.search(r"^peak_funcs=(.*)$", header, re.M)
peak_funcs = eval(res.groups()[0].strip())
if peak_funcs is not None:
peak_funcs = [pfbaselist[i] for i in peak_funcs]
# error_method
res = re.search(r"^ModelEvaluator=(.*)$", header, re.M)
__import__("diffpy.srmise.modelevaluators")
module = sys.modules["diffpy.srmise.modelevaluators"]
error_method = getattr(module, res.groups()[0].strip())
# slice
res = re.search(r"^slice=(.*)$", header, re.M)
cluster_slice = eval(res.groups()[0].strip())
# Instantiating BaselineObject
if re.match(r"^None$", baselineobject):
baseline = None
else:
baseline = Baseline.factory(baselineobject, blfbaselist)
# Instantiating model
model = Peaks()
res = re.split(r"(?m)^#+ ModelPeak\s*(?:#.*\s+)*", model_peaks)
for s in res[1:]:
model.append(Peak.factory(s, pfbaselist))
# Instantiating start data
# read actual data - r, y, dy
arrays = []
if hasr:
r_data = []
arrays.append(r_data)
else:
r_data = None
if hasy:
y_data = []
arrays.append(y_data)
else:
y_data = None
if hasdy:
y_error = []
arrays.append(y_error)
else:
y_error = None
# raise SrMiseDataFormatError if something goes wrong
try:
for line in start_data.split("\n"):
lines = line.split()
if len(arrays) != len(lines):
emsg = "Number of value fields does not match that given by '%s'" % start_data_info
raise IndexError(emsg)
for a, v in zip(arrays, line.split()):
a.append(float(v))
except (ValueError, IndexError) as err:
raise SrMiseDataFormatError(err)
if hasr:
r_data = np.array(r_data)
if hasy:
y_data = np.array(y_data)
if hasdy:
y_error = np.array(y_error)
return ModelCluster(
model,
baseline,
r_data,
y_data,
y_error,
cluster_slice,
error_method,
peak_funcs,
)
@staticmethod
def join_adjacent(m1, m2):
"""Create new ModelCluster from two adjacent ones.
Suspected duplicate peaks are removed, and peaks may be adjusted if
their sum where the clusters meet exceeds the data. m1 and m2 are
unchanged.
Parameters
m1 - A ModelCluster
m2 - A ModelCluster
"""
# Check for members that must be shared.
if not (m1.r_data is m2.r_data):
emsg = "Cannot join ModelClusters that do not share r_data."
raise ValueError(emsg)
if not (m1.y_data is m2.y_data):
emsg = "Cannot join ModelClusters that do not share y_data."
raise ValueError(emsg)
if not (m1.y_error is m2.y_error):
emsg = "Cannot join ModelClusters that do not share y_error."
raise ValueError(emsg)
if not (m1.error_method is m2.error_method):
emsg = "Cannot join ModelClusters that do not share error_method."
raise ValueError(emsg)
if not (m1.baseline == m2.baseline):
emsg = "Cannot join ModelClusters that do not have equivalent baselines."
raise ValueError(emsg)
m1_ids = m1.slice.indices(len(m1.r_data))
m2_ids = m2.slice.indices(len(m1.r_data))
if m1_ids[0] < m2_ids[0]:
left = m1
right = m2
left_ids = m1_ids
right_ids = m2_ids
else:
left = m2
right = m1
left_ids = m2_ids
right_ids = m1_ids
if not right_ids[0] == left_ids[1]:
raise ValueError("Given ModelClusters are not adjacent.")
new_slice = slice(left_ids[0], right_ids[1], 1)
# Approximately where the clusters meet.
border_x = 0.5 * (left.r_data[left_ids[1] - 1] + right.r_data[right_ids[0]])
border_y = 0.5 * (left.y_data[left_ids[1] - 1] + right.y_data[right_ids[0]])
if len(m1.model) > 0 and len(m2.model) > 0:
new_model = left.model.copy()
new_model.extend(right.model.copy())
new_ids = new_model.argsort(key="position")
new_model = Peaks([new_model[i] for i in new_ids])
# Compare raw order with sorted order. Peaks which are *both* out
# of the expected order AND located on the "wrong" side of
# border_x are removed. The highly unlikely case of two peaks
# exactly at the border is also handled.
for i in reversed(range(len(new_model))):
if new_model[i]["position"] == border_x and i > 0 and new_model[i - 1]["position"] == border_x:
del new_model[i]
elif new_ids[i] != i:
if (new_model[i]["position"] > border_x and new_ids[i] < len(left.model)) and (
new_model[i]["position"] < border_x and new_ids[i] >= len(left.model)
):
del new_model[i]
# Likely to improve any future fitting
new_model.match_at(border_x, border_y)
elif len(m1.model) > 0:
new_model = m1.model.copy()
else: # Only m2 has entries, or both are empty
new_model = m2.model.copy()
peak_funcs = list(set(m1.peak_funcs) | set(m2.peak_funcs)) # "Union"
return ModelCluster(
new_model,
m1.baseline,
m1.r_data,
m1.y_data,
m1.y_error,
new_slice,
m1.error_method,
peak_funcs,
)
def change_slice(self, new_slice):
"""Change the slice which represents the extent of a cluster."""
old_slice = self.slice
self.slice = new_slice
self.r_cluster = self.r_data[new_slice]
self.y_cluster = self.y_data[new_slice]
self.error_cluster = self.y_error[new_slice]
self.size = len(self.r_cluster)
# Determine if any data in the cluster is above the error threshold.
# If not, then this cluster is never fit. This is updated as the
# cluster expands. This is not necessarily a strict measure because
# data removed from a cluster are not considered when updating, but
# this does not occur in the normal operation of peak extraction.
# Therefore never_fit will only be incorrect if the removed data
# includes the only parts rising above the error threshold, so a
# cluster is never wrongly skipped, but it might be fit when it isn't
# necessary.
y_data_nobl = self.y_data - self.valuebl(self.r_data)
y_cluster_nobl = y_data_nobl[new_slice]
if old_slice is None:
self.never_fit = max(y_cluster_nobl - self.error_cluster) < 0
else:
# check if slice has expanded on the left
if self.never_fit and self.slice.start < old_slice.start:
left_slice = slice(self.slice.start, old_slice.start)
self.never_fit = max(y_data_nobl[left_slice] - self.y_error[left_slice]) < 0
# check if slice has expanded on the right
if self.never_fit and self.slice.stop > old_slice.stop:
right_slice = slice(old_slice.stop, self.slice.stop)
self.never_fit = max(y_data_nobl[right_slice] - self.y_error[right_slice]) < 0
return
def npars(self, count_baseline=True, count_fixed=True):
"""Return number of parameters in model and baseline.
Parameters
count_baseline - [True] Boolean determines whether or not to count
parameters from baseline.
count_fixed - [True] Boolean determines whether or not to include
non-free parameters.
"""
n = self.model.npars(count_fixed=count_fixed)
if count_baseline and self.baseline is not None:
n += self.baseline.npars(count_fixed=count_fixed)
return n
def replacepeaks(self, newpeaks, delslice=slice(0, 0)):
"""Replace peaks given by delslice by those in newpeaks.
Parameters
newpeaks - Add each Peak in this Peaks to cluster.
delslice - Existing peaks given by slice object are deleted.
"""
for p in self.model[delslice]:
if not p.removable:
raise ValueError("delslice specified non-removable peaks.")
self.model[delslice] = newpeaks
self.model.sort(key="position")
return
def deletepeak(self, idx):
"""Delete the peak at the given index."""
self.replacepeaks([], slice(idx, idx + 1))
def estimatepeak(self):
"""Attempt to add single peak to empty cluster. Return True if successful."""
# STUB!!! ###
# Currently only a single peak function is supported. Dynamic
# selection from multiple types may require additional support
# within peak functions themselves. The simplest method would
# be estimating and fitting each possible peak type to the data
# and seeing which works best, but for small clusters evaluating
# model quality is generally unreliable, and most peak shapes will
# be approxiately equally good anyway.
if len(self.model) > 0:
# throw some exception
pass
selected = self.peak_funcs[0]
estimate = selected.estimate_parameters(self.r_cluster, self.y_cluster - self.valuebl())
if estimate is not None:
newpeak = selected.actualize(estimate, "internal")
logger.info("Estimate: %s" % newpeak)
self.replacepeaks(Peaks([newpeak]))
return True
else:
return False
def fit(
self,
justify=False,
ntrials=0,
fitbaseline=False,
estimate=True,
cov=None,
cov_format="default_output",
):
"""Perform a chi-square fit of the model to data in cluster.
Parameters
justify - Revert to initial model (if one exists) if new model
has only a single peak and the quality of the fit suggests
additional peaks are present.
ntrials - The maximum number of function evaluations.
'0' indicates the fitting algorithm's default.
fitbaseline - Whether to fit baseline along with peaks
estimate - Estimate a single peak from data if model is empty.
cov - Optional ModelCovariance object preserves covariance information.
cov_format - Parameterization to use in cov.
If fitting changes a model, return ModelEvaluator instance. Otherwise
return None.
"""
if self.never_fit:
return None
if len(self.model) == 0:
# Attempt to add a first peak to the cluster
if estimate:
try:
self.estimatepeak()
except SrMiseEstimationError:
logger.info("Fit: No model to fit, estimation not possible.")
return
else:
logger.info("Fit: No model to fit.")
return
orig_qual = self.quality()
orig_model = self.model.copy()
if self.baseline is None:
orig_baseline = None
else:
orig_baseline = self.baseline.copy()
self.last_fit_size = self.size
if fitbaseline and self.baseline is not None and self.baseline.npars(count_fixed=False) > 0:
y_datafit = self.y_data
fmodel = ModelParts(self.model)
fmodel.append(self.baseline)
else:
y_datafit = self.y_data - self.valuebl(self.r_data)
fmodel = self.model
try:
fmodel.fit(
self.r_data,
y_datafit,
self.y_error,
self.slice,
ntrials,
cov,
cov_format,
)
except SrMiseFitError as e:
logger.debug("Error while fitting cluster: %s\nReverting to original model.", e)
self.model = orig_model
self.baseline = orig_baseline
return None
if fitbaseline and self.baseline is not None and self.baseline.npars(count_fixed=False) > 0:
self.model = Peaks(fmodel[:-1])
self.baseline = fmodel[-1]
else:
self.model = fmodel
self.model.sort()
self.cleanfit()
new_qual = self.quality()
# Test for fit improvement
if new_qual < orig_qual:
# either fit blew up (and leastsq didn't notice) or the fit had already converged.
msg = [
"ModelCluster.fit() warning: fit seems not to have improved.",
"Reverting to original model.",
"----------",
"New Quality: %s",
"Original Quality: %s" "%s",
"----------",
]
logger.debug("\n".join(msg), new_qual.stat, orig_qual.stat, self.model)
self.model = orig_model
self.baseline = orig_baseline
return None
# Short version: When justify=True a single peak is no longer fit
# after a second peak could potentially explain its residual.
#
# This is a tricky point. It is often the case while fitting that an
# intially good peak becomes less accurate due to greater overlap at
# the edges of the cluster, even as its (calculated) quality improves.
# This may make combining clusters later more difficult, and so test
# if the degree by which the new fit is off could perhaps be adequately
# explained by adding a second peak instead. If so, reverting to the
# original fit is less likely to obscure any hidden peaks.
if justify and len(self.model) == 1 and len(orig_model) > 0:
min_npars = min([p.npars for p in self.peak_funcs])
if new_qual.growth_justified(self, min_npars):
msg = [
"ModelCluster.fit(): Fit over current cluster better explained by additional peaks.",
"Reverting to original model.",
]
logger.debug("\n".join(msg))
self.model = orig_model
self.baseline = orig_baseline
return None
return new_qual
def contingent_fit(self, minpoints, growth_threshold):
"""Fit cluster if it has grown sufficiently large since its last fit.
Parameters
minpoints - The minimum number of points an empty cluster requires to fit.
growth_threshold - Fit non-empty model if (currentsize/oldsize) >= this value.
Return ModelEvaluator instance if fit changed, otherwise None.
"""