-
Notifications
You must be signed in to change notification settings - Fork 63
/
feffit_panel.py
2367 lines (1960 loc) · 90.9 KB
/
feffit_panel.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
import time
import os
import sys
import ast
import shutil
import string
import json
import math
from copy import deepcopy
from sys import exc_info
from string import printable
from functools import partial
import numpy as np
np.seterr(all='ignore')
import wx
import wx.lib.scrolledpanel as scrolled
import wx.dataview as dv
from lmfit import Parameter
from lmfit.model import (save_modelresult, load_modelresult,
save_model, load_model)
import lmfit.models as lm_models
from larch import Group, site_config
from larch.math import index_of
from larch.fitting import group2params, param
from larch.utils.jsonutils import encode4js, decode4js
from larch.inputText import is_complete
from larch.utils import fix_varname, fix_filename, gformat, mkdir, isValidName
from larch.io.export_modelresult import export_modelresult
from larch.xafs import feffit_report, feffpath
from larch.xafs.feffdat import FEFFDAT_VALUES
from larch.xafs.xafsutils import FT_WINDOWS
from larch.wxlib import (ReportFrame, BitmapButton, FloatCtrl, FloatSpin,
SetTip, GridPanel, get_icon, SimpleText, pack,
Button, HLine, Choice, Check, MenuItem, GUIColors,
CEN, RIGHT, LEFT, FRAMESTYLE, Font, FONTSIZE,
COLORS, set_color, FONTSIZE_FW, FileSave,
FileOpen, flatnotebook, EditableListBox, Popup,
ExceptionPopup)
from larch.wxlib.parameter import ParameterWidgets
from larch.wxlib.plotter import last_cursor_pos
from .taskpanel import TaskPanel
from .config import (Feffit_KWChoices, Feffit_SpaceChoices,
Feffit_PlotChoices, make_array_choice,
PlotWindowChoices)
DVSTYLE = dv.DV_SINGLE|dv.DV_VERT_RULES|dv.DV_ROW_LINES
# PlotOne_Choices = [chik, chirmag, chirre, chirmr]
Plot1_Choices = make_array_choice(['chi','chir_mag', 'chir_re', 'chir_mag+chir_re', 'chiq'])
Plot2_Choices = make_array_choice(['noplot', 'chi','chir_mag', 'chir_re', 'chir_mag+chir_re', 'chiq'])
# Plot2_Choices = [noplot] + Plot1_Choices
ScriptWcards = "Fit Models(*.lar)|*.lar|All files (*.*)|*.*"
MIN_CORREL = 0.10
COMMANDS = {}
COMMANDS['feffit_top'] = """##### FEFFIT Commands
##
## saved {ctime}
## to use from python, uncomment these import lines:
##
#from larch.xafs import feffit, feffit_dataset, feffit_transform, feffit_report
#from larch.xafs import pre_edge, autobk, xftf, xftr, ff2chi, feffpath
#from larch.fitting import param_group, param
#from larch.io import read_ascii, read_athena, read_xdi, read_specfile
#
#### for interactive plotting from python (but not the Larch shell!) use:
#from larch.wxlib.xafsplots import plot_chik, plot_chir
#from wxmplot.interactive import get_wxapp
#wxapp = get_wxapp() # <- needed for plotting to work from python command-line
####
####
"""
COMMANDS['data_source'] = """### you will need to add how the data chi(k) gets built:
###
## data group = {groupname}
## from source = {filename}
## some processing steps for this group (comment out as needed):
"""
COMMANDS['xft'] = """# ffts on group {groupname:s}
xftf({groupname:s}, kmin={kmin:.3f}, kmax={kmax:.3f}, dk={dk:.3f}, window='{kwindow:s}', kweight={kweight:.3f})
xftr({groupname:s}, rmin={rmin:.3f}, rmax={rmax:.3f}, dr={dr:.3f}, window='{rwindow:s}')
"""
COMMANDS['feffit_params_init'] = """# create feffit Parameter Group to hold fit parameters
_feffit_params = param_group(reff=-1.0)
"""
COMMANDS['feffit_trans'] = """# define Fourier transform and fitting space
_feffit_trans = feffit_transform(kmin={fit_kmin:.3f}, kmax={fit_kmax:.3f}, dk={fit_dk:.4f}, kw={fit_kwstring:s},
window='{fit_kwindow:s}', fitspace='{fit_space:s}', rmin={fit_rmin:.3f}, rmax={fit_rmax:.3f})
"""
COMMANDS['feffit_dataset_init'] = """# create empty dataset
_feffit_dataset = feffit_dataset(transform=_feffit_trans)
"""
COMMANDS['paths_init'] = """# make sure dictionary for Feff Paths exists
try:
npaths = len(_feffpaths.keys())
except:
_feffcache = {'paths':{}, 'runs':{}} # group of all paths, info about Feff runs
_feffpaths = {} # dict of paths currently in use, copied from _feffcache.paths
#endtry
"""
COMMANDS['paths_reset'] = """# clear existing paths
npaths = 0
_feffpaths = {}
#endtry
"""
COMMANDS['cache_path'] = """
_feffcache['paths']['{title:s}'] = feffpath('{fullpath:s}',
label='{title:s}',feffrun='{feffrun:s}', degen=1)
"""
COMMANDS['use_path'] = """
_feffpaths['{title:s}'] = use_feffpath(_feffcache['paths'], '{title:s}',
s02='{amp:s}', e0='{e0:s}',
deltar='{delr:s}', sigma2='{sigma2:s}',
third='{third:s}', ei='{ei:s}', use={use})
"""
COMMANDS['ff2chi'] = """# sum paths using a list of paths and a group of parameters
_feffit_dataset = feffit_dataset(data={groupname:s}, transform={trans:s},
refine_bkg={refine_bkg},
paths={paths:s})
_feffit_dataset.model = ff2chi({paths:s}, paramgroup=_feffit_params)
"""
COMMANDS['ff2chi_nodata'] = """# sum paths using a list of paths and a group of parameters
_feffit_dataset = feffit_dataset(transform={trans:s}, paths={paths:s})
_feffit_dataset.model = ff2chi({paths:s}, paramgroup=_feffit_params)
"""
COMMANDS['do_feffit'] = """# build feffit dataset, run feffit
_feffit_dataset = feffit_dataset(data={groupname:s}, transform={trans:s},
refine_bkg={refine_bkg},
paths={paths:s})
_feffit_result = feffit({params}, _feffit_dataset)
if not hasattr({groupname:s}, 'feffit_history'): {groupname}.feffit_history = []
{groupname:s}.feffit_history.insert(0, _feffit_result)
"""
COMMANDS['path2chi'] = """# generate chi(k) and chi(R) for each path
for label, path in {paths_name:s}.items():
path.calc_chi_from_params({pargroup_name:s})
xftf(path, kmin={kmin:.3f}, kmax={kmax:.3f}, dk={dk:.3f},
window='{kwindow:s}', kweight={kweight:.3f})
#endfor
"""
def get_commands(textlines):
"""return list of complete larch command / python function calls
from a list of text lines such as 'command history'
"""
out = []
work_lines = []
for line in textlines:
work_lines.append(line)
work = ' '.join(work_lines)
if is_complete(work):
out.append(work)
work_lines.clear()
out.extend(work_lines) # add any dangling text
return out
class ParametersModel(dv.DataViewIndexListModel):
def __init__(self, paramgroup, selected=None, pathkeys=None):
dv.DataViewIndexListModel.__init__(self, 0)
self.data = []
if selected is None:
selected = []
self.selected = selected
if pathkeys is None:
pathkeys = []
self.pathkeys = pathkeys
self.paramgroup = paramgroup
self.read_data()
def set_data(self, paramgroup, selected=None, pathkeys=None):
self.paramgroup = paramgroup
if selected is not None:
self.selected = selected
if pathkeys is not None:
self.pathkeys = pathkeys
self.read_data()
def read_data(self):
self.data = []
if self.paramgroup is None:
self.data.append(['param name', False, 'vary', '0.0'])
else:
for pname, par in group2params(self.paramgroup).items():
if any([pname.endswith('_%s' % phash) for phash in self.pathkeys]):
continue
ptype = 'vary'
if not par.vary:
pytype = 'fixed'
if getattr(par, 'skip', None) not in (False, None):
ptype = 'skip'
par.skip = ptype == 'skip'
try:
value = str(par.value)
except:
value = 'INVALID '
if par.expr is not None:
ptype = 'constraint'
value = "%s := %s" % (value, par.expr)
sel = pname in self.selected
self.data.append([pname, sel, ptype, value])
self.Reset(len(self.data))
def select_all(self, value=True):
self.selected = []
for irow, row in enumerate(self.data):
self.SetValueByRow(value, irow, 1)
if value:
self.selected.append(row[0])
def select_none(self):
self.select_all(value=False)
def GetColumnType(self, col):
return "bool" if col == 2 else "string"
def GetValueByRow(self, row, col):
return self.data[row][col]
def SetValueByRow(self, value, row, col):
self.data[row][col] = value
return True
def GetColumnCount(self):
return len(self.data[0])
def GetCount(self):
return len(self.data)
def GetAttrByRow(self, row, col, attr):
"""set row/col attributes (color, etc)"""
ptype = self.data[row][2]
if ptype == 'vary':
attr.SetColour('#000000')
elif ptype == 'fixed':
attr.SetColour('#AA2020')
elif ptype == 'skip':
attr.SetColour('#50AA50')
else:
attr.SetColour('#2010BB')
return True
class EditParamsFrame(wx.Frame):
""" edit parameters"""
def __init__(self, parent=None, feffit_panel=None,
paramgroup=None, selected=None):
wx.Frame.__init__(self, None, -1,
'Edit Feffit Parameters',
style=FRAMESTYLE, size=(550, 325))
self.parent = parent
self.feffit_panel = feffit_panel
self.paramgroup = paramgroup
spanel = scrolled.ScrolledPanel(self, size=(500, 275))
spanel.SetBackgroundColour('#EEEEEE')
self.font_fixedwidth = wx.Font(FONTSIZE_FW, wx.MODERN, wx.NORMAL, wx.BOLD)
self.dvc = dv.DataViewCtrl(spanel, style=DVSTYLE)
self.dvc.SetFont(self.font_fixedwidth)
self.SetMinSize((500, 250))
self.model = ParametersModel(paramgroup, selected)
self.dvc.AssociateModel(self.model)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.dvc, 1, LEFT|wx.ALL|wx.GROW)
pack(spanel, sizer)
spanel.SetupScrolling()
toppan = GridPanel(self, ncols=4, pad=1, itemstyle=LEFT)
bkws = dict(size=(200, -1))
toppan.Add(Button(toppan, "Select All", action=self.onSelAll, size=(175, -1)))
toppan.Add(Button(toppan, "Select None", action=self.onSelNone, size=(175, -1)))
toppan.Add(Button(toppan, "Select Unused Variables", action=self.onSelUnused, size=(200, -1)))
toppan.Add(Button(toppan, "Remove Selected", action=self.onRemove, size=(175,-1)), newrow=True)
toppan.Add(Button(toppan, "'Skip' Selected", action=self.onSkip, size=(175, -1)))
toppan.Add(Button(toppan, "Force Refresh", action=self.onRefresh, size=(200, -1)))
npan = wx.Panel(toppan)
nsiz = wx.BoxSizer(wx.HORIZONTAL)
self.par_name = wx.TextCtrl(npan, -1, value='par_name', size=(125, -1),
style=wx.TE_PROCESS_ENTER)
self.par_expr = wx.TextCtrl(npan, -1, value='<expression or value>', size=(250, -1),
style=wx.TE_PROCESS_ENTER)
nsiz.Add(SimpleText(npan, "Add Parameter:"), 0)
nsiz.Add(self.par_name, 0)
nsiz.Add(self.par_expr, 1, wx.GROW|wx.ALL)
nsiz.Add(Button(npan, label='Add', action=self.onAddParam), 0)
pack(npan, nsiz)
toppan.Add(npan, dcol=4, newrow=True)
toppan.Add(HLine(toppan, size=(500, 2)), dcol=5, newrow=True)
toppan.pack()
mainsizer = wx.BoxSizer(wx.VERTICAL)
mainsizer.Add(toppan, 0, wx.GROW|wx.ALL, 1)
mainsizer.Add(spanel, 1, wx.GROW|wx.ALL, 1)
pack(self, mainsizer)
columns = [('Parameter', 150, 'text'),
('Select', 75, 'bool'),
('Type', 75, 'text'),
('Value', 200, 'text')]
for icol, dat in enumerate(columns):
label, width, dtype = dat
method = self.dvc.AppendTextColumn
mode = dv.DATAVIEW_CELL_EDITABLE
if dtype == 'bool':
method = self.dvc.AppendToggleColumn
mode = dv.DATAVIEW_CELL_ACTIVATABLE
method(label, icol, width=width, mode=mode)
c = self.dvc.Columns[icol]
c.Alignment = c.Renderer.Alignment = wx.ALIGN_LEFT
c.SetSortable(False)
self.dvc.EnsureVisible(self.model.GetItem(0))
self.Bind(wx.EVT_CLOSE, self.onClose)
self.Show()
self.Raise()
wx.CallAfter(self.onSelUnused)
def onSelAll(self, event=None):
self.model.select_all()
self.model.read_data()
def onSelNone(self, event=None):
self.model.select_none()
self.model.read_data()
def onSelUnused(self, event=None):
curr_syms = self.feffit_panel.get_used_params()
unused = []
for pname, par in group2params(self.paramgroup).items():
if pname not in curr_syms: # and par.vary:
unused.append(pname)
self.model.set_data(self.paramgroup, selected=unused,
pathkeys=self.feffit_panel.get_pathkeys())
def onRemove(self, event=None):
out = []
for pname, sel, ptype, val in self.model.data:
if sel:
out.append(pname)
nout = len(out)
msg = f"Remove {nout:d} Parameters? \n This is not easy to undo!"
dlg = wx.MessageDialog(self, msg, 'Warning', wx.YES | wx.NO )
if (wx.ID_YES == dlg.ShowModal()):
for pname, sel, ptype, val in self.model.data:
if sel:
out.append(pname)
if hasattr(self.paramgroup, pname):
delattr(self.paramgroup, pname)
self.model.set_data(self.paramgroup, selected=None,
pathkeys=self.feffit_panel.get_pathkeys())
self.model.read_data()
self.feffit_panel.get_pathpage('parameters').Rebuild()
dlg.Destroy()
def onSkip(self, event=None):
for pname, sel, ptype, val in self.model.data:
if sel:
par = getattr(self.paramgroup, pname, None)
if par is not None:
par.skip = True
self.model.read_data()
self.feffit_panel.get_pathpage('parameters').Rebuild()
def onAddParam(self, event=None):
par_name = self.par_name.GetValue()
par_expr = self.par_expr.GetValue()
try:
val = float(par_expr)
ptype = 'vary'
except:
val = par_expr
ptype = 'expr'
if ptype == 'vary':
cmd = f"_feffit_params.{par_name} = param({val}, vary=True)"
else:
cmd = f"_feffit_params.{par_name} = param(expr='{val}')"
self.feffit_panel.larch_eval(cmd)
self.onRefresh()
def onRefresh(self, event=None):
self.paramgroup = self.feffit_panel.get_paramgroup()
self.model.set_data(self.paramgroup,
pathkeys=self.feffit_panel.get_pathkeys())
self.model.read_data()
self.feffit_panel.get_pathpage('parameters').Rebuild()
def onClose(self, event=None):
self.Destroy()
class FeffitParamsPanel(wx.Panel):
def __init__(self, parent=None, feffit_panel=None, **kws):
wx.Panel.__init__(self, parent, -1, size=(550, 250))
self.feffit_panel = feffit_panel
self.parwids = {}
self.SetFont(Font(FONTSIZE))
spanel = scrolled.ScrolledPanel(self)
spanel.SetSize((250, 250))
spanel.SetMinSize((50, 50))
panel = self.panel = GridPanel(spanel, ncols=8, nrows=30, pad=1, itemstyle=LEFT)
panel.SetFont(Font(FONTSIZE))
def SLabel(label, size=(80, -1), **kws):
return SimpleText(panel, label, size=size, style=wx.ALIGN_LEFT, **kws)
panel.Add(SLabel("Feffit Parameters ", colour='#0000AA', size=(200, -1)), dcol=2)
panel.Add(Button(panel, 'Edit Parameters', action=self.onEditParams), dcol=2)
panel.Add(Button(panel, 'Force Refresh', action=self.Rebuild), dcol=3)
panel.Add(SLabel("Parameter "), style=wx.ALIGN_LEFT, newrow=True)
panel.AddMany((SLabel(" Value"), SLabel(" Type"), SLabel(' Bounds'),
SLabel(" Min", size=(60, -1)),
SLabel(" Max", size=(60, -1)),
SLabel(" Expression")))
self.update()
panel.pack()
ssizer = wx.BoxSizer(wx.VERTICAL)
ssizer.Add(panel, 1, wx.GROW|wx.ALL, 2)
pack(spanel, ssizer)
spanel.SetupScrolling()
mainsizer = wx.BoxSizer(wx.VERTICAL)
mainsizer.Add(spanel, 1, wx.GROW|wx.ALL, 2)
pack(self, mainsizer)
def Rebuild(self, event=None):
for pname, parwid in self.parwids.items():
for x in parwid.widgets:
x.Destroy()
self.panel.irow = 1
self.parwids = {}
self.update()
def set_init_values(self, params):
for pname, par in params.items():
if pname in self.parwids and par.vary:
stderr = getattr(par, 'stderr', 0.001)
try:
prec = max(1, min(8, round(2-math.log10(stderr))))
except:
prec = 5
self.parwids[pname].value.SetValue(("%%.%.df" % prec) % par.value)
def update(self):
pargroup = self.feffit_panel.get_paramgroup()
hashkeys = self.feffit_panel.get_pathkeys()
params = group2params(pargroup)
for pname, par in params.items():
if any([pname.endswith('_%s' % phash) for phash in hashkeys]):
continue
if pname not in self.parwids and not hasattr(par, '_is_pathparam'):
pwids = ParameterWidgets(self.panel, par, name_size=100,
expr_size=150, float_size=70,
with_skip=True,
widgets=('name', 'value',
'minval', 'maxval',
'vary', 'expr'))
self.parwids[pname] = pwids
self.panel.Add(pwids.name, newrow=True)
self.panel.AddMany((pwids.value, pwids.vary, pwids.bounds,
pwids.minval, pwids.maxval, pwids.expr))
self.panel.pack()
pwids = self.parwids[pname]
varstr = 'vary' if par.vary else 'fix'
if par.expr is not None:
varstr = 'constrain'
pwids.expr.SetValue(par.expr)
if getattr(par, 'skip', None) not in (False, None):
varstr = 'skip'
pwids.vary.SetStringSelection(varstr)
if varstr != 'skip':
pwids.value.SetValue(par.value)
pwids.minval.SetValue(par.min)
pwids.maxval.SetValue(par.max)
pwids.onVaryChoice()
self.panel.Update()
def onEditParams(self, event=None):
pargroup = self.feffit_panel.get_paramgroup()
self.feffit_panel.show_subframe('edit_params', EditParamsFrame,
paramgroup=pargroup,
feffit_panel=self.feffit_panel)
def RemoveParams(self, event=None, name=None):
if name is None:
return
pargroup = self.feffit_panel.get_paramgroup()
if hasattr(pargroup, name):
delattr(pargroup, name)
if name in self.parwids:
pwids = self.parwids.pop(name)
pwids.name.Destroy()
pwids.value.Destroy()
pwids.vary.Destroy()
pwids.bounds.Destroy()
pwids.minval.Destroy()
pwids.maxval.Destroy()
pwids.expr.Destroy()
pwids.remover.Destroy()
def generate_params(self, event=None):
s = []
s.append(COMMANDS['feffit_params_init'])
for name, pwids in self.parwids.items():
param = pwids.param
args = [f'{param.value}']
minval = pwids.minval.GetValue()
if np.isfinite(minval):
args.append(f'min={minval}')
maxval = pwids.maxval.GetValue()
if np.isfinite(maxval):
args.append(f'max={maxval}')
varstr = pwids.vary.GetStringSelection()
if varstr == 'skip':
args.append('skip=True, vary=False')
elif param.expr is not None and varstr == 'constrain':
args.append(f"expr='{param.expr}'")
elif varstr == 'vary':
args.append(f'vary=True')
else:
args.append(f'vary=False')
args = ', '.join(args)
cmd = f'_feffit_params.{name} = param({args})'
s.append(cmd)
return s
class FeffPathPanel(wx.Panel):
"""Feff Path """
def __init__(self, parent, feffit_panel, filename, title, user_label,
geomstr, absorber, shell, reff, nleg, degen,
par_amp, par_e0, par_delr, par_sigma2, par_third, par_ei):
self.parent = parent
self.title = title
self.user_label = fix_varname(f'{title:s}')
self.feffit_panel = feffit_panel
self.editing_enabled = False
wx.Panel.__init__(self, parent, -1, size=(550, 250))
self.SetFont(Font(FONTSIZE))
panel = GridPanel(self, ncols=4, nrows=4, pad=2, itemstyle=LEFT)
self.fullpath = filename
par, feffdat_file = os.path.split(filename)
parent_folder, dirname = os.path.split(par)
self.user_label = user_label
self.nleg = nleg
self.reff = reff
self.geomstr = geomstr
# self.geometry = geometry
def SLabel(label, size=(80, -1), **kws):
return SimpleText(panel, label, size=size, style=LEFT, **kws)
self.wids = wids = {}
for name, expr in (('label', user_label),
('amp', par_amp),
('e0', par_e0),
('delr', par_delr),
('sigma2', par_sigma2),
('third', par_third),
('ei', par_ei)):
self.wids[name] = wx.TextCtrl(panel, -1, size=(250, -1),
value=expr, style=wx.TE_PROCESS_ENTER)
wids[name+'_val'] = SimpleText(panel, '', size=(150, -1), style=LEFT)
wids['use'] = Check(panel, default=True, label='Use in Fit?', size=(100, -1))
wids['del'] = Button(panel, 'Remove This Path', size=(150, -1),
action=self.onRemovePath)
wids['plot_feffdat'] = Button(panel, 'Plot F(k)', size=(150, -1),
action=self.onPlotFeffDat)
scatt = {2: 'Single', 3: 'Double', 4: 'Triple',
5: 'Quadruple'}.get(nleg, f'{nleg-1:d}-atom')
scatt = scatt + ' Scattering'
title1 = f'{dirname:s}: {feffdat_file:s} {absorber:s} {shell:s} edge'
title2 = f'Reff={reff:.4f}, Degen={degen:.1f}, {scatt:s}: {geomstr:s}'
panel.Add(SLabel(title1, size=(375, -1), colour='#0000AA'),
dcol=2, style=wx.ALIGN_LEFT, newrow=True)
panel.Add(wids['use'])
panel.Add(wids['del'])
panel.Add(SLabel(title2, size=(425, -1)),
dcol=3, style=wx.ALIGN_LEFT, newrow=True)
panel.Add(wids['plot_feffdat'])
panel.AddMany((SLabel('Label'), wids['label'], wids['label_val']), newrow=True)
panel.AddMany((SLabel('Amplitude'), wids['amp'], wids['amp_val']), newrow=True)
panel.AddMany((SLabel('E0 '), wids['e0'], wids['e0_val']), newrow=True)
panel.AddMany((SLabel('Delta R'), wids['delr'], wids['delr_val']), newrow=True)
panel.AddMany((SLabel('sigma2'), wids['sigma2'], wids['sigma2_val']),newrow=True)
panel.AddMany((SLabel('third'), wids['third'], wids['third_val']), newrow=True)
panel.AddMany((SLabel('Eimag'), wids['ei'], wids['ei_val']), newrow=True)
panel.pack()
sizer= wx.BoxSizer(wx.VERTICAL)
sizer.Add(panel, 1, LEFT|wx.GROW|wx.ALL, 2)
pack(self, sizer)
def enable_editing(self):
for name in ('label', 'amp', 'e0', 'delr', 'sigma2', 'third', 'ei'):
self.wids[name].Bind(wx.EVT_TEXT_ENTER, partial(self.onExpression, name=name))
self.wids[name].Bind(wx.EVT_KILL_FOCUS, partial(self.onExpression, name=name))
self.editing_enabled = True
self.wids['label'].SetValue(self.user_label)
def set_userlabel(self, label):
self.wids['label'].SetValue(label)
def get_expressions(self):
out = {'use': self.wids['use'].IsChecked()}
for key in ('label', 'amp', 'e0', 'delr', 'sigma2', 'third', 'ei'):
val = self.wids[key].GetValue().strip()
if len(val) == 0: val = '0'
out[key] = val
return out
def onExpression(self, event=None, name=None):
if name is None:
return
expr = self.wids[name].GetValue()
if name == 'label':
time.sleep(0.001)
return
expr = self.wids[name].GetValue().strip()
if len(expr) < 1:
return
opts= dict(value=1.e-3, minval=None, maxval=None)
if name == 'sigma2':
opts['minval'] = 0
opts['maxval'] = 1
opts['value'] = np.sqrt(self.reff)/200.0
elif name == 'delr':
opts['minval'] = -0.75
opts['maxval'] = 0.75
elif name == 'amp':
opts['value'] = 1
result = self.feffit_panel.update_params_for_expr(expr, **opts)
if result:
pargroup = self.feffit_panel.get_paramgroup()
_eval = pargroup.__params__._asteval
try:
value = _eval.eval(expr, show_errors=False, raise_errors=False)
if value is not None:
value = gformat(value, 11)
self.wids[name + '_val'].SetLabel(f'= {value}')
except:
result = False
if result:
bgcol, fgcol = 'white', 'black'
else:
bgcol, fgcol = '#AAAA4488', '#AA0000'
self.wids[name].SetForegroundColour(fgcol)
self.wids[name].SetBackgroundColour(bgcol)
self.wids[name].SetOwnBackgroundColour(bgcol)
if event is not None:
event.Skip()
def onPlotFeffDat(self, event=None):
cmd = f"plot_feffdat(_feffpaths['{self.title}'], title='Feff data for path {self.title}')"
self.feffit_panel.larch_eval(cmd)
def onRemovePath(self, event=None):
msg = f"Delete Path {self.title:s}?"
dlg = wx.MessageDialog(self, msg, 'Warning', wx.YES | wx.NO )
if (wx.ID_YES == dlg.ShowModal()):
self.feffit_panel.paths_data.pop(self.title)
self.feffit_panel.model_needs_build = True
path_nb = self.feffit_panel.paths_nb
for i in range(path_nb.GetPageCount()):
if self.title == path_nb.GetPageText(i).strip():
path_nb.DeletePage(i)
self.feffit_panel.skip_unused_params()
dlg.Destroy()
def update_values(self):
pargroup = self.feffit_panel.get_paramgroup()
_eval = pargroup.__params__._asteval
for par in ('amp', 'e0', 'delr', 'sigma2', 'third', 'ei'):
expr = self.wids[par].GetValue().strip()
if len(expr) > 0:
try:
value = _eval.eval(expr, show_errors=False, raise_errors=False)
if value is not None:
value = gformat(value, 10)
self.wids[par + '_val'].SetLabel(f'= {value}')
except:
self.feffit_panel.update_params_for_expr(expr)
class FeffitPanel(TaskPanel):
def __init__(self, parent=None, controller=None, **kws):
self.resetting = False
self.model_needs_rebuild = False
self.params_need_update = False
self.rmin_warned = False
TaskPanel.__init__(self, parent, controller, panel='feffit', **kws)
self.paths_data = {}
self.config_saved = self.get_defaultconfig()
self.dgroup = None
def onPanelExposed(self, **kws):
# called when notebook is selected
dgroup = self.controller.get_group()
try:
pargroup = self.get_paramgroup()
self.params_panel.update()
fname = self.controller.filelist.GetStringSelection()
gname = self.controller.file_groups[fname]
dgroup = self.controller.get_group(gname)
if not hasattr(dgroup, 'chi'):
self.xasmain.process_exafs(dgroup)
self.fill_form(dgroup)
except:
pass # print(" Cannot Fill feffit panel from group ")
if dgroup is not self.dgroup:
# setting up feffit for this group
self.dgroup = dgroup
try:
has_fit_hist = len(self.dgroup.feffit_history) > 0
except:
has_fit_hist = getattr(self.larch.symtable, '_feffit_dataset', None) is not None
if has_fit_hist:
self.wids['show_results'].Enable()
feffpaths = getattr(self.larch.symtable, '_feffpaths', None)
if feffpaths is not None:
self.reset_paths()
self.params_panel.update()
self.skip_unused_params()
self.params_need_update = False
def build_display(self):
self.paths_nb = flatnotebook(self, {}, on_change=self.onPathsNBChanged,
with_dropdown=True)
self.params_panel = FeffitParamsPanel(parent=self.paths_nb,
feffit_panel=self)
self.paths_nb.AddPage(self.params_panel, ' Parameters ', True)
pan = self.panel # = GridPanel(self, ncols=4, nrows=4, pad=2, itemstyle=LEFT)
self.wids = wids = {}
fsopts = dict(digits=2, increment=0.1, with_pin=True)
fit_kmin = self.add_floatspin('fit_kmin', value=2, **fsopts)
fit_kmax = self.add_floatspin('fit_kmax', value=17, **fsopts)
fit_dk = self.add_floatspin('fit_dk', value=4, **fsopts)
fit_rmax = self.add_floatspin('fit_rmax', value=5, **fsopts)
fit_rmin = self.add_floatspin('fit_rmin', value=1, action=self.onRmin, **fsopts)
wids['fit_kwstring'] = Choice(pan, size=(120, -1),
choices=list(Feffit_KWChoices.keys()))
wids['fit_kwstring'].SetSelection(1)
wids['fit_kwindow'] = Choice(pan, choices=list(FT_WINDOWS), size=(150, -1))
wids['fit_space'] = Choice(pan, choices=list(Feffit_SpaceChoices.keys()),
size=(150, -1))
wids['plot_kw'] = Choice(pan, size=(80, -1),
choices=['0', '1', '2', '3', '4'], default=2)
wids['plot1_op'] = Choice(pan, choices=list(Plot1_Choices.keys()),
action=self.onPlot, size=(150, -1))
wids['plot1_op'].SetSelection(1)
wids['plot1_voff'] = FloatSpin(pan, value=0, digits=2, increment=0.25,
size=(100, -1), action=self.onPlot)
wids['plot1_paths'] = Check(pan, default=False, label='Plot Each Path',
action=self.onPlot)
wids['plot1_ftwins'] = Check(pan, default=False, label='Plot FT Windows',
action=self.onPlot)
wids['plot2_win'] = Choice(pan, choices=PlotWindowChoices,
action=self.onPlot, size=(55, -1))
wids['plot2_win'].SetStringSelection('2')
wids['plot2_win'].SetToolTip('Plot Window for Second Plot')
wids['plot2_op'] = Choice(pan, choices=list(Plot2_Choices.keys()),
action=self.onPlot, size=(150, -1))
wids['plot2_voff'] = FloatSpin(pan, value=0, digits=2, increment=0.25,
size=(100, -1), action=self.onPlot)
wids['plot2_paths'] = Check(pan, default=False, label='Plot Each Path',
action=self.onPlot)
wids['plot2_ftwins'] = Check(pan, default=False, label='Plot FT Windows',
action=self.onPlot)
wids['plot_current'] = Button(pan,'Plot Current Model',
action=self.onPlot, size=(175, -1))
wids['refine_bkg'] = Check(pan, default=False,
label='Refine Background during Fit?')
wids['do_fit'] = Button(pan, 'Fit Data to Model',
action=self.onFitModel, size=(175, -1))
wids['show_results'] = Button(pan, 'Show Fit Results',
action=self.onShowResults, size=(175, -1))
wids['show_results'].Disable()
def add_text(text, dcol=1, newrow=True):
pan.Add(SimpleText(pan, text), dcol=dcol, newrow=newrow)
pan.Add(SimpleText(pan, 'Feff Fitting',
size=(150, -1), **self.titleopts), style=LEFT, dcol=1)
pan.Add(SimpleText(pan, 'Use Feff->Browse Feff Calculations to Add Paths',
size=(425, -1)), style=LEFT, dcol=4)
add_text('Fitting Space: ')
pan.Add(wids['fit_space'])
add_text('k weightings: ', newrow=False)
pan.Add(wids['fit_kwstring'], dcol=3)
add_text('k min: ')
pan.Add(fit_kmin)
add_text(' k max: ', newrow=False)
pan.Add(fit_kmax)
add_text('k Window: ')
pan.Add(wids['fit_kwindow'])
add_text('dk: ', newrow=False)
pan.Add(fit_dk)
add_text('R min: ')
pan.Add(fit_rmin)
add_text('R max: ', newrow=False)
pan.Add(fit_rmax)
add_text(' ', newrow=True)
pan.Add(wids['refine_bkg'], dcol=3)
pan.Add(HLine(pan, size=(600, 2)), dcol=6, newrow=True)
pan.Add(wids['plot_current'], dcol=1, newrow=True)
pan.Add(wids['plot1_op'], dcol=1)
add_text('k-weight:' , newrow=False)
pan.Add(wids['plot_kw'], dcol=1)
pan.Add(wids['plot1_ftwins'], newrow=True)
pan.Add(wids['plot1_paths'])
add_text('Vertical Offset' , newrow=False)
pan.Add(wids['plot1_voff'])
add_text('Add Second Plot: ')
pan.Add(wids['plot2_op'], dcol=1)
add_text('Plot Window:' , newrow=False)
pan.Add(wids['plot2_win'])
pan.Add(wids['plot2_ftwins'], newrow=True)
pan.Add(wids['plot2_paths'])
add_text('Vertical Offset' , newrow=False)
pan.Add(wids['plot2_voff'])
pan.Add(wids['do_fit'], dcol=1, newrow=True)
pan.Add(wids['show_results'])
pan.Add((5, 5), newrow=True)
pan.Add(HLine(pan, size=(600, 2)), dcol=6, newrow=True)
pan.pack()
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(pan, 0, LEFT, 3)
sizer.Add((3, 3), 0, LEFT, 3)
sizer.Add(SimpleText(self, ' Parameters and Paths'), 0, LEFT, 2)
sizer.Add((3, 3), 0, LEFT, 3)
sizer.Add(self.paths_nb, 1, LEFT|wx.GROW, 5)
pack(self, sizer)
def onRmin(self, event=None, **kws):
dgroup = self.controller.get_group()
if dgroup is None:
return
rbkg = getattr(dgroup, 'rbkg', None)
callargs = getattr(dgroup, 'callargs', None)
if rbkg is None and callargs is not None:
autobk_args = getattr(callargs, 'autobk', {'rbkg': 1.0})
rbkg = autobk_args.get('rbkg', None)
if rbkg is None: rbkg = 0.0
rmin = self.wids['fit_rmin'].GetValue()
if rmin > (rbkg-0.025):
self.rmin_warned = False
if rmin < (rbkg-0.025) and not self.rmin_warned:
self.rmin_warned = True
Popup(self,
f"""Rmin={rmin:.3f} Ang is below Rbkg={rbkg:.3f} Ang.
This should be done with caution.""",
"Warning: Rmin < Rbkg",
style=wx.ICON_WARNING|wx.OK_DEFAULT)
def onPathsNBChanged(self, event=None):
updater = getattr(self.paths_nb.GetCurrentPage(), 'update_values', None)
if self.params_need_update and not self.resetting:
self.params_panel.update()
self.skip_unused_params()
self.params_need_update = False
if callable(updater) and not self.resetting:
updater()
def get_config(self, dgroup=None):
"""get and set processing configuration for a group"""
if dgroup is None:
dgroup = self.controller.get_group()
if dgroup is None:
conf = None
if not hasattr(dgroup, 'chi'):
self.xasmain.process_exafs(dgroup)
dconf = self.get_defaultconfig()
if dgroup is None:
return dconf
if not hasattr(dgroup, 'config'):
dgroup.config = Group()
conf = getattr(dgroup.config, self.configname, dconf)
for k, v in dconf.items():
if k not in conf:
conf[k] = v
econf = getattr(dgroup.config, 'exafs', {})
for key in ('fit_kmin', 'fit_kmax', 'fit_dk',
'fit_rmin', 'fit_rmax', 'fit_dr',
'fit_kwindow', 'fit_rwindow'):
val = conf.get(key, -1)
if val in (None, -1, 'Auto'):
alt = key.replace('fit', 'fft')
if alt in econf:
conf[key] = econf[alt]