22
22
23
23
logger = logging .getLogger ("diffpy.srmise" )
24
24
25
+
25
26
class PeakFunction (BaseFunction ):
26
27
"""Base class for functions which represent peaks.
27
28
@@ -60,7 +61,15 @@ class PeakFunction(BaseFunction):
60
61
transform_parameters()
61
62
"""
62
63
63
- def __init__ (self , parameterdict , parformats , default_formats , metadict , base = None , Cache = None ):
64
+ def __init__ (
65
+ self ,
66
+ parameterdict ,
67
+ parformats ,
68
+ default_formats ,
69
+ metadict ,
70
+ base = None ,
71
+ Cache = None ,
72
+ ):
64
73
"""Set parameterdict defined by subclass
65
74
66
75
parameterdict: A dictionary mapping string keys to their index in a
@@ -82,24 +91,31 @@ def __init__(self, parameterdict, parformats, default_formats, metadict, base=No
82
91
raise ValueError (emsg )
83
92
BaseFunction .__init__ (self , parameterdict , parformats , default_formats , metadict , base , Cache )
84
93
85
-
86
94
#### "Virtual" class methods ####
87
95
88
96
def scale_at (self , peak , x , scale ):
89
97
emsg = "scale_at must be implemented in a PeakFunction subclass."
90
98
raise NotImplementedError (emsg )
91
99
92
-
93
100
#### Methods required by BaseFunction ####
94
101
95
- def actualize (self , pars , in_format = "default_input" , free = None , removable = True , static_owner = False ):
102
+ def actualize (
103
+ self ,
104
+ pars ,
105
+ in_format = "default_input" ,
106
+ free = None ,
107
+ removable = True ,
108
+ static_owner = False ,
109
+ ):
96
110
converted = self .transform_parameters (pars , in_format , out_format = "internal" )
97
111
return Peak (self , converted , free , removable , static_owner )
98
112
99
113
def getmodule (self ):
100
114
return __name__
101
115
102
- #end of class PeakFunction
116
+
117
+ # end of class PeakFunction
118
+
103
119
104
120
class Peaks (ModelParts ):
105
121
"""A collection for Peak objects."""
@@ -110,12 +126,12 @@ def __init__(self, *args, **kwds):
110
126
111
127
def argsort (self , key = "position" ):
112
128
"""Return sequence of indices which sort peaks in order specified by key."""
113
- keypars = np .array ([p [key ] for p in self ])
129
+ keypars = np .array ([p [key ] for p in self ])
114
130
# In normal use the peaks will already be sorted, so check for it.
115
- sorted = True
116
- for i in range (len (keypars )- 1 ):
117
- if keypars [i ] > keypars [i + 1 ]:
118
- sorted = False
131
+ sorted = True
132
+ for i in range (len (keypars ) - 1 ):
133
+ if keypars [i ] > keypars [i + 1 ]:
134
+ sorted = False
119
135
break
120
136
if not sorted :
121
137
return keypars .argsort ().tolist ()
@@ -142,14 +158,14 @@ def match_at(self, x, y):
142
158
orig = self .copy ()
143
159
144
160
try :
145
- scale = y / height
161
+ scale = y / height
146
162
147
163
# First attempt at scaling peaks. Record which peaks, if any,
148
164
# were not scaled in case a second attempt is required.
149
165
scaled = []
150
166
all_scaled = True
151
167
any_scaled = False
152
- fixed_height = 0.
168
+ fixed_height = 0.0
153
169
for peak in self :
154
170
scaled .append (peak .scale_at (x , scale ))
155
171
all_scaled = all_scaled and scaled [- 1 ]
@@ -161,27 +177,29 @@ def match_at(self, x, y):
161
177
if not all_scaled and fixed_height < y and fixed_height < height :
162
178
self [:] = orig [:]
163
179
any_scaled = False
164
- scale = (y - fixed_height )/ (height - fixed_height )
180
+ scale = (y - fixed_height ) / (height - fixed_height )
165
181
for peak , s in (self , scaled ):
166
182
if s :
167
183
# "or" is short-circuited, so scale_at() must be first
168
184
# to guarantee it is called.
169
185
any_scaled = peak .scale_at (x , scale ) or any_scaled
170
- except Exception , e :
186
+ except Exception as e :
171
187
logger .debug ("An exception prevented matching -- %s" , e )
172
188
self [:] = orig [:]
173
189
return False
174
190
return any_scaled
175
191
176
192
def sort (self , key = "position" ):
177
193
"""Sort peaks in order specified by key."""
178
- keypars = np .array ([p [key ] for p in self ])
194
+ keypars = np .array ([p [key ] for p in self ])
179
195
order = keypars .argsort ()
180
196
self [:] = [self [idx ] for idx in order ]
181
197
return
182
198
199
+
183
200
# End of class Peaks
184
201
202
+
185
203
class Peak (ModelPart ):
186
204
"""Represents a single peak associated with a PeakFunction subclass."""
187
205
@@ -225,7 +243,7 @@ def scale_at(self, x, scale):
225
243
226
244
try :
227
245
adj_pars = self ._owner .scale_at (self .pars , x , scale )
228
- except SrMiseScalingError , err :
246
+ except SrMiseScalingError as err :
229
247
logger .debug ("Cannot scale peak:" , err )
230
248
return False
231
249
@@ -256,10 +274,10 @@ def factory(peakstr, ownerlist):
256
274
try :
257
275
pdict [l [0 ]] = eval (l [1 ])
258
276
except Exception :
259
- emsg = ( "Invalid parameter: %s" % d )
277
+ emsg = "Invalid parameter: %s" % d
260
278
raise SrMiseDataFormatError (emsg )
261
279
else :
262
- emsg = ( "Invalid parameter: %s" % d )
280
+ emsg = "Invalid parameter: %s" % d
263
281
raise SrMiseDataFormatError (emsg )
264
282
265
283
# Correctly initialize the base function, if one exists.
@@ -271,10 +289,11 @@ def factory(peakstr, ownerlist):
271
289
272
290
return Peak (** pdict )
273
291
292
+
274
293
# End of class Peak
275
294
276
295
# simple test code
277
- if __name__ == ' __main__' :
296
+ if __name__ == " __main__" :
278
297
279
298
import matplotlib .pyplot as plt
280
299
from numpy .random import randn
@@ -283,26 +302,26 @@ def factory(peakstr, ownerlist):
283
302
from diffpy .srmise .modelevaluators import AICc
284
303
from diffpy .srmise .peaks import GaussianOverR
285
304
286
- res = .01
287
- r = np .arange (2 ,4 , res )
288
- err = np .ones (len (r )) # default unknown errors
289
- pf = GaussianOverR (.7 )
305
+ res = 0 .01
306
+ r = np .arange (2 , 4 , res )
307
+ err = np .ones (len (r )) # default unknown errors
308
+ pf = GaussianOverR (0 .7 )
290
309
evaluator = AICc ()
291
310
292
- pars = [[3 , .2 , 10 ], [3.5 , .2 , 10 ]]
311
+ pars = [[3 , 0 .2 , 10 ], [3.5 , 0 .2 , 10 ]]
293
312
ideal_peaks = Peaks ([pf .actualize (p , "pwa" ) for p in pars ])
294
- y = ideal_peaks .value (r ) + .1 * randn (len (r ))
313
+ y = ideal_peaks .value (r ) + 0.1 * randn (len (r ))
295
314
296
- guesspars = [[2.7 , .15 , 5 ], [3.7 , .3 , 5 ]]
315
+ guesspars = [[2.7 , 0 .15 , 5 ], [3.7 , 0 .3 , 5 ]]
297
316
guess_peaks = Peaks ([pf .actualize (p , "pwa" ) for p in guesspars ])
298
317
cluster = ModelCluster (guess_peaks , r , y , err , None , AICc , [pf ])
299
318
300
319
qual1 = cluster .quality ()
301
- print qual1 .stat
320
+ print ( qual1 .stat )
302
321
cluster .fit ()
303
322
yfit = cluster .calc ()
304
323
qual2 = cluster .quality ()
305
- print qual2 .stat
324
+ print ( qual2 .stat )
306
325
307
326
plt .figure (1 )
308
327
plt .plot (r , y , r , yfit )
0 commit comments