Debian Codegraph @

athena_parts/peakfit.pl

raw
1 ## -*- cperl -*-
2 ##
3 ## This file is part of Athena, copyright (c) 2001-2009 Bruce Ravel
4 ##
5 ## This section of the code contains subroutines associated with
6 ## near edge peak fitting.
7
8
9 sub peak_fit {
10 Echo("No data!"), return unless $current;
11 Echo("No data!"), return if ($current eq "Default Parameters");
12 my $ps = $project_saved;
13 my @save = ($plot_features{emin}, $plot_features{emax});
14 $plot_features{emin} = $config{peakfit}{emin};
15 $plot_features{emax} = $config{peakfit}{emax};
16 project_state($ps); # don't toggle if currently saved
17 my $npeaks = $config{peakfit}{maxpeaks};
18 my @peaks = ();
19 my @param_list = ("amp", "width");
20
21 $fat_showing = 'peakfit';
22 map {$_ -> configure(-state=>'disabled')}
23 ($data_menu, $merge_menu, $anal_menu, $settings_menu);
24 $fat -> packForget;
25 my $peak = $container->Frame(@fatgeom, -relief=>'sunken', -borderwidth=>3)
26 -> pack(-fill=>'both', -expand=>1);
27 #$peak -> packPropagate(0);
28 $which_showing = $peak;
29
30 my %peak_params = (function => 'atan', function_choice => 'atan',
31 fit_e => 0,
32 fit_a => 1,
33 fit_w => 1,
34 emin => $config{peakfit}{fitmin},
35 emax => $config{peakfit}{fitmax},
36 enot => $groups{$current}->{bkg_e0},
37 amp => 1, width => 1,
38 plot_components => $config{peakfit}{components},
39 plot_difference => $config{peakfit}{difference},
40 mark_centroids => $config{peakfit}{centroids},
41 toplevel => $peak,
42 deltas => []);
43 #my %function_map = (arctangent=>'atan', None=>'None', 'error function'=>'erf',
44 # Gaussian=>'gauss', Lorentzian=>'loren', none=>'none',
45 # 'pseudo-Voight'=>'pvoight');
46 $hash_pointer = \%peak_params;
47 my $peak_results;
48
49 $peak -> Label(-text=>"Peak fitting with lineshapes",
50 -font=>$config{fonts}{large},
51 -foreground=>$config{colors}{activehighlightcolor})
52 -> pack(-side=>'top', -fill=>'x', -anchor=>'w');
53 my $params_frame = $peak -> Frame(-borderwidth=>2, -relief=>'flat')
54 -> pack(-side=>'top', -fill=>'x', -ipadx=>5);
55 my $frame = $params_frame -> Frame(-borderwidth=>2, -relief=>'flat')
56 -> pack(-side=>'top', -fill=>'x', -ipadx=>5);
57 $frame -> Label(-text=>'Group: ',
58 -foreground=>$config{colors}{activehighlightcolor},
59 )
60 -> pack(-side=>'left');
61 $widget{peak_group} = $frame -> Label(-text=>$groups{$current}->{label},
62 -foreground=>$config{colors}{button},
63 #-width=>15, -justify=>'left'
64 )
65 -> pack(-side=>'left', -padx=>3, -anchor=>'w');
66
67
68 ## pack the next few in reverse order so they go flush up against
69 ## the right hand side
70 $grab{peak_emax} = $frame -> Button(@pluck_button, @pluck,
71 -command=>sub{&pluck("peak_emax");
72 my $e = $widget{peak_emax}->get();
73 $e = sprintf("%.3f", $e-$peak_params{enot});
74 $widget{peak_emax}->delete(0, 'end');
75 $widget{peak_emax}->insert(0, $e);
76 })
77 -> pack(-side=>'right', -pady=>3);
78 $widget{peak_emax} = $frame -> Entry(-width=>5, -textvariable=>\$peak_params{emax},
79 -validate=>'all',
80 -validatecommand=>[\&peak_set_variable, 'emax'],
81 )
82 -> pack(-side=>'right', -pady=>3);
83 $frame -> Label(-text=> "to",
84 -foreground=>$config{colors}{activehighlightcolor})
85 -> pack(-side=>'right', -pady=>6);
86 $grab{peak_emin} = $frame -> Button(@pluck_button, @pluck,
87 -command=>sub{&pluck("peak_emin");
88 my $e = $widget{peak_emin}->get();
89 $e = sprintf("%.3f", $e-$peak_params{enot});
90 $widget{peak_emin}->delete(0, 'end');
91 $widget{peak_emin}->insert(0, $e);
92 })
93 -> pack(-side=>'right', -pady=>3);
94 $widget{peak_emin} = $frame -> Entry(-width=>5, -textvariable=>\$peak_params{emin},
95 -validate=>'all',
96 -validatecommand=>[\&peak_set_variable, 'emin'],
97 )
98 -> pack(-side=>'right', -pady=>3);
99 $frame -> Label(-text=> "Fitting range:",
100 -foreground=>$config{colors}{activehighlightcolor},
101 )
102 -> pack(-side=>'right', -pady=>3, -fill=>'x');
103
104
105
106 $frame = $params_frame -> Frame(-borderwidth=>2, -relief=>'flat')
107 -> pack(-side=>'top', -fill=>'x', -ipadx=>5);
108
109 $widget{peak_components} = $frame ->
110 Checkbutton(-text=>'Plot components', -selectcolor=>$config{colors}{single},
111 -variable=>\$peak_params{plot_components})
112 -> pack(-side=>'left', -padx=>5);#, -expand=>1, -anchor=>'w');
113 $widget{peak_difference} = $frame ->
114 Checkbutton(-text=>'Plot difference', -selectcolor=>$config{colors}{single},
115 -variable=>\$peak_params{plot_difference})
116 -> pack(-side=>'left', -padx=>5);#, -expand=>1, -anchor=>'center');
117 $widget{peak_show} = $frame ->
118 Checkbutton(-text=>'Mark centroids', -selectcolor=>$config{colors}{single},
119 -command=>sub{$peak_params{mark_centroids} and
120 peak_mark_centroids($current,\%peak_params,\@peaks);},
121 -variable=>\$peak_params{mark_centroids})
122 -> pack(-side=>'left', -padx=>5);
123
124
125 $peak -> Button(-text=>'Return to the main window', @button_list,
126 -background=>$config{colors}{background2},
127 -activebackground=>$config{colors}{activebackground2},
128 -command=>sub{
129 $groups{$current}->dispose("erase \@group p___eak", $dmode);
130 $groups{$current}->dispose("erase p___eak_enot p___eak_amp p___eak_width",
131 $dmode);
132 foreach my $ipk (0 .. $#peaks) {
133 my $i = $ipk+1;
134 $groups{$current}->dispose("erase p___eak_e$i p___eak_a$i p___eak_w$i",
135 $dmode);
136 };
137 &reset_window($peak, "peak fitting", \@save);
138 })
139 -> pack(-side=>'bottom', -fill=>'x', -padx=>5, -pady=>5);
140
141 ## help button
142 $peak -> Button(-text=>'Document section: peak fitting', @button_list,
143 -command=>sub{pod_display("analysis::peak.pod")})
144 -> pack(-side=>'bottom', -fill=>'x', -pady=>4);
145
146 ## frame with buttons in
147 my $nb = $peak -> NoteBook(-backpagecolor=>$config{colors}{background},
148 -inactivebackground=>$config{colors}{inactivebackground},)
149 -> pack(-side=>'top', -expand=>1, -fill=>'y');
150
151 ## step function
152 #my $lab = $frame -> Frame(-borderwidth=>2, -relief=>'flat')
153 # -> pack(-side=>'top', -expand=>1, -fill=>'both');
154
155 my %nc;
156 $nc{params} = $nb -> add('params', -label=>'Parameters', -anchor=>'center',);
157
158 ## there should be a Pane here
159 my $pane = $nc{params} -> Scrolled('Pane', -relief=>'groove', -borderwidth=>2,
160 -scrollbars=>'oe')
161 -> pack(-expand=>1, -fill=>'y');
162 $pane->Subwidget("yscrollbar")->configure(-background=>$config{colors}{background});
163
164 my $hlist = $pane -> HList(-columns=>10, -header=>1, -width=>65, -height=>18,
165 -selectborderwidth=>0, -selectbackground=>
166 $config{colors}{activebackground} )
167 -> pack(-expand=>1, -fill=>'y', -anchor=>'n');
168 my $style = $hlist ->
169 ItemStyle('text', -foreground=>$config{colors}{activehighlightcolor},
170 -font=>$config{fonts}{smbold},
171 -anchor=>'center');
172 my $ih = 0;
173 foreach my $t ('Function', 'Centroid', '', 'Fit', ' ',
174 'Amp.', 'Fit', ' ', 'Width', 'Fit') {
175 $hlist->headerCreate($ih++, -headerbackground=>$config{colors}{background},
176 -itemtype=>'text', -style=>$style,
177 -text=>=>$t);
178 };
179 $hlist->add(1);
180
181 $widget{peak_function} = $hlist -> Optionmenu(-textvariable => \$peak_params{function_choice},
182 -borderwidth=>1, -width=>5);
183 foreach my $f ('none', 'atan', 'erf', 'CL') {
184 $widget{peak_function}
185 -> command(-label => $f, -state=>($f =~ /CL/) ? 'disabled' : 'normal',
186 -command=>sub{
187 $peak_params{function_choice} = $f;
188 SWITCH: {
189 $peak_params{function} = 'none', last SWITCH if ($f eq 'none');
190 $peak_params{function} = 'atan', last SWITCH if ($f eq 'atan');
191 $peak_params{function} = 'erf', last SWITCH if ($f eq 'erf');
192 $peak_params{function} = 'CL', last SWITCH if ($f eq 'CL');
193 };
194 foreach my $p (@param_list) {
195 $peak_params{$p} = $widget{"peak_$p"}->get();
196 };
197 #&peak_do_fit($current, \%peak_params, $peak_results, @peaks);
198 });
199 };
200 $hlist->itemCreate(1, 0, -itemtype=>'window', -widget=>$widget{peak_function});
201 $widget{peak_enot} = $hlist -> Entry(-width=>8, -textvariable=>\$peak_params{enot},
202 -validate=>'all',
203 -validatecommand=>[\&peak_set_variable, 'enot'],
204 );
205 $hlist->itemCreate(1, 1, -itemtype=>'window', -widget=>$widget{peak_enot});
206 my $inner = $hlist -> Frame();
207 $hlist->itemCreate(1, 2, -itemtype=>'window', -widget=>$inner);
208 $grab{peak_enot} = $inner -> Button(@pluck_button, @pluck,
209 -command=>sub{&pluck("peak_enot");}) -> pack();
210 $widget{peak_fit_e} = $hlist -> Checkbutton(-text=>"",
211 -selectcolor=>$config{colors}{single},
212 -variable=>\$peak_params{fit_e});
213 $hlist->itemCreate(1, 3, -itemtype=>'window', -widget=>$widget{peak_fit_e});
214 ##$hlist->itemCreate(1, 2, -itemtype=>'window', -widget=>$grab{peak_enot});
215 $widget{peak_amp} = $hlist -> Entry(-width=>6, -textvariable=>\$peak_params{amp},
216 -validate=>'all',
217 -validatecommand=>[\&peak_set_variable, 'amp'],
218 );
219 $hlist->itemCreate(1, 5, -itemtype=>'window', -widget=>$widget{peak_amp});
220 $widget{peak_fit_a} = $hlist -> Checkbutton(-text=>"",
221 -selectcolor=>$config{colors}{single},
222 -variable=>\$peak_params{fit_a});
223 $hlist->itemCreate(1, 6, -itemtype=>'window', -widget=>$widget{peak_fit_a});
224 $widget{peak_width} = $hlist -> Entry(-width=>6, -textvariable=>\$peak_params{width},
225 -validate=>'all',
226 -validatecommand=>[\&peak_set_variable, 'width'],
227 );
228 $hlist->itemCreate(1, 8, -itemtype=>'window', -widget=>$widget{peak_width});
229 $widget{peak_fit_w} = $hlist -> Checkbutton(-text=>"",
230 -selectcolor=>$config{colors}{single},
231 -variable=>\$peak_params{fit_w});
232 $hlist->itemCreate(1, 9, -itemtype=>'window', -widget=>$widget{peak_fit_w});
233
234
235 #my $normalbg=$top->ItemStyle('window', -background=>$config{colors}{background});
236 #my $alternatebg=$top->ItemStyle('window', -background=>$config{colors}{background2});
237 foreach my $i (1 .. $npeaks) {
238 $hlist->add($i+1);
239
240 $peak_params{"e$i"} = "";
241 $peak_params{"a$i"} = $config{peakfit}{peakamp};
242 $peak_params{"w$i"} = $config{peakfit}{peakwidth};
243 $peak_params{"f$i"} = "none";
244 $peak_params{"function$i"} = "none";
245 $peak_params{"fit_e$i"} = 0;
246 $peak_params{"fit_a$i"} = 1;
247 $peak_params{"fit_w$i"} = 1;
248 $peaks[$i] = 0;
249 #my $bg = ($i % 2) ? $config{colors}{background2} : $config{colors}{background};
250 #my $abg = ($i % 2) ? $config{colors}{activebackground2} :
251 my $bg = $config{colors}{background};
252 my $abg = $config{colors}{activebackground};
253 #my $style = ($i % 2) ? $alternatebg : $normalbg;
254 push @param_list, "e$i", "a$i", "w$i";
255 $widget{"peak_function$i"} = $hlist ->
256 Optionmenu(-textvariable => \$peak_params{"function$i"}, -width=>5,
257 -borderwidth=>1, -background=>$bg, -activebackground=>$abg);
258 foreach my $f (qw(none gauss loren pvoight atan erf CL)) {
259 $widget{"peak_function$i"} ->
260 command(-label => $f, -state=>($f =~ /(pvoight|CL)/) ? 'disabled' : 'normal',
261 -command=>sub{
262 $peak_params{"function$i"} = $f;
263 $peaks[$i] = ($f eq 'none') ? 0 : 1;
264 SWITCH: {
265 $peak_params{"f$i"} = 'none', last SWITCH if ($f eq 'none');
266 $peak_params{"f$i"} = 'gauss', last SWITCH if ($f eq 'gauss');
267 $peak_params{"f$i"} = 'loren', last SWITCH if ($f eq 'loren');
268 $peak_params{"f$i"} = 'pvoight', last SWITCH if ($f eq 'pvoight');
269 $peak_params{"f$i"} = 'atan', last SWITCH if ($f eq 'atan');
270 $peak_params{"f$i"} = 'erf', last SWITCH if ($f eq 'erf');
271 $peak_params{"f$i"} = 'CL', last SWITCH if ($f eq 'CL');
272 };
273 foreach my $p (qw(e a w)) {
274 $peak_params{$p.$i} = $widget{"peak_$p$i"}->get();
275 };
276 #&peak_do_fit($current, \%peak_params, $peak_results, @peaks);
277 });
278 };
279 $hlist->itemCreate($i+1, 0, -itemtype=>'window', -widget=>$widget{"peak_function$i"});
280 $widget{"peak_e$i"} = $hlist -> Entry(-width=>8, -textvariable=>\$peak_params{"e$i"},
281 -background=>$bg, -validate=>'all',
282 -validatecommand=>[\&peak_set_variable, "e$i"],
283 );
284 $hlist->itemCreate($i+1, 1, -itemtype=>'window',
285 -widget=>$widget{"peak_e$i"});
286 my $inner = $hlist -> Frame();
287 $hlist->itemCreate($i+1, 2, -itemtype=>'window', -widget=>$inner);
288 $grab{"peak_e$i"} = $inner -> Button(@pluck_button, @pluck,
289 -background=>$bg , -activebackground=>$abg,
290 -command=>sub{&pluck("peak_e$i")}) -> pack();
291 #$hlist->itemCreate($i+1, 2, -itemtype=>'window', -widget=>$grab{"peak_e$i"});
292 $widget{"peak_fit_e$i"} = $hlist -> Checkbutton(-text=>"",
293 -background=>$bg,
294 -activebackground=>$abg,
295 -selectcolor=>$config{colors}{single},
296 -variable=>\$peak_params{"fit_e$i"});
297 $hlist->itemCreate($i+1, 3, -itemtype=>'window', -widget=>$widget{"peak_fit_e$i"});
298 $widget{"peak_a$i"} = $hlist -> Entry(-width=>6, -textvariable=>\$peak_params{"a$i"},
299 -background=>$bg, -validate=>'all',
300 -validatecommand=>[\&peak_set_variable, "a$i"],
301 );
302 $hlist->itemCreate($i+1, 5, -itemtype=>'window', -widget=>$widget{"peak_a$i"});
303 $widget{"peak_fit_a$i"} = $hlist -> Checkbutton(-text=>"",
304 -background=>$bg,
305 -activebackground=>$abg,
306 -selectcolor=>$config{colors}{single},
307 -variable=>\$peak_params{"fit_a$i"});
308 $hlist->itemCreate($i+1, 6, -itemtype=>'window', -widget=>$widget{"peak_fit_a$i"});
309 $widget{"peak_w$i"} = $hlist -> Entry(-width=>6, -textvariable=>\$peak_params{"w$i"},
310 -background=>$bg, -validate=>'all',
311 -validatecommand=>[\&peak_set_variable, "w$i"],
312 );
313 $hlist->itemCreate($i+1, 8, -itemtype=>'window', -widget=>$widget{"peak_w$i"});
314 $widget{"peak_fit_w$i"} = $hlist -> Checkbutton(-text=>"",
315 -background=>$bg,
316 -activebackground=>$abg,
317 -selectcolor=>$config{colors}{single},
318 -variable=>\$peak_params{"fit_w$i"});
319 $hlist->itemCreate($i+1, 9, -itemtype=>'window', -widget=>$widget{"peak_fit_w$i"});
320
321 };
322
323 $frame = $peak -> Frame()
324 -> pack(-side=>'bottom', -fill=>'x');
325 $widget{peak_save} = $frame ->
326 Button(-text=>'Save fit as a data group', @button_list,
327 -width=>1,
328 -state=>'disabled',
329 -command=>sub{
330 my $group = $groups{$current}->{group};
331 my $name = $groups{$current}->{label};
332 my ($new, $label) = group_name("Peak $name");
333 $groups{$new} = Ifeffit::Group -> new(group=>$new, label=>$label);
334 ##$groups{$new} -> set_to_another($groups{$group});
335 $groups{$new} -> make(is_xmu => 0, is_chi => 0, is_rsp => 0,
336 is_qsp => 0, is_bkg => 0,
337 not_data => 1);
338 $groups{$new} -> make(bkg_e0 => $groups{$group}->{bkg_e0});
339 $groups{$new}->{titles} = [];
340 my $text = $peak_results -> get(qw(1.0 end));
341 ## see refresh_titles for explanation
342 foreach (split(/\n/, $text)) {
343 next if ($_ =~ /^\s*$/);
344 my $count = 0;
345 foreach my $i (0..length($_)) {
346 ++$count if (substr($_, $i, 1) eq '(');
347 --$count if ($count and (substr($_, $i, 1) eq ')'));
348 };
349 $_ .= ')' x $count;
350 push @{$groups{$new}->{titles}}, $_;
351 };
352 $groups{$new} -> put_titles;
353 my $sets = "set($new.energy = $group.energy + " . $groups{$group}->{bkg_eshift} . ",\n";
354 $sets .= " $new.det = p___eak.fun)";
355 $groups{$new}->dispose($sets, $dmode);
356 ++$line_count;
357 fill_skinny($list, $new, 1);
358 my $memory_ok = $groups{$new}
359 -> memory_check($top, \&Echo, \%groups, $max_heap, 0, 0);
360 Echo ("WARNING: Ifeffit is out of memory!") if ($memory_ok == -1);
361 }
362 )
363 -> pack(-side=>'left', -expand=>1, -fill=>'x');
364 $widget{peak_log} = $frame ->
365 Button(-text=>'Write a log file', @button_list,
366 -width=>1,
367 -state=>'disabled',
368 -command=>sub{&peak_log($current, $peak_results, \%peak_params, @peaks)}, )
369 -> pack(-side=>'right', -expand=>1, -fill=>'x');
370
371
372 $frame = $peak -> Frame()
373 -> pack(-side=>'bottom', -fill=>'x');
374 $widget{peak_reset} =
375 $frame -> Button(-text=>'Reset amplitudes and widths', @button_list,
376 -width=>1,
377 -command=>sub{
378 $widget{"peak_amp"} -> delete(qw(0 end));
379 $widget{"peak_amp"} -> insert(0, 1.0);
380 $widget{"peak_width"} -> delete(qw(0 end));
381 $widget{"peak_width"} -> insert(0, 1.0);
382 foreach my $i (1 .. $#peaks) {
383 $widget{"peak_a$i"} -> delete(qw(0 end));
384 $widget{"peak_a$i"} -> insert(0, $config{peakfit}{peakamp});
385 $widget{"peak_w$i"} -> delete(qw(0 end));
386 $widget{"peak_w$i"} -> insert(0, $config{peakfit}{peakwidth});
387 };
388 })
389 -> pack(-side=>'right', -expand=>1, -fill=>'x');
390 $widget{peak_plot} =
391 $frame -> Button(-text=>'Plot lineshapes', @button_list,
392 -width=>1,
393 -command=>sub{
394 Error("This is not mu(E) data."), return unless $groups{$current}->{is_xmu};
395 my $fun = $ {$widget{peak_function}->cget("-textvariable")};
396 $peak_params{function} = $fun;
397 foreach my $p (qw(enot amp width)) {
398 $peak_params{$p} = $widget{"peak_$p"}->get();
399 };
400 foreach my $i (1 .. $#peaks) {
401 my $fun = $ {$widget{"peak_function$i"}->cget("-textvariable")};
402 $peaks[$i] = (lc($fun) eq 'none') ? 0 : 1;
403 $peak_params{"f$i"} = $fun;
404 foreach my $p (qw(e a w)) {
405 $peak_params{$p.$i} = $widget{"peak_$p$i"}->get();
406 };
407 };
408 &peak_do_fit($current, 0, \%peak_params, $peak_results, @peaks);
409 $widget{peak_save} -> configure(-state=>'normal');
410 $widget{peak_log} -> configure(-state=>'normal');
411 })
412 -> pack(-side=>'left', -expand=>1, -fill=>'x');
413
414 $peak -> Button(-text=>'Fit lineshapes', @button_list,
415 -command=>sub{
416 Error("This is not mu(E) data."), return unless $groups{$current}->{is_xmu};
417 my $fun = $ {$widget{peak_function}->cget("-textvariable")};
418 $peak_params{function} = $fun;
419 foreach my $p (qw(enot amp width)) {
420 $peak_params{$p} = $widget{"peak_$p"}->get();
421 };
422 foreach my $i (1 .. $#peaks) {
423 my $fun = $ {$widget{"peak_function$i"}->cget("-textvariable")};
424 $peaks[$i] = (lc($fun) eq 'none') ? 0 : 1;
425 $peak_params{"f$i"} = $fun;
426 foreach my $p (qw(e a w)) {
427 $peak_params{$p.$i} = $widget{"peak_$p$i"}->get();
428 };
429 };
430 &peak_do_fit($current, 1, \%peak_params, $peak_results, @peaks);
431 $widget{peak_save} -> configure(-state=>'normal');
432 $widget{peak_log} -> configure(-state=>'normal');
433 })
434 -> pack(-side=>'bottom', -fill=>'x', -pady=>4);
435
436
437
438
439 ## text box containing the results + buttons for log file and data group
440 $nc{results} = $nb -> add('results', -label=>'Results', -anchor=>'center',);
441 $peak_results = $nc{results} -> Scrolled('ROText', qw(-relief sunken -borderwidth 2
442 -wrap none -scrollbars se
443 -width 5 -height 5),
444 -font=>$config{fonts}{fixed})
445 -> pack(qw/-expand yes -fill both -side top/);
446 disable_mouse3($peak_results->Subwidget('rotext'));
447 $peak_results -> Subwidget("yscrollbar")
448 -> configure(-background=>$config{colors}{background});
449 $peak_results -> Subwidget("xscrollbar")
450 -> configure(-background=>$config{colors}{background});
451 $peak_results -> tagConfigure("text", -font=>$config{fonts}{fixedsm});
452
453
454 $groups{$current}->{update_bkg} and $groups{$current}->dispatch_bkg($dmode);
455 $groups{$current}->{peak} and peak_fill_variables($current, \%peak_params, \@peaks);
456 &peak_do_fit($current, 1, \%peak_params, $peak_results, @peaks);
457 #$peak -> grab;
458 $plotsel -> raise('e');
459 $top -> update;
460
461 };
462
463
464 sub peak_do_fit {
465 my ($standard, $do_fit, $r_params, $peak_results, @peaks) = @_;
466
467 Error("Peak fit aborted: " . $groups{$standard}->{label} . " is not an xmu group."),
468 return unless ($groups{$standard}->{is_xmu});
469
470 Echo("Fitting near edge peak structure for \`$groups{$standard}->{label}\' ... ");
471 $top -> Busy(-recurse=>1,);
472 my $emin += $$r_params{emin} + $$r_params{enot};
473 my $emax += $$r_params{emax} + $$r_params{enot};
474 my $offset = "";
475 SWITCH: {
476 $offset = "/pi + 0.5", last SWITCH if ($$r_params{function} eq 'atan');
477 $offset = " + 1", last SWITCH if ($$r_params{function} eq 'erf');
478 };
479 my @deltas = ();
480 my @deflist = ();
481 my $command = "## starting peak fit for " . $groups{$standard}->{label} . "\n";
482 $command .= "unguess\nerase \@group p___eak\n";
483 $command .= "set $standard.eshift = $standard.energy + " .
484 $groups{$standard}->{bkg_eshift} . "\n";
485 $groups{$standard} ->dispose("## clean up parameters from previous fit...", $dmode) if $$r_params{deltas};
486 foreach my $d (@{$$r_params{deltas}}) {
487 $groups{$standard} ->dispose("erase $d delta_$d\n", $dmode);
488 };
489 my $function = "p___eak.fun = 0";
490 ## $ymax is used for the vertical lines marking the fit range
491 my $suff = ($groups{$standard}->{bkg_flatten}) ? 'flat' : 'norm';
492 $groups{$standard} ->
493 dispose("set ___x = splint($standard.energy+$groups{$standard}->{bkg_eshift}, $standard.$suff, $$r_params{enot})", 1);
494 my $ymax = 2.5*Ifeffit::get_scalar("___x");
495 $$r_params{ymax} = $ymax;
496
497 ## save peak fitting parameters in data group
498 $groups{$standard} -> MAKE(peak=>1,
499 peak_enot=>$$r_params{enot},
500 peak_amp=>$$r_params{amp},
501 peak_width=>$$r_params{width},
502 peak_function=>$$r_params{function},
503 peak_function_choice=>$$r_params{function_choice},
504 peak_fit_e=>$$r_params{fit_e},
505 peak_fit_a=>$$r_params{fit_a},
506 peak_fit_w=>$$r_params{fit_w},
507 );
508 unless ($$r_params{function} eq 'none') {
509 my ($fite, $fita, $fitw);
510 #($fita, $toss, $fitw, $toss) = split(" ", $$r_params{fit_choice});
511 $fite = ($$r_params{fit_e}) ? "guess" : "set ";
512 $fita = ($$r_params{fit_a}) ? "guess" : "set ";
513 $fitw = ($$r_params{fit_w}) ? "guess" : "set ";
514 $command .= "$fite p___eak_e = $$r_params{enot}\n";
515 $command .= "$fita p___eak_amp = $$r_params{amp}\n";
516 $command .= "$fitw p___eak_width = $$r_params{width}\n";
517 $command .= "def p___eak.step = p___eak_amp * ($$r_params{function}(($standard.eshift - p___eak_e)/p___eak_width)$offset)\n";
518 $function = "def p___eak.fun = p___eak.step";
519 push @deltas, qw(p___eak_e p___eak_amp p___eak_width);
520 push @deflist, "p___eak.step", "p___eak.fun";
521 };
522 ## build the peak arrays, taking care not to leave any unused
523 ## variables lying around
524 foreach my $ipk (0 .. $#peaks) {
525 my $i = $ipk+1;
526 my $this = $$r_params{"f$i"};
527 next unless ($peaks[$i] and ($$r_params{"e$i"}));
528 my ($fite, $fita, $fitw, $toss);
529 #($fita, $toss, $fitw, $toss) = split(" ", $$r_params{"fit$i"});
530 $fite = ($$r_params{"fit_e$i"}) ? "guess" : "set ";
531 $fita = ($$r_params{"fit_a$i"}) ? "guess" : "set ";
532 $fitw = ($$r_params{"fit_w$i"}) ? "guess" : "set ";
533 $command .= "$fite p___eak_e$i = " . $$r_params{"e$i"} . "\n";
534 $command .= "$fita p___eak_a$i = " . $$r_params{"a$i"} . "\n";
535 $command .= "$fitw p___eak_w$i = " . $$r_params{"w$i"} . "\n";
536 push @deltas, "p___eak_e$i", "p___eak_a$i", "p___eak_w$i";
537 if ($this =~ /(gauss|loren|pvoight)/) { # peak function
538 $command .= "def p___eak.peak$i = p___eak_a$i * $this($standard.eshift, p___eak_e$i, p___eak_w$i)\n";
539 } else { # extra step function
540 my $ff = $$r_params{"f$i"};
541 my $offset = "";
542 SWITCH: {
543 $offset = "/pi + 0.5", last SWITCH if ($ff eq 'atan');
544 $offset = " + 1", last SWITCH if ($ff eq 'erf');
545 };
546 $command .= "def p___eak.peak$i = p___eak_a$i * ($ff(($standard.eshift - p___eak_e$i)/p___eak_w$i)$offset)\n";
547 };
548 ## add this peak to the fitting function
549 $function .= " + p___eak.peak$i";
550 push @deflist, "p___eak.peak$i";
551 ## save peak parameters to the data group
552 $groups{$standard} -> MAKE("peak_e$i"=>$$r_params{"e$i"}, "peak_a$i"=>$$r_params{"a$i"},
553 "peak_w$i"=>$$r_params{"w$i"}, "peak_f$i"=>$$r_params{"f$i"},
554 "peak_function$i"=>$$r_params{"function$i"},
555 "peak_fit$i"=>$$r_params{"fit$i"},
556 );
557 };
558
559 ## make the residual array and then minimize
560 $command .= $function . "\n";
561 if ($do_fit) {
562 $command .= "def p___eak.resid = $standard.$suff - p___eak.fun\n";
563 $command .= "minimize(p___eak.resid, x=$standard.eshift, xmin=$emin, xmax=$emax)\n";
564 push @deflist, "p___eak.resid";
565 };
566 $groups{$standard} -> dispose($command, $dmode);
567 $$r_params{deltas} = \@deltas;
568 $groups{$standard} -> dispose("## don't want to leave defs lying around...\n", $dmode);
569 foreach my $f (@deflist) {
570 $groups{$standard} -> dispose("set($f = $f)\n", $dmode);
571 };
572
573 ## store the results of the fit
574 foreach my $p (qw(amp width)) {
575 $widget{"peak_$p"} -> delete(qw(0 end));
576 $$r_params{$p} = sprintf("%.3f", Ifeffit::get_scalar("p___eak_$p"));
577 $widget{"peak_$p"} -> insert(0, $$r_params{$p});
578 };
579 foreach my $ipk (0 .. $#peaks) {
580 my $i = $ipk+1;
581 next unless ($peaks[$i] and ($$r_params{"e$i"}));
582 foreach my $p (qw(e a w)) {
583 $widget{"peak_$p$i"} -> delete(qw(0 end));
584 $$r_params{"$p$i"} = sprintf("%.3f", Ifeffit::get_scalar("p___eak_$p$i"));
585 $widget{"peak_$p$i"} -> insert(0, $$r_params{"$p$i"});
586 };
587 };
588 ## plot the result
589 $groups{$standard}->plotE('emn', $dmode, \%plot_features, \@indicator);
590 my $fitcolor = $config{plot}{c1};
591 $groups{$standard}->dispose("plot($standard.eshift, p___eak.fun, key=fit, color=$fitcolor, style=lines)", $dmode);
592 my $ic = 2;
593 if ($$r_params{plot_components}) {
594 unless ($widget{peak_function} eq 'None') {
595 my $color = $config{plot}{c2};
596 $groups{$standard}->dispose("plot($standard.eshift, p___eak.step, key=\"step\", style=lines, color=$color)", $dmode);
597 };
598 foreach my $ipk (0 .. $#peaks) {
599 my $i = $ipk+1;
600 next unless ($peaks[$i] and ($$r_params{"e$i"}));
601 ++$ic;
602 my $color = $config{plot}{'c'.$ic};
603 $groups{$standard}->dispose("plot($standard.eshift, p___eak.peak$i, key=\"peak $i\", style=lines, color=$color)", $dmode);
604 };
605 };
606 if ($$r_params{plot_difference}) {
607 ++$ic;
608 my @e = Ifeffit::get_array("$standard.eshift");
609 my @x = Ifeffit::get_array('p___eak.resid');
610 my ($emin, $emax) = ($$r_params{enot}+$$r_params{emin},$$r_params{enot}+$$r_params{emax});
611 foreach my $i (0 .. $#e) {
612 ($x[$i] = 0) if (($e[$i] < $emin) or ($e[$i] > $emax));
613 };
614 Ifeffit::put_array('p___eak.diff', \@x);
615 my $color = $config{plot}{'c'.$ic};
616 $groups{$standard}->dispose("plot($standard.eshift, p___eak.diff, key=\"difference\", style=lines, color=$color)", $dmode);
617 };
618 $groups{$standard}->plot_vertical_line($emin, 0, $ymax, $dmode, "fit range",
619 $groups{$standard}->{plot_yoffset});
620 $groups{$standard}->plot_vertical_line($emax, 0, $ymax, $dmode, "",
621 $groups{$standard}->{plot_yoffset});
622 $$r_params{mark_centroids} and peak_mark_centroids($standard,$r_params,\@peaks);
623 $last_plot='e';
624 peak_fill_results($standard, $r_params, $peak_results, @peaks) if ($do_fit);
625 $$r_params{peaks} = \@peaks;
626 $top->Unbusy;
627 Echo("Fitting near edge peak structure for \`$groups{$standard}->{label}\' ... done!");
628 };
629
630
631 sub peak_fill_results {
632 my ($standard, $r_params, $peak_results, @peaks) = @_;
633 $peak_results -> delete(qw(1.0 end));
634 $peak_results -> insert('end', "Results of near edge peak fit to \"$groups{$standard}->{label}\"\n\n", 'text');
635 $peak_results -> insert('end', "Fitting range = \[$$r_params{emin}:$$r_params{emax}\] (relative to centroid of step function)\n\n", 'text');
636
637 my $suff = ($groups{$standard}->{bkg_flatten}) ? 'flat' : 'norm';
638 my @e = Ifeffit::get_array("$standard.eshift");
639 my @r = Ifeffit::get_array('p___eak.resid');
640 my @x = Ifeffit::get_array("$standard.$suff");
641 my ($emin, $emax) = ($$r_params{enot}+$$r_params{emin},$$r_params{enot}+$$r_params{emax});
642 my ($rfactor, $sumsqr, $npts) = (0, 0, 0);
643 foreach my $i (0 .. $#e) {
644 if (($e[$i] > $emin) and ($e[$i] < $emax)) {
645 ++$npts;
646 $rfactor += $r[$i]**2;
647 $sumsqr += $x[$i]**2;
648 };
649 };
650 my $chisqr = Ifeffit::get_scalar("chi_square");
651 my $chinu = Ifeffit::get_scalar("chi_reduced");
652 my $nvarys = Ifeffit::get_scalar("n_varys");
653 $peak_results -> insert('end', "Fit included $npts data points and $nvarys variables\n");
654 $peak_results -> insert('end', sprintf("R-factor = %.5f, chi-square = %.5f, reduced chi-square = %.7f\n\n",
655 $rfactor/$sumsqr, $chisqr, $chinu), 'text');
656
657 if ($$r_params{function} eq 'none') {
658 $peak_results -> insert('end', "No step function was used\n", 'text');
659 $peak_results -> insert('end', " function centroid amplitude width\n", 'text');
660 } else {
661 $peak_results -> insert('end', " function centroid amplitude width\n", 'text');
662 $peak_results -> insert('end',
663 sprintf(" %-14s %8.2f(%8.2f) %6.3f(%6.3f) %6.3f(%6.3f)\n",
664 $$r_params{function_choice},
665 $$r_params{enot}, Ifeffit::get_scalar("delta_p___eak_e"),
666 $$r_params{amp}, Ifeffit::get_scalar("delta_p___eak_amp"),
667 $$r_params{width}, Ifeffit::get_scalar("delta_p___eak_width")),
668 'text');
669 };
670 foreach my $ipk (0 .. $#peaks) {
671 my $i = $ipk+1;
672 next unless ($peaks[$i] and ($$r_params{"e$i"}));
673 $peak_results -> insert('end',
674 sprintf(" %-14s %8.2f(%8.2f) %6.3f(%6.3f) %6.3f(%6.3f)\n",
675 $$r_params{"function$i"},
676 $$r_params{"e$i"}, Ifeffit::get_scalar("delta_p___eak_e$i"),
677 $$r_params{"a$i"}, Ifeffit::get_scalar("delta_p___eak_a$i"),
678 $$r_params{"w$i"}, Ifeffit::get_scalar("delta_p___eak_w$i")),
679 'text');
680 };
681 $peak_results -> insert('end', "\n\nThe Gaussians and Lorentzians are unit normalized,\nso the amplitudes are the areas.", 'text');
682 };
683
684
685 sub peak_fill_variables {
686 my ($standard, $r_params, $r_peaks) = @_;
687 $$r_params{enot} = $groups{$standard}->{peak_enot};
688 $$r_params{amp} = $groups{$standard}->{peak_amp};
689 $$r_params{width} = $groups{$standard}->{peak_width};
690 $$r_params{function} = $groups{$standard}->{peak_function};
691 $$r_params{function_choice} = $groups{$standard}->{peak_function_choice};
692 $$r_params{fit_e} = $groups{$standard}->{peak_fit_e}||0;
693 $$r_params{fit_a} = $groups{$standard}->{peak_fit_a}||1;
694 $$r_params{fit_w} = $groups{$standard}->{peak_fit_w}||1;
695
696 ## yipes! this counts the size of the dereferenced array
697 foreach my $ipk (0 .. $#{@$r_peaks}) {
698 my $i = $ipk+1;
699 next unless ($groups{$standard}->{"peak_e$i"});
700 $$r_params{"e$i"} = $groups{$standard}->{"peak_e$i"};
701 $$r_params{"a$i"} = $groups{$standard}->{"peak_a$i"} || 0.3;
702 $$r_params{"w$i"} = $groups{$standard}->{"peak_w$i"} || 1.0;
703 $$r_params{"f$i"} = $groups{$standard}->{"peak_f$i"} || 'none';
704 $$r_params{"function$i"} = $groups{$standard}->{"peak_function$i"} || 'none';
705 $$r_params{"fit_e$i"} = $groups{$standard}->{"peak_fit_e$i"};
706 $$r_params{"fit_a$i"} = $groups{$standard}->{"peak_fit_a$i"};
707 $$r_params{"fit_w$i"} = $groups{$standard}->{"peak_fit_w$i"};
708 ($$r_params{"e$i"} and ($$r_params{"function$i"} ne 'none')) and ($$r_peaks[$i] = 1);
709 };
710 };
711
712 sub peak_set_variable {
713 my ($k, $entry, $prop) = (shift, shift, shift);
714 ($entry =~ /^\s*$/) and ($entry = 0); # error checking ...
715 ($entry =~ /^\s*-$/) and return 1; # error checking ...
716 ($entry =~ /^\s*-?(\d+\.?\d*|\.\d+)\s*$/) or return 0;
717 };
718
719
720 sub peak_log {
721 my ($standard, $peak_results, $r_params, @peaks) = @_;
722 my $path = $current_data_dir || Cwd::cwd;
723 my $types = [['Log files', '.log'], ['All files', '*']];
724 my $initial = $groups{$standard}->{label}."_peak.log";
725 ($initial =~ s/[\\:\/\*\?\'<>\|]/_/g);# if ($is_windows);
726 my $file = $top ->
727 getSaveFile(-filetypes=>$types,
728 #(not $is_windows) ?
729 # (-sortcmd=>sub{$Tk::FBox::a cmp $Tk::FBox::b}) : () ,
730 -initialdir=>$path,
731 -initialfile=>$initial,
732 -title => "Athena: Save peak fit log file");
733 return unless $file;
734 my ($name, $pth, $suffix) = fileparse($file);
735 $current_data_dir = $pth;
736 #&push_mru($file, 0);
737 Echo("Saving log file from peak fit to \"$standard\" ...");
738
739 my $command = q{};
740 my $i = 0;
741 foreach my $line (split(/\n/, $peak_results->get(qw(1.0 end)))) {
742 ++$i;
743 if ($line) {
744 $command .= "set \$peak_title_$i = \"$line\"\n";
745 } else {
746 $command .= "set \$peak_title_$i = \". \"\n";
747 };
748 if ($line =~ /^Results/) {
749 ++$i;
750 $command .= "set \$peak_title_$i = \"Titles from $groups{$standard}->{label}\"\n";
751 foreach (@{$groups{$standard}->{titles}}) {
752 ++$i;
753 $command .= "set \$peak_title_$i = \" . $_\"\n";
754 };
755 } elsif ($line =~ /^\s*function/) {
756 ++$i;
757 $command .= "set \$peak_title_$i = \"" . "=" x 60 . "\"\n";
758 };
759 };
760
761
762 ++$i;
763 $command .= "set \$peak_title_$i = \"Formulas:\"\n";
764 ++$i;
765 $command .= "set \$peak_title_$i = \"- arctangent: A*[atan((e-E0)/W)/pi + 0.5]\"\n";
766 ++$i;
767 $command .= "set \$peak_title_$i = \"- error function: A*[erf((e-E0)/W) + 1]\"\n";
768 ++$i;
769 $command .= "set \$peak_title_$i = \"- Gaussian: [A/(W*sqrt(2pi))] * exp[-(e-E0)^2/(2W^2)]\"\n";
770 ++$i;
771 $command .= "set \$peak_title_$i = \"- Lorentzian: (AW/2pi) / [(e-E0)^2 + (W/2)^2]\"\n";
772
773 $command .= sprintf("set %s.ee = %s.energy + %f\n", $standard, $standard, $groups{$standard}->{bkg_eshift});
774
775 my $peakstring = q{};
776 my $ic = 0;
777 foreach my $ipk (0 .. $#peaks) {
778 my $i = $ipk+1;
779 next unless ($peaks[$i] and ($$r_params{"e$i"}));
780 ++$ic;
781 $peakstring .= ", p___eak.peak$ic";
782 };
783 my $suff = ($groups{$standard}->{bkg_flaten}) ? 'flat' : 'norm';
784 $command .= "write_data(file=\"$file\", \$peak_title_\*, $standard.ee, $standard.$suff, p___eak.fun, p___eak.step$peakstring, p___eak.resid)\n";
785
786 $groups{$standard}->dispose($command, $dmode);
787
788 my $postcmd = q{};
789 foreach my $j (1 .. $i) {
790 $postcmd .= "erase \$peak_title_$j\n";
791 };
792 $groups{$standard}->dispose($postcmd, $dmode);
793
794 Echo("Saving log file from peak fit to \"$groups{$standard}->{label}\" ... done!");
795 }
796
797
798 sub peak_mark_centroids {
799 my ($standard, $r_params, $r_peaks) = @_;
800 $$r_params{toplevel} -> Busy(-recurse=>1);
801 my @list;
802 push @list, $$r_params{enot} unless ($$r_params{function_choice} eq 'none');
803 foreach my $ipk (0 .. $#{@$r_peaks}) {
804 my $i = $ipk+1;
805 push @list, $$r_params{"e$i"} if $$r_params{"e$i"};
806 };
807
808 my $string = "$config{plot}{marker}, $config{plot}{markercolor}, $groups{$standard}->{plot_yoffset}";
809 my $command = "";
810 foreach my $e (@list) {
811 $command .= "pmarker \"$standard.energy+$groups{$standard}->{bkg_eshift}\", " .
812 "p___eak.fun, $e, $string\n";
813 };
814 $groups{$standard} -> dispose($command, $dmode);
815 $$r_params{toplevel} -> Unbusy
816 };
817
818
819
820
821 ## END OF PEAK FITTING SUBSECTION
822 ##########################################################################################