Debian Codegraph @

athena_parts/lcf.pl

raw
1 ## -*- cperl -*-
2 ##
3 ## This file is part of Athena, copyright (c) 2001-2009 Bruce Ravel
4 ##
5 ## This file implements linear combination XANES fitting in Athena
6
7 sub lcf {
8
9 ## generally, we do not change modes unless there is data.
10 ## exceptions include things like the prefernces and key bindings,
11 ## which are data-independent
12 Echo("No data!"), return unless $current;
13 Echo("No data!"), return if ($current eq "Default Parameters");
14
15 ## this is a way of testing the current list of data groups for some
16 ## necessary property. for the demo, this will just be the list of
17 ## groups
18 my @keys = ('None');
19 foreach my $k (&sorted_group_list) {
20 ($groups{$k}->{is_xmu} or $groups{$k}->{is_chi}) and push @keys, $k;
21 };
22 Echo("You need two or more xmu groups to do linear combination fitting"), return unless ($#keys >= 2);
23
24 $values_menubutton -> menu -> entryconfigure(17, -state=>'disabled'); # purge lcf
25 $right_values -> menu -> entryconfigure(17, -state=>'disabled'); # purge lcf
26 my %lcf_params = (unknown => $current,
27 fitspace => $groups{$current}->{lcf_fitspace} || $config{linearcombo}{fitspace},
28 components => $config{linearcombo}{components},
29 difference => 0,
30 fitmin_e => $groups{$current}->{lcf_fitmin_e} || $config{linearcombo}{fitmin},
31 fitmax_e => $groups{$current}->{lcf_fitmax_e} || $config{linearcombo}{fitmax},
32 fitmin_k => $groups{$current}->{lcf_fitmin_k} || $config{linearcombo}{fitmin_k},
33 fitmax_k => $groups{$current}->{lcf_fitmax_k} || $config{linearcombo}{fitmax_k},
34 enot => $groups{$current}->{bkg_e0},
35 linear => $groups{$current}->{lcf_linear} || 0,
36 nonneg => $groups{$current}->{lcf_nonneg} || 1,
37 100 => $groups{$current}->{lcf_100} || 1,
38 e0all => $groups{$current}->{lcf_e0all} || 0,
39 yint => 0,
40 slope => 0,
41 noise => 0,
42 deflist => [],
43 toggle => 0,
44 maxstan => 4,
45 iterator => "",
46 sumsqr => 0,
47 kw => $plot_features{kw} || 1,
48 #kw => $groups{$current}->{fft_kw} || 1,
49 keys => \@keys,
50 );
51 if ($lcf_params{fitspace} eq 'k') {
52 $lcf_params{fitmin} = $lcf_params{fitmin_k};
53 $lcf_params{fitmax} = $lcf_params{fitmax_k};
54 } else {
55 $lcf_params{fitmin} = $lcf_params{fitmin_e};
56 $lcf_params{fitmax} = $lcf_params{fitmax_e};
57 };
58 ($lcf_params{fitspace} = 'k') if $groups{$current}->{is_chi};
59
60 my $ps = $project_saved;
61 my @save = ($plot_features{emin}, $plot_features{emax});
62 $plot_features{emin} = $config{linearcombo}{emin};
63 $plot_features{emax} = $config{linearcombo}{emax};
64 project_state($ps); # don't toggle if currently saved
65
66 ## these two global variables must be set before this view is displayed
67 $fat_showing = 'lcf';
68 $hash_pointer = \%lcf_params;
69
70 ## disable many menus.
71 map {$_ -> configure(-state=>'disabled')}
72 ($data_menu, $merge_menu, $anal_menu, $settings_menu);
73
74 ## this removes the currently displayed view without destroying its
75 ## contents
76 $fat -> packForget;
77
78 ## define the parent Frame for this analysis chore and pack it in
79 ## the correct location
80 my $lcf = $container->Frame(@fatgeom, -relief=>'sunken', -borderwidth=>3)
81 -> pack(-fill=>'both', -expand=>1);
82 #$lcf -> packPropagate(0);
83 ## global variable identifying which Frame is showing
84 $which_showing = $lcf;
85
86 $lcf -> Label(-text=>"Linear combination fitting",
87 -font=>$config{fonts}{large},
88 -foreground=>$config{colors}{activehighlightcolor})
89 -> pack(-side=>'top', -fill=>'x', -anchor=>'w');
90
91 my $frame = $lcf -> Frame(-borderwidth=>2, -relief=>'flat')
92 -> pack(-side=>'top', -fill=>'x');
93 $frame -> Label(-text=>"Unknown: ",
94 -foreground=>$config{colors}{activehighlightcolor},
95 )
96 -> pack(-side=>'left');
97
98 $widget{lcf_unknown} = $frame -> Label(-text=>$groups{$current}->{label},
99 -foreground=>$config{colors}{button})
100 -> pack(-side=>'left');
101
102
103 $frame = $lcf -> Frame(-borderwidth=>2, -relief=>'flat')
104 -> pack(-side=>'top', -fill=>'x',);
105 $frame -> Label(-text=>"Fitting range: ",
106 -foreground=>$config{colors}{activehighlightcolor},
107 )
108 -> pack(-side=>'left', -anchor=>'n');
109 $widget{lcf_fitmin} = $frame -> Entry(-width=>6,
110 -validate=>'none',
111 -validatecommand=>[\&lcf_set_variable, 'lcf_fitmin'],
112 ##-textvariable=>\$lcf_params{fitmin},
113 )
114 -> pack(-side=>'left', -anchor=>'n');
115 $grab{lcf_fitmin} = $frame -> Button(@pluck_button, @pluck,
116 -command=>sub{lcf_pluck(\%lcf_params, 'fitmin');
117 lcf_quickplot(\%lcf_params); })
118 -> pack(-side=>'left', -pady=>2, -anchor=>'n');
119 $frame -> Label(-text=>' to ',
120 -foreground=>$config{colors}{activehighlightcolor})
121 -> pack(-side=>'left', -anchor=>'n');
122 $widget{lcf_fitmax} = $frame -> Entry(-width=>6,
123 -validate=>'none',
124 -validatecommand=>[\&lcf_set_variable, 'lcf_fitmax'],
125 ##-textvariable=>\$lcf_params{fitmax},
126 )
127 -> pack(-side=>'left', -anchor=>'n');
128 $grab{lcf_fitmax} = $frame -> Button(@pluck_button, @pluck,
129 -command=>sub{lcf_pluck(\%lcf_params, 'fitmax');
130 lcf_quickplot(\%lcf_params); })
131 -> pack(-side=>'left', -pady=>2, -anchor=>'n');
132 $widget{lcf_components} = $frame
133 -> Checkbutton(-text=>'Plot components?',
134 -selectcolor=>$config{colors}{single},
135 -width=>15,
136 -anchor=>'w',
137 -variable=>\$lcf_params{components})
138 -> pack(-side=>'right', -anchor=>'w');
139
140 $frame = $lcf -> Frame(-borderwidth=>2, -relief=>'flat')
141 -> pack(-side=>'top', -fill=>'x');
142 $frame -> Label(-text=>"Fitting space: ",
143 -foreground=>$config{colors}{activehighlightcolor},
144 )
145 -> pack(-side=>'left', -anchor=>'n');
146 $frame -> Radiobutton(-text=>'norm(E)',
147 -selectcolor=>$config{colors}{single},
148 -value=>'e',
149 -variable=>\$lcf_params{fitspace},
150 -command=>sub{
151 $lcf_params{fitmin_e} = $groups{$current}->{lcf_fitmin_e} || $config{linearcombo}{fitmin};
152 $lcf_params{fitmax_e} = $groups{$current}->{lcf_fitmax_e} || $config{linearcombo}{fitmax};
153 $groups{$current}->MAKE(lcf_fitspace => $lcf_params{fitspace},
154 lcf_fitmin => $lcf_params{fitmin_e},
155 lcf_fitmax => $lcf_params{fitmax_e});
156 foreach (qw(fitmin fitmax)) {
157 $lcf_params{$_} = $lcf_params{$_."_e"};
158 $widget{"lcf_$_"} -> configure(-validate=>'none');
159 $widget{"lcf_$_"} -> delete(0, 'end');
160 $widget{"lcf_$_"} -> insert('end', $lcf_params{$_});
161 $widget{"lcf_$_"} -> configure(-validate=>'key');
162 };
163 foreach my $i (1 .. $config{linearcombo}{maxspectra}) {
164 $widget{"lcf_e0val$i"} -> configure(-state=>'normal');
165 $widget{"lcf_e0$i"} -> configure(-state=>'normal');
166 };
167 $widget{lcf_linear} -> configure(-state=>'normal');
168 $widget{lcf_e0all} -> configure(-state=>'normal');
169 $widget{lcf_operations} -> entryconfigure(7, -state=>'disabled', -style=>$lcf_params{disabled_style});
170 lcf_reset(\%lcf_params,1);
171 lcf_quickplot_e(\%lcf_params);
172 })
173 -> pack(-side=>'left', -anchor=>'n');
174 $frame -> Radiobutton(-text=>'deriv(E)',
175 -selectcolor=>$config{colors}{single},
176 -value=>'d',
177 -variable=>\$lcf_params{fitspace},
178 -command=>sub{
179 $lcf_params{fitmin_e} = $groups{$current}->{lcf_fitmin_e} || $config{linearcombo}{fitmin};
180 $lcf_params{fitmax_e} = $groups{$current}->{lcf_fitmax_e} || $config{linearcombo}{fitmax};
181 $groups{$current}->MAKE(lcf_fitspace => $lcf_params{fitspace},
182 lcf_fitmin => $lcf_params{fitmin_e},
183 lcf_fitmax => $lcf_params{fitmax_e});
184 foreach (qw(fitmin fitmax)) {
185 $lcf_params{$_} = $lcf_params{$_."_e"};
186 $widget{"lcf_$_"} -> configure(-validate=>'none');
187 $widget{"lcf_$_"} -> delete(0, 'end');
188 $widget{"lcf_$_"} -> insert('end', $lcf_params{$_});
189 $widget{"lcf_$_"} -> configure(-validate=>'key');
190 };
191 foreach my $i (1 .. $config{linearcombo}{maxspectra}) {
192 $widget{"lcf_e0val$i"} -> configure(-state=>'normal');
193 $widget{"lcf_e0$i"} -> configure(-state=>'normal');
194 };
195 $widget{lcf_linear} -> configure(-state=>'disabled');
196 $widget{lcf_e0all} -> configure(-state=>'normal');
197 $widget{lcf_operations} -> entryconfigure(7, -state=>'disabled', -style=>$lcf_params{disabled_style});
198 lcf_reset(\%lcf_params,1);
199 lcf_quickplot_e(\%lcf_params);
200 })
201 -> pack(-side=>'left', -anchor=>'n');
202 $frame -> Radiobutton(-text=>'chi(k)',
203 -selectcolor=>$config{colors}{single},
204 -value=>'k',
205 -variable=>\$lcf_params{fitspace},
206 -command=>sub{
207 $lcf_params{fitmin_k} = $groups{$current}->{lcf_fitmin_k} || $config{linearcombo}{fitmin_k};
208 $lcf_params{fitmax_k} = $groups{$current}->{lcf_fitmax_k} || $config{linearcombo}{fitmax_k};
209 $groups{$current}->MAKE(lcf_fitspace => $lcf_params{fitspace},
210 lcf_fitmin => $lcf_params{fitmin_k},
211 lcf_fitmax => $lcf_params{fitmax_k});
212 foreach (qw(fitmin fitmax)) {
213 $lcf_params{$_} = $lcf_params{$_."_k"};
214 $widget{"lcf_$_"} -> configure(-validate=>'none');
215 $widget{"lcf_$_"} -> delete(0, 'end');
216 $widget{"lcf_$_"} -> insert('end', $lcf_params{$_});
217 $widget{"lcf_$_"} -> configure(-validate=>'key');
218 };
219 foreach my $i (1 .. $config{linearcombo}{maxspectra}) {
220 $widget{"lcf_e0val$i"} -> configure(-state=>'disabled');
221 $widget{"lcf_e0$i"} -> configure(-state=>'disabled');
222 };
223 $widget{lcf_linear} -> configure(-state=>'disabled');
224 $widget{lcf_e0all} -> configure(-state=>'disabled');
225 $widget{lcf_operations} -> entryconfigure(7, -state=>'normal', -style=>$lcf_params{normal_style});
226 lcf_reset(\%lcf_params,1);
227 lcf_quickplot_k(\%lcf_params);
228 })
229 -> pack(-side=>'left', -anchor=>'n');
230
231 $widget{lcf_difference} = $frame
232 -> Checkbutton(-text=>'Plot difference?',
233 -selectcolor=>$config{colors}{single},
234 -width=>15,
235 -anchor=>'w',
236 -variable=>\$lcf_params{difference})
237 -> pack(-side=>'right', -anchor=>'w');
238
239
240
241
242
243 ## this is a spacer frame which pushes all the widgets to the top
244 ## $lcf -> Frame(-background=>$config{colors}{darkbackground})
245 ## -> pack(-side=>'bottom', -expand=>1, -fill=>'both');
246
247 ## at the bottom of the frame, there are full width buttons for
248 ## returning to the main view and for going to the appropriate
249 ## document section
250 $lcf -> Button(-text=>'Return to the main window', @button_list,
251 -background=>$config{colors}{background2},
252 -activebackground=>$config{colors}{activebackground2},
253 -command=>sub{$groups{$current}->dispose("unguess\n", $dmode);
254 $values_menubutton -> menu -> entryconfigure(17, -state=>'normal'); # purge lcf
255 $right_values -> menu -> entryconfigure(17, -state=>'normal');
256 #$groups{$current}->dispose("erase \@group l___cf\n");
257 &reset_window($lcf, "linear combination fitting", \@save);
258 })
259 -> pack(-side=>'bottom', -fill=>'x');
260 ## help button
261 $lcf -> Button(-text=>'Document section: Linear combination fitting',
262 @button_list,
263 -command=>sub{pod_display("analysis::lcf.pod")})
264 -> pack(-side=>'bottom', -fill=>'x', -pady=>4);
265
266
267 my $notebook = $lcf ->NoteBook(-background=>$config{colors}{background},
268 -backpagecolor=>$config{colors}{background},
269 -inactivebackground=>$config{colors}{inactivebackground},
270 #-foreground=>$config{colors}{activehighlightcolor},
271 -font=>$config{fonts}{small},
272 )
273 -> pack(-side=>'top', -fill =>'both', -expand=>1, -padx=>4, -pady=>4);
274 $widget{lcf_notebook} = $notebook;
275
276 my ($buttonframe, $st, $re, $co);
277 $st = $notebook -> add('standards',
278 -label=>'Standards spectra',
279 -anchor=>'center',
280 #-raisecmd=>sub{$buttonframe->pack(-in=>$st)}
281 );
282 $re = $notebook -> add('results',
283 -label=>'Fit results',
284 -anchor=>'center',
285 #-raisecmd=>sub{$buttonframe->pack(-in=>$re)}
286 );
287 $co = $notebook -> add('combinatorics',
288 -label=>'Combinatorics',
289 -anchor=>'center',
290 -state=>'disabled',
291 #-raisecmd=>sub{$buttonframe->packForget}
292 );
293 $widget{lcf_notebook} -> pageconfigure('combinatorics', -state=>'normal')
294 if (exists $lcf_data{$current});
295
296
297 my $outerframe = $st -> Frame()
298 -> pack(-side=>'bottom', -fill=>'both', -expand=>1, -padx=>2, -pady=>0, -anchor=>'s');
299
300 ## frame with control buttons
301 $buttonframe = $outerframe -> LabFrame(-label=>'Operations',
302 -foreground=>$config{colors}{activehighlightcolor},
303 -labelside=>'acrosstop',)
304 -> pack(-side=>'right', -fill=>'both', -expand=>1, -padx=>2, -pady=>4, -anchor=>'s');
305 $widget{lcf_operations} = $buttonframe ->Scrolled('HList',
306 -scrollbars => 'oe',
307 -background => $config{colors}{background},
308 -selectmode => 'single',
309 -selectbackground => $config{colors}{activebackground},
310 -highlightcolor => $config{colors}{background},
311 -browsecmd => sub{lcf_multiplexer(\%lcf_params)},
312 )
313 -> pack(-fill=>'both', -expand=>1);
314 $widget{lcf_operations} -> Subwidget("yscrollbar")
315 -> configure(-background=>$config{colors}{background},
316 ($is_windows) ? () : (-width=>8));
317 BindMouseWheel($widget{lcf_operations});
318 my $t = $buttonframe->Subwidget("label");
319 my @bold = (-foreground => $config{colors}{marked},);
320 my @normal = (-foreground => $config{colors}{activehighlightcolor},);
321
322 $t -> bind("<Any-Enter>", sub {shift->configure(@bold)});
323 $t -> bind("<Any-Leave>", sub {shift->configure(@normal)});
324 $t -> bind('<ButtonPress-1>' => sub{Echo("Clicking on an entries in the operations list will perform the function described.")});
325
326
327 $lcf_params{normal_style} = $widget{lcf_operations} -> ItemStyle('text',
328 -font=>$config{fonts}{small},
329 -anchor=>'w',
330 -foreground=>$config{colors}{foreground});
331 $lcf_params{disabled_style} = $widget{lcf_operations} -> ItemStyle('text',
332 -font=>$config{fonts}{small},
333 -anchor=>'w',
334 -foreground=>$config{colors}{disabledforeground});
335
336
337 $widget{lcf_operations} -> add(1,
338 -itemtype =>'text',
339 -text =>'Fit this group',
340 -state => 'disabled',
341 -style => $lcf_params{disabled_style},
342 );
343 $widget{lcf_operations} -> add(2,
344 -itemtype =>'text',
345 -text =>'Fit all combinations',
346 -state => 'disabled',
347 -style => $lcf_params{disabled_style},
348 );
349 $widget{lcf_operations} -> add(3,
350 -itemtype =>'text',
351 -text =>'Fit marked groups',
352 -state => 'disabled',
353 -style => $lcf_params{disabled_style},
354 );
355 $widget{lcf_operations} -> add(4,
356 -itemtype =>'text',
357 -text =>'Write a report',
358 -state => 'disabled',
359 -style => $lcf_params{disabled_style},
360 );
361 $widget{lcf_operations} -> add(5,
362 -itemtype =>'text',
363 -text =>'Marked fits report',
364 -state => 'disabled',
365 -style => $lcf_params{disabled_style},
366 );
367 $widget{lcf_operations} -> add(6,
368 -itemtype =>'text',
369 -text =>'Plot data + sum',
370 -state => 'disabled',
371 -style => $lcf_params{disabled_style},
372 );
373 $widget{lcf_operations} -> add(7,
374 -itemtype =>'text',
375 -text =>'Plot data + sum in R',
376 -state => 'disabled',
377 -style => $lcf_params{disabled_style},
378 );
379 $widget{lcf_operations} -> add(8,
380 -itemtype =>'text',
381 -text =>'Make fit group',
382 -state => 'disabled',
383 -style => $lcf_params{disabled_style},
384 );
385 $widget{lcf_operations} -> add(9,
386 -itemtype =>'text',
387 -text =>'Make difference group',
388 -state => 'disabled',
389 -style => $lcf_params{disabled_style},
390 );
391 $widget{lcf_operations} -> add(10,
392 -itemtype =>'text',
393 -text =>'Set params, all groups',
394 -state => 'normal',
395 -style => $lcf_params{normal_style},
396 );
397 $widget{lcf_operations} -> add(11,
398 -itemtype =>'text',
399 -text =>'Set params, marked groups',
400 -state => 'normal',
401 -style => $lcf_params{normal_style},
402 );
403 $widget{lcf_operations} -> add(12,
404 -itemtype =>'text',
405 -text =>'Reset',
406 -state => 'normal',
407 -style => $lcf_params{normal_style},
408 );
409
410
411 $frame = $buttonframe -> Frame(-borderwidth=>2, -relief=>'flat')
412 -> pack(-side=>'top', -fill=>'x', -padx=>0);
413
414
415
416
417 ## frame with options
418 $frame = $outerframe -> LabFrame(-label=>'Options',
419 -foreground=>$config{colors}{activehighlightcolor},
420 -labelside=>'acrosstop',)
421 -> pack(-side=>'left', -fill=>'x', -expand=>1, -padx=>2, -pady=>4, -anchor=>'s');
422
423 $widget{lcf_linear} = $frame -> Checkbutton(-text=>'Add a linear term after e0',
424 -selectcolor=>$config{colors}{single},
425 -variable=>\$lcf_params{linear})
426 -> pack(-side=>'top', -padx=>2, -anchor=>'w');
427 $widget{lcf_nonneg} = $frame -> Checkbutton(-text=>'Weights between 0 & 1',
428 -selectcolor=>$config{colors}{single},
429 -variable=>\$lcf_params{nonneg})
430 -> pack(-side=>'top', -padx=>2, -anchor=>'w');
431
432 $widget{lcf_100} = $frame -> Checkbutton(-text=>'Force weights to sum to 1',
433 -selectcolor=>$config{colors}{single},
434 -variable=>\$lcf_params{100})
435 -> pack(-side=>'top', -padx=>2, -anchor=>'w');
436 $widget{lcf_e0all} = $frame -> Checkbutton(-text=>'All standards use same e0',
437 -selectcolor=>$config{colors}{single},
438 -variable=>\$lcf_params{e0all},
439 -command=>sub{
440 foreach my $i (1 .. $config{linearcombo}{maxspectra}) {
441 if ($lcf_params{e0all}) {
442 $widget{"lcf_e0$i"} -> select;
443 $widget{"lcf_e0$i"} -> configure(-state=>'disabled');
444 } else {
445 $widget{"lcf_e0$i"} -> configure(-state=>'normal');
446 };
447 };
448 })
449 -> pack(-side=>'top', -padx=>2, -anchor=>'w');
450
451 $frame -> Button(-text=>'Use marked groups',
452 @button_list,
453 -borderwidth=>1,
454 -command=>[\&lcf_use_marked, \%lcf_params])
455 -> pack(-side=>'top', -fill=>'x', -padx=>2, -anchor=>'w');
456
457 my $ff = $frame -> Frame()
458 -> pack(-side=>'top', -padx=>2, -anchor=>'w');
459 $ff -> Label(-text=>"Add noise")
460 -> pack(-side=>'left', -padx=>2);
461 $widget{lcf_noise} = $ff -> Entry(-width => 7,
462 -textvariable => \$lcf_params{noise},
463 -validate => 'none',
464 -validatecommand => [\&set_variable, 'lcf_noise']
465 )
466 -> pack(-side=>'left');
467 $ff -> Label(-text=>" to data")
468 -> pack(-side=>'left', -padx=>2);
469
470 $ff = $frame -> Frame()
471 -> pack(-side=>'top', -padx=>2, -anchor=>'w');
472 $ff -> Label(-text=>"Use at most")
473 -> pack(-side=>'left', -padx=>2);
474 $widget{lcf_maxstan} = $ff -> NumEntry(-orient => 'horizontal',
475 -minvalue => 2,
476 -maxvalue => $config{linearcombo}{maxspectra},
477 -textvariable => \$lcf_params{maxstan},
478 -width=>3)
479 -> pack(-side=>'left');
480 $ff -> Label(-text=>" standards")
481 -> pack(-side=>'left', -padx=>2);
482
483 $widget{lcf_maxfit} = $frame -> Label(-font=>$config{fonts}{smbold},
484 -foreground=>$config{colors}{activehighlightcolor})
485 -> pack(-side=>'top', -padx=>2, -anchor=>'center', -fill=>'x');
486
487
488
489
490 ## frame containing the grid of widgets for selecting the
491 ## standards spectra
492 $frame = $st -> Scrolled('HList',
493 -scrollbars => 'oe',
494 -header => 1,
495 -columns => 6,
496 -borderwidth => 0,
497 -relief => 'flat',
498 -highlightcolor => $config{colors}{background},)
499 -> pack(-side=>'top', -fill =>'both', -padx=>4, -pady=>4);
500 BindMouseWheel($frame);
501 #($frame->children)[2] -> configure(-highlightcolor=>$config{colors}{background});
502 #foreach (($frame->children)[2]->configure) {no warnings; no strict; print join(" ", @$_), $/};
503 $frame -> Subwidget("yscrollbar")
504 -> configure(-background=>$config{colors}{background},
505 ($is_windows) ? () : (-width=>8));
506
507 my $style = $frame -> ItemStyle('text',
508 -font=>$config{fonts}{small},
509 -anchor=>'w',
510 -foreground=>$config{colors}{activehighlightcolor});
511 $frame -> headerCreate(0,
512 -text=>" ",
513 -style=>$style,
514 -headerbackground=>$config{colors}{background},
515 -borderwidth => 1,);
516 $frame -> headerCreate(1,
517 -text=>"Standards",
518 -style=>$style,
519 -headerbackground=>$config{colors}{background},
520 -borderwidth => 1,);
521 $frame -> headerCreate(2,
522 -text=>"weight",
523 -style=>$style,
524 -headerbackground=>$config{colors}{background},
525 -borderwidth => 1,);
526 $frame -> headerCreate(3,
527 -text=>"e0",
528 -style=>$style,
529 -headerbackground=>$config{colors}{background},
530 -borderwidth => 1,);
531 $frame -> headerCreate(4,
532 -text=>"fit?",
533 -style=>$style,
534 -headerbackground=>$config{colors}{background},
535 -borderwidth => 1,);
536 $frame -> headerCreate(5,
537 -text=>"req.",
538 -style=>$style,
539 -headerbackground=>$config{colors}{background},
540 -borderwidth => 1,);
541
542
543
544 $lcf_params{req} = $groups{$current}->{"lcf_req"} || q{};
545 foreach my $i (1 .. $config{linearcombo}{maxspectra}) {
546 $lcf_params{"standard$i"} = $groups{$current}->{"lcf_standard$i"} || 'None';
547 $lcf_params{"e0$i"} = $groups{$current}->{"lcf_e0$i"} || $config{linearcombo}{fite0};
548 $lcf_params{"e0val$i"} = $groups{$current}->{"lcf_e0val$i"} || 0;
549 $lcf_params{"value$i"} = $groups{$current}->{"lcf_value$i"} || 0;
550
551
552 $frame -> add($i);
553 $frame -> itemCreate($i, 0, -itemtype=>'text', -text=>$i, -style=>$style);
554 $widget{"lcf_standard_list$i"} = $frame -> BrowseEntry(-variable => \$lcf_params{"standard_lab$i"},
555 @browseentry_list,
556 -width=>18,
557 -browsecmd => sub {
558 my $text = $_[1];
559 my $this = $1 if ($text =~ /^(\d+):/);
560 Echo("Failed to match in browsecmd. Yikes! Complain to Bruce."), return unless ($this or ($this eq '0'));
561 #$this -= 1;
562 $lcf_params{"standard$i"}=$lcf_params{keys}->[$this];
563 $groups{$current} -> MAKE("lcf_standard$i" => $lcf_params{keys}->[$this],
564 "lcf_standard_lab$i" => $lcf_params{"standard_lab$i"});
565 if ($this == 0) { # select None
566 $lcf_params{"standard$i"} = "None";
567 $lcf_params{"standard_lab$i"} = "0: None";
568 $lcf_params{"value$i"} = 0;
569 $lcf_params{"e0$i"} = 0;
570 $lcf_params{"e0val$i"} = 0;
571 $lcf_params{"delta_value$i"} = 0;
572 $lcf_params{"delta_e0val$i"} = 0;
573 $groups{$current} -> MAKE("lcf_value$i" => 0,
574 "lcf_e0$i" => 0,
575 "lcf_e0val$i" => 0,
576 "lcf_delta_value$i" => 0,
577 "lcf_delta_e0val$i" => 0,
578 );
579 };
580 &lcf_initialize(\%lcf_params, 2);
581 });
582 $widget{"lcf_standard_list$i"} -> insert("end", "0: None");
583 my $j = 1;
584 foreach my $s (@keys) {
585 next if ($s eq 'None');
586 $groups{$s}->MAKE(lcf_menu_label => "$j: $groups{$s}->{label}");
587 $widget{"lcf_standard_list$i"} -> insert("end", "$j: $groups{$s}->{label}");
588 ++$j;
589 };
590 ## make sure menu labels are up to date
591 my $label = "";
592 ($label = $groups{$groups{$current}->{"lcf_standard$i"}}->{lcf_menu_label})
593 if (exists $groups{$current}->{"lcf_standard$i"});
594 $lcf_params{"standard_lab$i"} = $label || '0: None';
595
596
597
598
599 $frame -> itemCreate($i, 1, -itemtype=>'window', -widget=>$widget{"lcf_standard_list$i"});
600 my $en = $frame -> Entry(-width=>6,
601 -textvariable=>\$lcf_params{"value$i"});
602 $frame -> itemCreate($i, 2, -itemtype=>'window', -widget=>$en);
603 $widget{"lcf_e0val$i"} = $frame -> Entry(-width=>6,
604 #-state=>($lcf_params{"e0$i"}) ? 'normal' : 'disabled',
605 -textvariable=>\$lcf_params{"e0val$i"});
606 $frame -> itemCreate($i, 3, -itemtype=>'window', -widget=>$widget{"lcf_e0val$i"});
607 $widget{"lcf_e0$i"} = $frame -> Checkbutton(-variable=>\$lcf_params{"e0$i"},
608 -selectcolor=>$config{colors}{single},
609 #-command=>sub{$widget{"lcf_e0val$i"}->configure(-state=>($lcf_params{"e0$i"})?'normal':'disabled')},
610 );
611 $frame -> itemCreate($i, 4, -itemtype=>'window', -widget=>$widget{"lcf_e0$i"});
612 $widget{"lcf_req$i"} = $frame -> Radiobutton(-variable=>\$lcf_params{req},
613 -value=>$i,
614 -selectcolor=>$config{colors}{single},
615 #-command=>sub{$widget{"lcf_e0val$i"}->configure(-state=>($lcf_params{"e0$i"})?'normal':'disabled')},
616 );
617 $frame -> itemCreate($i, 5, -itemtype=>'window', -widget=>$widget{"lcf_req$i"});
618 };
619
620
621
622
623
624
625 ## a place to write information after the fit is finished
626 $frame = $re -> Frame()
627 -> pack(-side=>'top', -fill=>'both', -padx=>4, -expand=>1);
628
629 $widget{lcf_text} = $frame -> Scrolled("ROText", -scrollbars=>'osoe',
630 -wrap=>'none',
631 -height=>1,
632 -width=>40,
633 -font=>$config{fonts}{fixed})
634 -> pack(-fill=>'both', -expand=>1);
635 disable_mouse3($widget{lcf_text}->Subwidget('rotext'));
636 $widget{lcf_text} -> Subwidget("xscrollbar")->configure(-background=>$config{colors}{background},
637 ($is_windows) ? () : (-width=>8));
638 $widget{lcf_text} -> Subwidget("yscrollbar")->configure(-background=>$config{colors}{background},
639 ($is_windows) ? () : (-width=>8));
640 $widget{lcf_text} -> tagConfigure("text", -font=>$config{fonts}{fixedsm});
641 my $smbold = $config{fonts}{smbold};
642 my $red = $config{colors}{single};
643 $widget{lcf_text} -> tagConfigure('error',
644 -lmargin1 => 4,
645 -font => $smbold,
646 -foreground => $red,
647 -background => 'white');
648
649 $frame = $buttonframe -> Frame(-borderwidth=>2, -relief=>'flat')
650 -> pack(-side=>'top', -fill=>'x', -padx=>0);
651
652
653
654
655
656 ## table for selecting a fit from the combinatorial fits
657 $widget{lcf_combo_group} = $co -> Label(-foreground=>$config{colors}{activehighlightcolor},
658 -font=>$config{fonts}{smbold})
659 -> pack(-side=>'top', -fill=>'x');
660 $widget{lcf_select_table} = $co -> Scrolled("HList",
661 -columns => 3,
662 -header => 1,
663 -height => 1,
664 -scrollbars => 'osoe',
665 -background => $config{colors}{background},
666 -selectbackground=> $config{colors}{current},
667 )
668 -> pack(-side=>'top', -fill=>'both', -expand=>1);
669 BindMouseWheel($widget{lcf_select_table});
670 $widget{lcf_select_table} -> Subwidget("xscrollbar")
671 -> configure(-background=>$config{colors}{background},
672 ($is_windows) ? () : (-width=>8));
673 $widget{lcf_select_table} -> Subwidget("yscrollbar")
674 -> configure(-background=>$config{colors}{background},
675 ($is_windows) ? () : (-width=>8));
676 $widget{lcf_select_table}->bind('<ButtonPress-3>',\&lcf_post_menu);
677
678 my $header_style = $widget{lcf_select_table} -> ItemStyle('text',
679 -font=>$config{fonts}{small},
680 -anchor=>'w',
681 -foreground=>$config{colors}{activehighlightcolor});
682 $widget{lcf_select_table} -> headerCreate(0,
683 -text=>"Standards",
684 -style=>$header_style,
685 -headerbackground=>$config{colors}{background},
686 -borderwidth => 1,);
687 $widget{lcf_select_table} -> headerCreate(1,
688 -text=>"R-factor",
689 -style=>$header_style,
690 -headerbackground=>$config{colors}{background},
691 -borderwidth => 1,);
692 $widget{lcf_select_table} -> headerCreate(2,
693 -text=>"Reduced chi-square",
694 -style=>$header_style,
695 -headerbackground=>$config{colors}{background},
696 -borderwidth => 1,);
697
698 ## table for displaying the results from a selected fit
699 my $lf = $co -> LabFrame(-label => 'Results for the selected fit',
700 -foreground => $config{colors}{activehighlightcolor},
701 -labelside => 'acrosstop')
702 -> pack(-fill=>'both', -expand=>1);
703
704 $widget{lcf_result_table} = $lf -> Scrolled("HList",
705 -columns => 4,
706 -header => 1,
707 -height => 4,
708 -scrollbars => 'osoe',
709 -background => $config{colors}{background},
710 -selectbackground => $config{colors}{background},
711 )
712 -> pack(-side=>'top', -fill=>'both', -expand=>1);
713 BindMouseWheel($widget{lcf_result_table});
714 $widget{lcf_result_table} -> Subwidget("xscrollbar")
715 -> configure(-background=>$config{colors}{background},
716 ($is_windows) ? () : (-width=>8));
717 $widget{lcf_result_table} -> Subwidget("yscrollbar")
718 -> configure(-background=>$config{colors}{background},
719 ($is_windows) ? () : (-width=>8));
720 $header_style = $widget{lcf_result_table} -> ItemStyle('text',
721 -font=>$config{fonts}{small},
722 -anchor=>'w',
723 -foreground=>$config{colors}{activehighlightcolor});
724 $widget{lcf_result_table} -> headerCreate(0,
725 -text=>"#",
726 -style=>$header_style,
727 -headerbackground=>$config{colors}{background},
728 -borderwidth => 1,);
729 $widget{lcf_result_table} -> headerCreate(1,
730 -text=>"Standard",
731 -style=>$header_style,
732 -headerbackground=>$config{colors}{background},
733 -borderwidth => 1,);
734 $widget{lcf_result_table} -> headerCreate(2,
735 -text=>"Weight",
736 -style=>$header_style,
737 -headerbackground=>$config{colors}{background},
738 -borderwidth => 1,);
739 $widget{lcf_result_table} -> headerCreate(3,
740 -text=>"E0",
741 -style=>$header_style,
742 -headerbackground=>$config{colors}{background},
743 -borderwidth => 1,);
744
745 ## $frame = $co -> Frame() -> pack(-fill=>'both', -side=>'bottom');
746 ## $frame -> Button(-text=>'Make groups of all fits',
747 ## @button_list,
748 ## -width=>1,
749 ## -command=>sub{Echo("Nothin' yet.")})
750 ## -> pack(-side=>'left', -fill=>'x', -expand=>1);
751 $lf -> Button(-text=>'Write CSV report for all fits',
752 @button_list,
753 -width=>1,
754 -command=>\&lcf_csv_report)
755 -> pack(-side=>'left', -fill=>'x', -expand=>1);
756
757
758 ## and finally....
759 &lcf_initialize(\%lcf_params, 1);
760 $top -> Busy;
761 $groups{$current}->{lcf_fitspace} ||= 'e';
762 $groups{$current}->{lcf_fitmin} ||= ($groups{$current}->{lcf_fitspace} eq 'k') ? $config{linearcombo}{fitmin_k} : $config{linearcombo}{fitmin};
763 $groups{$current}->{lcf_fitmax} ||= ($groups{$current}->{lcf_fitspace} eq 'k') ? $config{linearcombo}{fitmax_k} : $config{linearcombo}{fitmax};
764 ## plot the current group
765 if ($lcf_params{fitspace} =~ '[de]') {
766 $lcf_params{fitmin} = ($groups{$current}->{lcf_fitspace} =~ '[de]') ? $groups{$current}->{lcf_fitmin} : $config{linearcombo}{fitmin};
767 $lcf_params{fitmax} = ($groups{$current}->{lcf_fitspace} =~ '[de]') ? $groups{$current}->{lcf_fitmax} : $config{linearcombo}{fitmax};
768 lcf_quickplot_e(\%lcf_params);
769 } else {
770 $lcf_params{fitmin} = ($groups{$current}->{lcf_fitspace} eq 'k') ? $groups{$current}->{lcf_fitmin} : $config{linearcombo}{fitmin_k};
771 $lcf_params{fitmax} = ($groups{$current}->{lcf_fitspace} eq 'k') ? $groups{$current}->{lcf_fitmax} : $config{linearcombo}{fitmax_k};
772 lcf_quickplot_k(\%lcf_params);
773 $widget{lcf_operations} -> entryconfigure(7, -state=>'normal', -style=>$lcf_params{normal_style});
774 };
775 if (exists $lcf_data{$current}) {
776 my @list = $lcf_data{$current}{results}->[0];
777 $lcf_params{rfact} = $list[1];
778 $lcf_params{chisqr} = $list[2];
779 $lcf_params{chinu} = $list[3];
780 $lcf_params{nvarys} = $list[4];
781 $lcf_params{ndata} = $list[5];
782 lcf_display();
783 };
784 if (exists $groups{$current}->{lcf_fit} and $groups{$current}->{lcf_fit}) {
785 lcf_results(\%lcf_params);
786 $widget{lcf_operations} -> entryconfigure(4, -state=>'normal', -style=>$$hash_pointer{normal_style});
787 };
788 &lcf_initialize(\%lcf_params, 1);
789
790 $widget{lcf_fitmin} -> insert(0, $$hash_pointer{fitmin});
791 $widget{lcf_fitmin} -> configure(-validate=>"key");
792 $widget{lcf_fitmax} -> insert(0, $$hash_pointer{fitmax});
793 $widget{lcf_fitmax} -> configure(-validate=>"key");
794 $widget{lcf_noise} -> configure(-validate=>"key");
795
796 $top -> Unbusy;
797 $top -> update;
798
799 };
800
801 sub lcf_set_variable {
802 my ($k, $entry, $prop) = (shift, shift, shift);
803 ($entry =~ /^\s*$/) and ($entry = 0); # error checking ...
804 ($entry =~ /^\s*-$/) and return 1; # error checking ...
805 ($entry =~ /^\s*-?(\d+\.?\d*|\.\d+)\s*$/) or return 0;
806 my $param = substr($k,4);
807 $$hash_pointer{$param} = $entry;
808 $groups{$current} -> MAKE($k=>$entry);
809 if ($param =~ /fitm(ax|in)/) {
810 my $kk = ($$hash_pointer{fitspace} eq 'k') ? $param."_k" : $param."_e";
811 $$hash_pointer{$kk} = $entry;
812 $groups{$current} -> MAKE("lcf_$kk"=>$entry);
813 };
814 project_state(0);
815 return 1;
816 };
817
818 sub lcf_multiplexer {
819 my $lcf_params_ref = $_[0];
820 my $pick = $widget{lcf_operations} -> selectionGet;
821 ($pick = $pick->[0]) if (ref($pick) =~ /ARRAY/); # Tk 800 returns a scalar
822 # Tk 804 returns an array ref
823 SWITCH: {
824 lcf_fit($lcf_params_ref, 1), last SWITCH if ($pick == 1);
825 lcf_combinatorics($lcf_params_ref), last SWITCH if ($pick == 2);
826 lcf_marked($lcf_params_ref), last SWITCH if ($pick == 3);
827 lcf_report(), last SWITCH if ($pick == 4);
828 lcf_save_marked_report(), last SWITCH if ($pick == 5);
829 lcf_plot($lcf_params_ref), last SWITCH if ($pick == 6);
830 lcf_plot_r($lcf_params_ref), last SWITCH if ($pick == 7);
831 lcf_group($lcf_params_ref, 'fit'), last SWITCH if ($pick == 8);
832 lcf_group($lcf_params_ref, 'diff'), last SWITCH if ($pick == 9);
833 lcf_constrain("all"), last SWITCH if ($pick == 10);
834 lcf_constrain("marked"), last SWITCH if ($pick == 11);
835 lcf_reset($lcf_params_ref, 0), last SWITCH if ($pick == 12);
836 };
837 $widget{lcf_operations} -> selectionClear;
838 $widget{lcf_operations} -> anchorClear;
839 };
840
841
842
843
844 sub lcf_quickplot {
845 my $rlp = $_[0];
846 if ($$rlp{fitspace} eq 'k') {
847 $$rlp{fitmin_k} = $$rlp{fitmin};
848 $$rlp{fitmax_k} = $$rlp{fitmax};
849 } else {
850 $$rlp{fitmin_e} = $$rlp{fitmin};
851 $$rlp{fitmax_e} = $$rlp{fitmax};
852 };
853 lcf_quickplot_k($rlp), return if ($$rlp{fitspace} eq 'k');
854 lcf_quickplot_e($rlp);
855 };
856
857
858 sub lcf_quickplot_e {
859 my $rlp = $_[0];
860 Error("\"$groups{$current}->{label}\" cannot be plotted in energy."), return if ($groups{$current}->{is_chi} or
861 $groups{$current}->{is_rsp} or
862 $groups{$current}->{is_qsp});
863 my $how = ($$rlp{fitspace} eq 'e') ? 'emn' : 'emnd';
864 $groups{$current}->plotE($how, $dmode, \%plot_features, \@indicator);
865 my ($emin, $emax) = ($$rlp{enot}+$$rlp{fitmin}, $$rlp{enot}+$$rlp{fitmax});
866
867 my $suff = ($groups{$current}->{bkg_flatten}) ? 'flat' : 'norm';
868 my $sets = "set(l___cf.x = $current.energy+$groups{$current}->{bkg_eshift},\n";
869 if ($$rlp{fitspace} eq 'd') {
870 $sets .= " l___cf.y = deriv($current.norm)/deriv($current.energy)+$groups{$current}->{plot_yoffset})";
871 } else {
872 $sets .= " l___cf.y = $current.$suff+$groups{$current}->{plot_yoffset})";
873 };
874 $groups{$current}->dispose($sets, $dmode);
875 my @x = Ifeffit::get_array("l___cf.x");
876 my @y = Ifeffit::get_array("l___cf.y");
877 my ($ymin, $ymax) = Ifeffit::Group->floor_ceil(\@x, \@y, \%plot_features, 'e', $groups{$current}->{bkg_e0});
878
879 $groups{$current}->plot_vertical_line($emin, $ymin, $ymax, $dmode, "fit range", 0);
880 $groups{$current}->plot_vertical_line($emax, $ymin, $ymax, $dmode, "", 0);
881 $last_plot='e';
882 $plotsel -> raise('e');
883 };
884 sub lcf_quickplot_k {
885 my $rlp = $_[0];
886 Error("\"$groups{$current}->{label}\" cannot be plotted in k."), return if ($groups{$current}->{is_xanes} or
887 $groups{$current}->{is_rsp} or
888 $groups{$current}->{is_qsp});
889 $groups{$current}->plotk('kw', $dmode, \%plot_features, \@indicator);
890 my ($kmin, $kmax) = ($$rlp{fitmin}, $$rlp{fitmax});
891 ##my ($kw, $group) = ($groups{$current}->{fft_kw}, $groups{$current}->{group});
892 my ($kw, $group, $yoff) = ($plot_features{kw}, $groups{$current}->{group}, $groups{$current}->{plot_yoffset});
893 my @x = Ifeffit::get_array("$group.k");
894 $groups{$current}->dispose("set(l___cf.kw = $group.chi*$group.k^$kw)", $dmode);
895 my @y = Ifeffit::get_array("l___cf.kw");
896 my ($ymin, $ymax) = Ifeffit::Group->floor_ceil(\@x, \@y, \%plot_features, 'k', 0);
897 $ymin = $ymin*1.05 + $yoff;
898 $ymax = $ymax*1.05 + $yoff;
899 $groups{$current}->plot_vertical_line($kmin, $ymin, $ymax, $dmode, "fit range", 0);
900 $groups{$current}->plot_vertical_line($kmax, $ymin, $ymax, $dmode, "", 0);
901 $last_plot='k';
902 $plotsel -> raise('k');
903 };
904
905
906 ## need to verify that the current group is not one of the standards
907 ## selected in the standards grid. also need to count the number of
908 ## standards for the sake of the initial guesses for the weights
909 sub lcf_initialize {
910 my ($rlp, $reset) = @_;
911 my $n = 0;
912 my $unknown_stan = 0;
913 foreach my $i (1 .. $config{linearcombo}{maxspectra}) {
914 $$rlp{"delta_value$i"} = 0;
915 next unless exists($$rlp{"standard$i"});
916 ++$n if ($$rlp{"standard$i"} ne 'None');
917 ++$unknown_stan if ($$rlp{"standard$i"} eq $current);
918 };
919 if ($reset == 1) {
920 foreach my $i (1 .. $config{linearcombo}{maxspectra}) {
921 if (exists $groups{$current}->{"lcf_value$i"}) {
922 $$rlp{"value$i"} = $groups{$current}->{"lcf_value$i"};
923 } else {
924 $$rlp{"value$i"} = ($$rlp{"standard$i"} eq 'None') ? 0 : sprintf("%.3f", 1/$n);
925 };
926 };
927 } elsif ($reset == 2) {
928 foreach my $i (1 .. $config{linearcombo}{maxspectra}) {
929 $$rlp{"value$i"} = ($$rlp{"standard$i"} eq 'None') ? 0 : sprintf("%.3f", 1/$n);
930 };
931 };
932 my $state = ($unknown_stan) ? 'disabled' : 'normal';
933 my $style = ($unknown_stan) ? $$rlp{disabled_style} : $$rlp{normal_style};
934 $widget{lcf_operations} -> entryconfigure(1, -state=>$state, -style=>$style);
935 $widget{lcf_operations} -> entryconfigure(3, -state=>$state, -style=>$style);
936 my $nn = ($$rlp{fitspace} eq 'k') ? 1 : 2;
937 $widget{lcf_operations} -> entryconfigure(1, -state=>'disabled', -style=>$$rlp{disabled_style}) unless ($n>=$nn);
938 $widget{lcf_operations} -> entryconfigure(2, -state=>$state, -style=>$style);
939 $widget{lcf_operations} -> entryconfigure(2, -state=>'disabled', -style=>$$rlp{disabled_style}) unless ($n>=3);
940 $widget{lcf_operations} -> entryconfigure(3, -state=>'disabled', -style=>$$rlp{disabled_style}) unless ($n>=$nn);
941 $state = (exists $groups{$current}->{lcf_fit} and $groups{$current}->{lcf_fit}) ? 'normal' : 'disabled';
942 $style = (exists $groups{$current}->{lcf_fit} and $groups{$current}->{lcf_fit}) ? $$rlp{normal_style} : $$rlp{disabled_style};
943 $widget{lcf_operations} -> entryconfigure(4, -state=>$state, -style=>$style);
944 $widget{lcf_operations} -> entryconfigure(5, -state=>'normal', -style=>$$rlp{normal_style}) if (-e $groups{"Default Parameters"}->find('athena', 'temp_lcf'));
945 $state = ($n) ? 'normal' : 'disabled';
946 $style = ($n) ? $$rlp{normal_style} : $$rlp{disabled_style};
947 $widget{lcf_operations} -> entryconfigure(6, -state=>$state, -style=>$style);
948 $widget{lcf_operations} -> entryconfigure(8, -state=>'disabled', -style=>$$rlp{disabled_style});
949 $widget{lcf_operations} -> entryconfigure(9, -state=>'disabled', -style=>$$rlp{disabled_style});
950
951 $widget{lcf_maxstan} -> configure(-state=>($unknown_stan) ? 'disabled' : 'normal');
952 $widget{lcf_maxstan} -> configure(-state=>'disabled') unless ($n>=3);
953 $widget{lcf_linear} -> configure(-state=>'normal');
954 $widget{lcf_e0all} -> configure(-state=>'normal');
955 if ($$rlp{fitspace} eq 'k') {
956 $widget{lcf_linear} -> configure(-state=>'disabled');
957 $widget{lcf_e0all} -> configure(-state=>'disabled');
958 } elsif ($$rlp{fitspace} eq 'd') {
959 $widget{lcf_linear} -> configure(-state=>'disabled');
960 };
961 };
962
963
964
965
966 ## this multiplexes between the norm(E) and chi(k) fits
967 sub lcf_fit {
968 my $rlp = $_[0];
969 $groups{$current} -> dispose("set &status = 0\n", $dmode);
970 ## need to clean up error bars from the last fit. this should be
971 ## innocuous if those scalars do not exist in Ifeffit
972 foreach my $i (1 .. $config{linearcombo}{maxspectra}) {
973 $groups{$current}->MAKE("lcf_delta_e0val$i" => 0,
974 "lcf_delta_value$i" => 0,
975 );
976 $groups{$current} -> dispose("erase delta_e$i delta_w$i delta_ww$i", $dmode);
977 };
978 $groups{$current} -> dispose("erase delta_yint delta_slope", $dmode);
979 $$rlp{fit_status} = 0;
980 if ($$rlp{fitspace} eq 'k') {
981 $$rlp{fitmin_k} = $$rlp{fitmin};
982 $$rlp{fitmax_k} = $$rlp{fitmax};
983 } else {
984 $$rlp{fitmin_e} = $$rlp{fitmin};
985 $$rlp{fitmax_e} = $$rlp{fitmax};
986 };
987 $$rlp{fitting} = 1;
988 SWITCH: {
989 lcf_fit_k(@_), last SWITCH if ($$rlp{fitspace} eq 'k');
990 lcf_fit_e(@_);
991 };
992 $$rlp{fitting} = 0;
993 };
994
995 sub lcf_marked {
996 my $rlp = $_[0];
997 my $start = $current;
998 #foreach my $i (1 .. $config{linearcombo}{maxspectra}) {
999 # $groups{$current} -> MAKE("lcf_standard$i" => $$rlp{"standard$i"});
1000 # next if ($$rlp{"standard$i"} eq 'None');
1001 # $groups{$current} -> MAKE("lcf_standard_lab$i" => $$rlp{"standard_lab$i"},
1002 # "lcf_value$i" => $$rlp{"value$i"},
1003 # "lcf_e0$i" => $$rlp{"e0$i"},
1004 # "lcf_e0val$i" => $$rlp{"e0val$i"},
1005 # );
1006 #};
1007 if ($config{linearcombo}{marked_query} eq 'set') {
1008 lcf_constrain("marked");
1009 } elsif ($config{linearcombo}{marked_query} eq 'skip') {
1010 1; ## do nothing
1011 } else {
1012 my $dialog =
1013 $top -> Dialog(-bitmap => 'questhead',
1014 -text => "You are about to do linear combination fits on the marked groups. Would you like to constrain the parameters of all marked groups to those of the current group?",
1015 -title => 'Athena: Constrain parameters for linear combination fit?',
1016 -buttons => ["Constrain", "Do not constrain", "Cancel fits"],
1017 -default_button => 'Constrain');
1018 my $answer = $dialog->Show();
1019 return if ($answer eq "Cancel fits");
1020 lcf_constrain("marked") if ($answer eq "Constrain");
1021 };
1022 Echo("Fitting all marked groups ...");
1023 $top -> Busy;
1024 unlink($groups{"Default Parameters"}->find('athena', 'temp_lcf'))
1025 if (-e $groups{"Default Parameters"}->find('athena', 'temp_lcf'));
1026 my $n_fits = 0;
1027 tie my $timer, 'Time::Stopwatch';
1028 foreach my $g (&sorted_group_list) {
1029 next unless $marked{$g};
1030 my $is_ok = 1;
1031 foreach my $i (1 .. $config{linearcombo}{maxspectra}) {
1032 $is_ok = 0 if ($g eq $$rlp{"standard$i"});
1033 };
1034 next unless $is_ok;
1035 ++$n_fits;
1036 set_properties(0, $g, 0);
1037 lcf_fit($rlp);
1038 };
1039 my $elapsed = $timer;
1040 undef $timer;
1041 $elapsed = sprintf("%d fits in %.0f min, %.0f sec", $n_fits, $elapsed/60, $elapsed%60);
1042 lcf_marked_report();
1043 set_properties(0, $start,0);
1044 $widget{lcf_operations} -> entryconfigure(5, -state=>'normal', -style=>$$rlp{normal_style});
1045 Echo("Fitting all marked groups ... done! ($elapsed)");
1046 $top -> Unbusy;
1047 };
1048
1049 sub lcf_fit_e {
1050 my $rlp = $_[0];
1051 my $plot = $_[1];
1052 my $bg = $config{colors}{background};
1053 $widget{lcf_maxfit} -> configure(-foreground=>'black',
1054 -background=>$bg,
1055 -text=>"") unless $$rlp{doing_combinatorics};
1056
1057 my $abort = 0;
1058 foreach my $i (1 .. $config{linearcombo}{maxspectra}) {
1059 next if ($$rlp{"standard$i"} eq 'None');
1060 my $this = $$rlp{"standard$i"};
1061 ++$abort if $groups{$this}->{is_chi};
1062 };
1063 Error("Fit aborted! One or more of your standards cannot be plotted in energy."), return if $abort;
1064
1065 my $how = ($$rlp{fitspace} eq 'e') ? 'norm(E)' : 'deriv(E)';
1066 Echo("Linear combination fitting $groups{$current}->{label} in $how ... ");
1067 my $is_busy = grep (/Busy/, $top->bindtags);
1068 $top -> Busy unless $is_busy;
1069 my $group = $groups{$current}->{group};
1070 my $eshift = $groups{$current}->{bkg_eshift};
1071 $groups{$current}->dispatch_bkg($dmode) if $groups{$current}->{update_bkg};
1072 my $command = "## performing linear combination fit in $how\nunguess\n";
1073 $command .= "erase \@group l___cf\n";
1074 my $define = "def l___cf.mix =";
1075 push @{ $$rlp{deflist} }, "l___cf.mix";
1076 $$rlp{filestring} = "linear combination in E of";
1077 my @weights;
1078 my @which;
1079
1080 $groups{$current}->dispose($command, $dmode);
1081 $command = "";
1082 ## make the unknown data arrays
1083 lcf_arrays_e(1);
1084
1085 ## make sure each standard is up-to-date with respect to
1086 ## normalization
1087 $$rlp{nstandards} = 0;
1088 foreach my $i (1 .. $config{linearcombo}{maxspectra}) {
1089 next if ($$rlp{"standard$i"} eq 'None');
1090 ++$$rlp{nstandards};
1091 push @which, $i;
1092 my $this = $$rlp{"standard$i"};
1093 $groups{$this}->dispatch_bkg($dmode) if $groups{$this}->{update_bkg};
1094 $$rlp{filestring} .= " " . $$rlp{"standard_lab$i"};
1095 };
1096 ## the last standard needs to be handled slightly differently
1097 my $last = pop @which;
1098
1099 ## interpolate each standard onto the grid of the unknown, guess a
1100 ## weight and (if requested) an e0 shift. make sure to use the
1101 ## flattened spectrum if appropriate
1102 foreach my $j (@which) {
1103 my $this = $$rlp{"standard$j"};
1104 my $esh = sprintf("%.3f",$groups{$this}->{bkg_eshift});
1105 my $suff = ($groups{$this}->{bkg_flatten}) ? 'flat' : 'norm';
1106 ($suff = 'norm') if ($$rlp{fitspace} eq 'd');
1107 $command .= "# $this is $groups{$this}->{label}\n";
1108 if ($$rlp{e0all}) {
1109 if ($j == $which[0]) {
1110 $command .= "guess e$j = " . $$rlp{"e0val$j"} . "\n";
1111 } else {
1112 $command .= "def e$j = e$which[0]\n";
1113 push @{ $$rlp{deflist} }, "e$j";
1114 };
1115 } else {
1116 if ($$rlp{"e0$j"}) {
1117 $command .= "guess e$j = " . $$rlp{"e0val$j"} . "\n";
1118 } else {
1119 $command .= "set e$j = " .$$rlp{"e0val$j"} . "\n";
1120 };
1121 };
1122 my $function = ($$rlp{fitspace} eq 'd') ? "deriv($this.$suff)/deriv($this.energy)" : "$this.$suff";
1123 if ($$rlp{nonneg}) {
1124 $command .= "guess ww$j = " . $$rlp{"value$j"} . "\n";
1125 $command .= "def w$j = max(0,min(ww$j,1))\n";
1126 push @{ $$rlp{deflist} }, "w$j";
1127 $command .= "def l___cf.$j = abs(w$j)*splint($this.energy+e$j+$esh, $function, l___cf.energy)\n";
1128 push @{ $$rlp{deflist} }, "l___cf.$j";
1129 } else {
1130 $command .= "guess w$j = " . $$rlp{"value$j"} . "\n";
1131 $command .= "def l___cf.$j = w$j*splint($this.energy+e$j+$esh, $function, l___cf.energy)\n";
1132 push @{ $$rlp{deflist} }, "l___cf.$j";
1133 };
1134 $define .= " l___cf.$j +";
1135 push @weights, "w$j";
1136 };
1137
1138 ## do the same for the last spectrum, except def its weight to be
1139 ## one minus the sum of all the rest of the weights
1140 my $this = $$rlp{"standard$last"};
1141 my $esh = sprintf("%.3f",$groups{$this}->{bkg_eshift});
1142 my $suff = ($groups{$this}->{bkg_flatten}) ? 'flat' : 'norm';
1143 ($suff = 'norm') if ($$rlp{fitspace} eq 'd');
1144 my @www = ($$rlp{nonneg}) ? map { "abs(".$_.")" } @weights : @weights;
1145 $command .= "# $this is $groups{$this}->{label}\n";
1146 if ($$rlp{100}) {
1147 $command .= "def w$last = max(0, 1 - (" . join("+", @weights) . "))\n";
1148 push @{ $$rlp{deflist} }, "w$last";
1149 } else {
1150 if ($$rlp{nonneg}) {
1151 $command .= "guess ww$last = " . $$rlp{"value$last"} . "\n";
1152 $command .= "def w$last = max(0,min(ww$last,1))\n";
1153 push @{ $$rlp{deflist} }, "w$last";
1154 } else {
1155 $command .= "guess w$last = " . $$rlp{"value$last"} . "\n";
1156 };
1157 };
1158 push @weights, "w$last";
1159 if ($$rlp{e0all}) {
1160 $command .= "def e$last = e$which[0]\n";
1161 push @{ $$rlp{deflist} }, "e$last";
1162 } elsif ($$rlp{"e0$last"}) {
1163 $command .= "guess e$last = " . $$rlp{"e0val$last"} ."\n";
1164 } else {
1165 $$rlp{"e0val$last"} ||= 0;
1166 $command .= "set e$last = " . $$rlp{"e0val$last"} ."\n";
1167 };
1168 my $function = ($$rlp{fitspace} eq 'd') ? "deriv($this.$suff)/deriv($this.energy)" : "$this.$suff";
1169 $command .= "def l___cf.$last = w$last*splint($this.energy+e$last+$esh, $function, l___cf.energy)\n";
1170 push @{ $$rlp{deflist} }, "l___cf.$last";
1171 $define .= " l___cf.$last";
1172
1173 ## add a line to the fitting function, if requested. the line
1174 ## should only be applied after e0, so use a step function
1175 if (($$rlp{fitspace} eq 'e') and $$rlp{linear}) {
1176 $command .= "step l___cf.energy $groups{$current}->{bkg_eshift} $groups{$current}->{bkg_e0} l___cf.theta\n";
1177 #$command .= "step $group.energy $$rlp{fitmin} $group.theta\n";
1178 $command .= "guess slope=0\nguess yint=0\n";
1179 $define .= " + l___cf.theta*(yint + slope*l___cf.energy)";
1180 };
1181 $define .= "\n";
1182 $command .= $define;
1183
1184 ## def the residual array and minimize
1185 my ($emin, $emax) = ($$rlp{enot}+$$rlp{fitmin},
1186 $$rlp{enot}+$$rlp{fitmax});
1187 $command .= "def l___cf.resid = l___cf.mix - l___cf.data\n";
1188 push @{ $$rlp{deflist} }, "l___cf.resid";
1189 $command .= "minimize(l___cf.resid, x=l___cf.energy, xmin=$emin, xmax=$emax)\n";
1190 $groups{$current}->dispose($command, $dmode);
1191 # if ($$rlp{nonneg}) {
1192 # foreach my $w (@weights) {
1193 # $groups{$current}->dispose("set $w = abs($w)\n", $dmode);
1194 # };
1195 # };
1196
1197 ## store the fit results in the object
1198 $$rlp{fit_status} = lcf_values($rlp);
1199 $groups{$current}->MAKE(lcf_fit => 1,
1200 lcf_fitspace => $$rlp{fitspace},
1201 lcf_fit_status => $$rlp{fit_status},
1202 lcf_linear => $$rlp{linear},
1203 lcf_nonneg => $$rlp{nonneg},
1204 lcf_100 => $$rlp{100},
1205 lcf_e0all => $$rlp{e0all},
1206 lcf_slope => $$rlp{slope},
1207 lcf_yint => $$rlp{yint},
1208 lcf_delta_slope => $$rlp{delta_slope},
1209 lcf_delta_yint => $$rlp{delta_yint},
1210 lcf_fitmin => $$rlp{fitmin},
1211 lcf_fitmax => $$rlp{fitmax},);
1212 foreach my $i (1 .. $config{linearcombo}{maxspectra}) {
1213 $groups{$current}->MAKE("lcf_standard$i" => $$rlp{"standard$i"});
1214 next if ($$rlp{"standard$i"} eq 'None');
1215 $groups{$current}->MAKE("lcf_standard_lab$i" => $$rlp{"standard_lab$i"},
1216 "lcf_e0$i" => $$rlp{"e0$i"},
1217 "lcf_e0val$i" => $$rlp{"e0val$i"},
1218 "lcf_delta_e0val$i" => $$rlp{"delta_e0val$i"},
1219 "lcf_value$i" => $$rlp{"value$i"},
1220 "lcf_delta_value$i" => $$rlp{"delta_value$i"},
1221 );
1222 };
1223 project_state(0);
1224 ## write a report to the text box
1225 lcf_statistics($rlp);
1226 lcf_results($rlp) if ($plot);
1227
1228 my $red = $config{colors}{single};
1229
1230 lcf_undef($rlp);
1231 ## plot the results
1232 lcf_plot_e($rlp) if $plot;
1233
1234 ## and finish up
1235 $widget{lcf_operations} -> entryconfigure(4, -state=>'normal', -style=>$$rlp{normal_style});
1236 $widget{lcf_operations} -> entryconfigure(8, -state=>'normal', -style=>$$rlp{normal_style});
1237 $widget{lcf_operations} -> entryconfigure(9, -state=>'normal', -style=>$$rlp{normal_style});
1238 Echo("Linear combination fitting $groups{$current}->{label} in norm(E) ... done!");
1239 $top -> Unbusy unless $is_busy;
1240 };
1241
1242
1243 sub lcf_fit_k {
1244 my $rlp = $_[0];
1245 my $plot = $_[1];
1246 my $bg = $config{colors}{background};
1247 $widget{lcf_maxfit} -> configure(-foreground=>'black',
1248 -background=>$bg,
1249 -text=>"") unless $$rlp{doing_combinatorics};
1250
1251 my $abort = 0;
1252 foreach my $i (1 .. $config{linearcombo}{maxspectra}) {
1253 next if ($$rlp{"standard$i"} eq 'None');
1254 my $this = $$rlp{"standard$i"};
1255 ++$abort if $groups{$this}->{is_xanes};
1256 };
1257 Error("Fit aborted! One or more of your standards cannot be plotted in k."), return if $abort;
1258
1259 Echo("Linear combination fitting $groups{$current}->{label} in chi(k) ... ");
1260 $top -> Busy;
1261 my $group = $groups{$current}->{group};
1262 ##my $kw = $groups{$current}->{fft_kw};
1263 my $kw = $plot_features{kw};
1264 $$rlp{kw} = $kw;
1265 $groups{$current}->dispatch_bkg($dmode) if $groups{$current}->{update_bkg};
1266 my $command = "## performing linear combination fit in chi(k)\nunguess\n";
1267 $command .= "erase \@group l___cf\n";
1268 my $define = "def l___cf.mix =";
1269 push @{ $$rlp{deflist} }, "l___cf.mix";
1270 $$rlp{filestring} = "linear combination in k of";
1271 my @weights;
1272 my @which;
1273 $groups{$current}->dispose($command, $dmode);
1274 $command = "";
1275 lcf_arrays_k(1);
1276
1277 ## make sure each standard is up-to-date with respect to
1278 ## normalization
1279 $$rlp{nstandards} = 0;
1280 my $smallest_kmax = 10000;
1281 foreach my $i (1 .. $config{linearcombo}{maxspectra}) {
1282 next if ($$rlp{"standard$i"} eq 'None');
1283 ++$$rlp{nstandards};
1284 push @which, $i;
1285 my $this = $$rlp{"standard$i"};
1286 $groups{$this}->dispatch_bkg($dmode) if $groups{$this}->{update_bkg};
1287 $$rlp{filestring} .= " " . $$rlp{"standard_lab$i"};
1288
1289 ## need to make sure that the fitting range is not beyond any of the data
1290 my @y = Ifeffit::get_array($this . ".k");
1291 ($smallest_kmax = $y[$#y]) if ($y[$#y] < $smallest_kmax);
1292 };
1293
1294 ## the last standard needs to be handled slightly differently
1295 my $last = ($$rlp{nstandards} > 1) ? pop @which : q{};
1296
1297 ## guess a weight and (if requested) an e0 shift. add this to the mix
1298 foreach my $j (@which) {
1299 my $this = $$rlp{"standard$j"};
1300 $command .= "# $this is $groups{$this}->{label}\n";
1301 if ($$rlp{nonneg}) {
1302 $command .= "guess ww$j = " . $$rlp{"value$j"} . "\n";
1303 $command .= ($last) ? "def w$j = max(0,min(ww$j,1))\n" : "def w$j = ww$j\n";
1304 } else {
1305 $command .= "guess w$j = " . $$rlp{"value$j"} . "\n";
1306 };
1307 push @{ $$rlp{deflist} }, "w$j";
1308 $command .= "def l___cf.$j = w$j*$this.chi*$this.k^$kw\n";
1309 push @{ $$rlp{deflist} }, "l___cf.$j";
1310 $define .= " l___cf.$j +";
1311 push @weights, "w$j";
1312 };
1313
1314 if ($last) {
1315 ## do the same for the last spectrum, except def its weight to be
1316 ## one minus the sum of all the rest of the weights
1317 my $this = $$rlp{"standard$last"};
1318 my $suff = ($groups{$this}->{bkg_flatten}) ? 'flat' : 'norm';
1319 my @www = ($$rlp{nonneg}) ? map { "abs(".$_.")" } @weights : @weights;
1320 $command .= "# $this is $groups{$this}->{label}\n";
1321 if ($$rlp{100}) {
1322 $command .= "def w$last = max(0, 1 - (" . join("+", @weights) . "))\n";
1323 } else {
1324 $command .= "guess ww$last = " . $$rlp{"value$last"} . "\n";
1325 $command .= "def w$last = max(0,min(ww$last,1))\n";
1326 };
1327 $command .= "def l___cf.$last = w$last*$this.chi*$this.k^$kw\n";
1328 push @{ $$rlp{deflist} }, "l___cf.$last", "w$last";
1329 $define .= " l___cf.$last";
1330 } else {
1331 $define =~ s/\+\s*$//;
1332 };
1333
1334 $define .= "\n";
1335 $command .= $define;
1336
1337 ## def the residual array and minimize
1338 my ($kmin, $kmax) = ($$rlp{fitmin}, $$rlp{fitmax});
1339 ($kmax = $smallest_kmax - 0.01) if ($kmax > $smallest_kmax);
1340 $$rlp{fitmax} = $kmax;
1341 ##$command .= "def l___cf.resid = l___cf.mix - $group.chi*$group.k^$kw\n";
1342 $command .= "def l___cf.resid = l___cf.mix - l___cf.data\n";
1343 push @{ $$rlp{deflist} }, "l___cf.resid";
1344 $command .= "minimize(l___cf.resid, x=$group.k, xmin=$kmin, xmax=$kmax)\n";
1345 $groups{$current}->dispose($command, $dmode);
1346 # if ($$rlp{nonneg}) {
1347 # foreach my $w (@weights, "w$last") {
1348 # $groups{$current}->dispose("set $w = abs($w)\n", $dmode);
1349 # };
1350 # };
1351
1352 ## store the fit results in the object
1353 $$rlp{fit_status} = lcf_values($rlp);
1354 $groups{$current}->MAKE(lcf_fit => 1,
1355 lcf_fitspace => 'k',
1356 lcf_fit_status => $$rlp{fit_status},
1357 lcf_linear => $$rlp{linear},
1358 lcf_nonneg => $$rlp{nonneg},
1359 lcf_100 => $$rlp{100},
1360 lcf_e0all => $$rlp{e0all},
1361 lcf_slope => $$rlp{slope},
1362 lcf_yint => $$rlp{yint},
1363 lcf_kw => $$rlp{kw},
1364 lcf_fitmin => $$rlp{fitmin},
1365 lcf_fitmax => $$rlp{fitmax},);
1366 foreach my $i (1 .. $config{linearcombo}{maxspectra}) {
1367 $groups{$current}->MAKE("lcf_standard$i" => $$rlp{"standard$i"});
1368 next if ($$rlp{"standard$i"} eq 'None');
1369 $groups{$current}->MAKE("lcf_standard_lab$i" => $$rlp{"standard_lab$i"},
1370 "lcf_value$i" => $$rlp{"value$i"},
1371 "lcf_delta_value$i" => $$rlp{"delta_value$i"},
1372 );
1373 };
1374 project_state(0);
1375
1376 ## write a report to the text box
1377 lcf_statistics($rlp);
1378 lcf_results($rlp) if ($plot);
1379 my $last_error = 0;
1380
1381 lcf_undef($rlp);
1382 lcf_plot_k($rlp) if ($plot);
1383
1384 ## and finish up
1385 $widget{lcf_operations} -> entryconfigure(4, -state=>'normal', -style=>$$rlp{normal_style});
1386 $widget{lcf_operations} -> entryconfigure(8, -state=>'normal', -style=>$$rlp{normal_style});
1387 $widget{lcf_operations} -> entryconfigure(9, -state=>'normal', -style=>$$rlp{normal_style});
1388 $widget{lcf_operations} -> entryconfigure(7, -state=>'normal', -style=>$$rlp{normal_style});
1389 Echo("Linear combination fitting $groups{$current}->{label} in chi(k) ... done!");
1390 $top -> Unbusy;
1391 };
1392
1393
1394 sub lcf_values {
1395 my $rlp = $_[0];
1396 my $last_error = 0;
1397 my $j = 0;
1398 foreach my $i (1 .. $config{linearcombo}{maxspectra}) {
1399 next if ($$rlp{"standard$i"} eq 'None');
1400 ++$j;
1401 $$rlp{"value$i"} = sprintf("%.3f", Ifeffit::get_scalar("w$i"));
1402 my $thiserr;
1403 if ($$rlp{nstandards} == 1) {
1404 if ($$rlp{nonneg}) {
1405 $thiserr = Ifeffit::get_scalar("delta_ww".$$rlp{nstandards});
1406 } else {
1407 $thiserr = Ifeffit::get_scalar("delta_w".$$rlp{nstandards});
1408 };
1409 } elsif ($j eq $$rlp{nstandards}) {
1410 if ($$rlp{100}) {
1411 $thiserr = sqrt($last_error);
1412 } else {
1413 if ($$rlp{nonneg}) {
1414 $thiserr = Ifeffit::get_scalar("delta_ww".$$rlp{nstandards});
1415 } else {
1416 $thiserr = Ifeffit::get_scalar("delta_w".$$rlp{nstandards});
1417 };
1418 };
1419 } else {
1420 if ($$rlp{nonneg}) {
1421 $last_error += Ifeffit::get_scalar("delta_ww$i")**2;
1422 $thiserr = Ifeffit::get_scalar("delta_ww$i");
1423 } else {
1424 $last_error += Ifeffit::get_scalar("delta_w$i")**2;
1425 $thiserr = Ifeffit::get_scalar("delta_w$i");
1426 };
1427 };
1428 $$rlp{"delta_value$i"} = $thiserr;
1429 };
1430
1431 unless ($$rlp{fitspace} eq 'k') {
1432 foreach my $i (1 .. $config{linearcombo}{maxspectra}) {
1433 next if ($$rlp{"standard$i"} eq 'None');
1434 $$rlp{"e0val$i"} = sprintf("%.3f", Ifeffit::get_scalar("e$i"));
1435 $$rlp{"delta_e0val$i"} = sprintf("%.3f", Ifeffit::get_scalar("delta_e$i"));
1436 };
1437
1438 if ($$rlp{linear}) {
1439 $$rlp{slope} = Ifeffit::get_scalar("slope");
1440 $$rlp{delta_slope} = Ifeffit::get_scalar("delta_slope");
1441 $$rlp{yint} = Ifeffit::get_scalar("yint");
1442 $$rlp{delta_yint} = Ifeffit::get_scalar("delta_yint");
1443 } else {
1444 $$rlp{slope} = 0;
1445 $$rlp{delta_slope} = 0;
1446 $$rlp{yint} = 0;
1447 $$rlp{delta_yint} = 0;
1448 };
1449 };
1450
1451
1452 return Ifeffit::get_scalar('&status');
1453 };
1454
1455
1456 sub lcf_undef {
1457 my $rlp = $_[0];
1458 $groups{$current}->dispose("## best not to leave defs lying around...", $dmode);
1459 foreach (@{ $$rlp{deflist} }) {
1460 $groups{$current}->dispose("set $_ = $_", $dmode);
1461 };
1462 $$rlp{deflist} = ();
1463 };
1464
1465 sub lcf_plot {
1466 my $rlp = $_[0];
1467 if ($$rlp{fitspace} eq 'k') {
1468 $$rlp{fitmin_k} = $$rlp{fitmin};
1469 $$rlp{fitmax_k} = $$rlp{fitmax};
1470 } else {
1471 $$rlp{fitmin_e} = $$rlp{fitmin};
1472 $$rlp{fitmax_e} = $$rlp{fitmax};
1473 };
1474 lcf_plot_k($rlp), return if ($$rlp{fitspace} eq 'k');
1475 lcf_plot_e($rlp);
1476 };
1477
1478 sub lcf_plot_e {
1479 my $rlp = $_[0];
1480 Error("\"$groups{$current}->{label}\" cannot be plotted in energy."),
1481 return if ($groups{$current}->{is_chi} or
1482 $groups{$current}->{is_rsp} or
1483 $groups{$current}->{is_qsp});
1484 my $how = ($$rlp{fitspace} eq 'e') ? 'norm(E)' : 'deriv(E)';
1485 Echo("Plotting $groups{$current}->{label} + linear combination as $how ... ");
1486 $top -> Busy;
1487 my $linear = (($$rlp{slope} != 0) or ($$rlp{yint} != 0));
1488 my $group = $groups{$current}->{group};
1489 my $yoff = $groups{$current}->{plot_yoffset};
1490 $groups{$current}->dispose("## Plotting linear combination of spectra as $how\n", $dmode);
1491 #($command .= "step $group.energy $groups{$current}->{bkg_e0} $group.theta\n")
1492 # if $linear;
1493
1494 lcf_arrays_e();
1495
1496 ## plot 'em up
1497 $how = ($$rlp{fitspace} eq 'e') ? 'emn' : 'emnd';
1498 $groups{$current}->plotE($how, $dmode, \%plot_features, \@indicator);
1499 #$groups{$current}->dispose($command, $dmode);
1500 my $color = $config{plot}{'c1'};
1501 my $c = 1;
1502 if ($$rlp{noise} > 0 ) {
1503 $groups{$current}->dispose("plot(l___cf.energy, \"l___cf.data+$yoff\", key=\"data+noise\", style=lines, color=$color)\n", $dmode);
1504 $color = $config{plot}{'c2'};
1505 ++$c;
1506 };
1507 $groups{$current}->dispose("plot(l___cf.energy, \"l___cf.mix+$yoff\", key=\"linear combo.\", style=lines, color=$color)\n", $dmode);
1508 if ($$rlp{difference}) {
1509 ++$c;
1510 my $color = $config{plot}{'c'.$c};
1511 my $key = 'difference';
1512 $groups{$current}->dispose("plot(l___cf.energy, \"l___cf.diff+$yoff\", key=\"$key\", style=lines, color=$color)\n", $dmode);
1513 };
1514
1515 my $suff = ($groups{$current}->{bkg_flatten}) ? 'flat' : 'norm';
1516 $groups{$current}->dispose("set l___cf.x = $current.energy+$groups{$current}->{bkg_eshift}", $dmode);
1517 if ($$rlp{fitspace} eq 'd') {
1518 $groups{$current}->dispose("set l___cf.y = deriv($current.norm)/deriv($current.energy)+$groups{$current}->{plot_yoffset}", $dmode);
1519 } else {
1520 $groups{$current}->dispose("set l___cf.y = $current.$suff+$groups{$current}->{plot_yoffset}", $dmode);
1521 };
1522 my @x = Ifeffit::get_array("l___cf.x");
1523 my @y = Ifeffit::get_array("l___cf.y");
1524 my ($ymin, $ymax) = Ifeffit::Group->floor_ceil(\@x, \@y, \%plot_features, 'e', $groups{$current}->{bkg_e0});
1525 my $offset = 0;
1526 if ($$rlp{components}) {
1527 foreach my $i (1 .. $config{linearcombo}{maxspectra}) {
1528 next if ($$rlp{"standard$i"} eq 'None');
1529 ++$c;
1530 my $color = $config{plot}{'c'.$c};
1531 ($offset = sprintf("%.4f", abs(($ymin-$yoff)*0.5*$c))) if ($$rlp{fitspace} eq 'd');
1532 my $key = $groups{$$rlp{"standard$i"}}->{label};
1533 $groups{$current}->dispose("plot(l___cf.energy, \"l___cf.$i-$offset+$yoff\", key=\"$key\", style=lines, color=$color)\n", $dmode);
1534 };
1535 };
1536
1537 my ($emin, $emax) = ($$rlp{enot}+$$rlp{fitmin},
1538 $$rlp{enot}+$$rlp{fitmax});
1539 $groups{$current}->plot_vertical_line($emin, $ymin, $ymax, $dmode, "fit range", 0);
1540 $groups{$current}->plot_vertical_line($emax, $ymin, $ymax, $dmode, "", 0);
1541 $last_plot='e';
1542 Echo("Plotting $groups{$current}->{label} + linear combination as norm(E) ... done!");
1543 $top -> Unbusy;
1544 };
1545
1546
1547 ## need to construct l___cf.mix anew...
1548 sub lcf_plot_k {
1549 Error("\"$groups{$current}->{label}\" cannot be plotted in k."), return if ($groups{$current}->{is_xanes} or
1550 $groups{$current}->{is_rsp} or
1551 $groups{$current}->{is_qsp});
1552 Echo("Plotting $groups{$current}->{label} + linear combination as chi(k) ... ");
1553 $groups{$current}->dispose("## Plotting linear combination of spectra as chi(k)\n", $dmode);
1554 my $rlp = $_[0];
1555 my $group = $groups{$current}->{group};
1556 my $yoff = $groups{$current}->{plot_yoffset};
1557 my ($kmin, $kmax) = ($$rlp{fitmin}, $$rlp{fitmax});
1558 $groups{$current}->plotk('kw', $dmode, \%plot_features, \@indicator);
1559 lcf_arrays_k(0);
1560
1561 my $color = $config{plot}{'c1'};
1562 my $c = 1;
1563 if ($$rlp{noise} > 0 ) {
1564 $groups{$current}->dispose("plot($group.k, \"l___cf.data+$yoff\", key=\"data+noise\", style=lines, color=$color)\n", $dmode);
1565 $color = $config{plot}{'c2'};
1566 ++$c;
1567 };
1568
1569 $groups{$current}->dispose("plot($group.k, \"l___cf.mix+$yoff\", key=\"linear combo.\", style=lines, color=$color)\n", $dmode);
1570 my @x = Ifeffit::get_array("$group.k");
1571 ##$groups{$current}->dispose("set l___cf.y = $group.chi * $group.k**$groups{$current}->{fft_kw}");
1572 $groups{$current}->dispose("set l___cf.y = $group.chi * $group.k**$plot_features{kw}", $dmode);
1573 my @y = Ifeffit::get_array("l___cf.y");
1574 my ($ymin, $ymax) = Ifeffit::Group->floor_ceil(\@x, \@y, \%plot_features, 'k', 0);
1575 $ymin = $ymin*1.05 + $yoff;
1576 $ymax = $ymax*1.05 + $yoff;
1577 my $offset = 0;
1578 if ($$rlp{difference}) {
1579 ++$c;
1580 my $color = $config{plot}{'c'.$c};
1581 my $key = 'difference';
1582 $offset = sprintf("%.4f", abs(($ymin-$yoff)*0.5*$c));
1583 $groups{$current}->dispose("plot($group.k, \"l___cf.resid-$offset+$yoff\", key=\"$key\", style=lines, color=$color)\n", $dmode);
1584 };
1585 if ($$rlp{components}) {
1586 foreach my $i (1 .. $config{linearcombo}{maxspectra}) {
1587 next if ($$rlp{"standard$i"} eq 'None');
1588 ++$c;
1589 my $color = $config{plot}{'c'.$c};
1590 my $key = $groups{$$rlp{"standard$i"}}->{label};
1591 $offset = sprintf("%.4f", abs(($ymin-$yoff)*0.5*$c));
1592 $groups{$current}->dispose("plot($group.k, \"l___cf.$i-$offset+$yoff\", key=\"$key\", style=lines, color=$color)\n", $dmode);
1593 };
1594 };
1595 $ymin = ($offset) ? $yoff - abs(($ymin-$yoff)*0.6*$c) : $ymin;
1596 $groups{$current}->plot_vertical_line($kmin, $ymin, $ymax, $dmode, "fit range", 0);
1597 $groups{$current}->plot_vertical_line($kmax, $ymin, $ymax, $dmode, "", 0);
1598 $last_plot='k';
1599 Echo("Plotting $groups{$current}->{label} + linear combination as chi(k) ... done!");
1600 };
1601
1602
1603 sub lcf_plot_r {
1604 Echo("Plotting $groups{$current}->{label} + linear combination as |chi(R)| ... ");
1605 $groups{$current}->dispose("## Plotting linear combination of spectra as |chi(R)|\n", $dmode);
1606 my $rlp = $_[0];
1607 my $group = $groups{$current}->{group};
1608 my $yoff = $groups{$current}->{plot_yoffset};
1609 my ($kmin, $kmax) = ($$rlp{fitmin}, $$rlp{fitmax});
1610 $groups{$current}->plotR('rm', $dmode, \%plot_features, \@indicator);
1611 lcf_arrays_k(0);
1612 my $command = "(l___cf.mix, ";
1613 $command .= "k=$current.k, ",
1614 $command .= "kweight=0, ";
1615 $command .= "kmin=$groups{$current}->{fft_kmin}, ";
1616 $command .= "kmax=$groups{$current}->{fft_kmax}, ";
1617 $command .= "dk=$groups{$current}->{fft_dk}, ";
1618 $command .= "kwindow=$groups{$current}->{fft_win}, ";
1619 $command .= "group=l___cf, ";
1620 $command .= "rmax_out=$Ifeffit::Group::rmax_out";
1621 if (lc($groups{$current}->{fft_pc}) eq 'on') {
1622 my $str = join(" ", lc($groups{$current}->{bkg_z}), lc($groups{$current}->{fft_edge}));
1623 ($command .= ", pc_edge=\"$str\", pc_caps=1");
1624 };
1625 $command .= ")\n";
1626 $command = wrap("fftf", " ", $command);
1627 my $color = $config{plot}{'c1'};
1628 $command .= "plot(l___cf.r, \"l___cf.chir_mag+$yoff\", key=\"linear combo.\", style=lines, color=$color)\n";
1629 $groups{$current}->dispose($command, $dmode);
1630 };
1631
1632
1633 sub lcf_arrays_e {
1634 my $just_data = $_[0];
1635 my $group = $groups{$current}->{group};
1636 my $eshift = $groups{$current}->{bkg_eshift};
1637
1638 my $command .= "## Making arrays for fit in energy to $groups{$current}->{label}\n";
1639
1640 ## find longest common energy range in the marked groups.
1641 ## interpolate over this range. intrpolating just over the range of
1642 ## the first group might lead to extrapolation in other groups.
1643 my @ee = Ifeffit::get_array("$group.energy");
1644 my ($emin, $emax) = ($ee[0]+$eshift, $ee[-1]+$eshift);
1645 foreach my $i (1 .. $config{linearcombo}{maxspectra}) {
1646 next if ($$hash_pointer{"standard$i"} eq 'None');
1647 my $this = $$hash_pointer{"standard$i"};
1648 my $esh = sprintf("%.3f",$groups{$this}->{bkg_eshift});
1649 @ee = Ifeffit::get_array("$this.energy");
1650 my ($e1, $e2) = ($ee[0]+$esh, $ee[-1]+$esh);
1651 ($emin = $e1) if ($e1 > $emin);
1652 ($emax = $e2) if ($e2 < $emax);
1653 };
1654
1655 my $suff = ($groups{$current}->{bkg_flatten}) ? 'flat' : 'norm';
1656 ($suff = 'norm') if ($$hash_pointer{fitspace} eq 'd');
1657 my $function = ($$hash_pointer{fitspace} eq 'd') ? "deriv($group.$suff)/deriv($group.energy)" : "$group.$suff";
1658 if ($config{linearcombo}{energy} eq 'data') {
1659 $groups{$current}->dispose("set l___cf.eee = $group.energy+$eshift\n", $dmode);
1660 my @earray = Ifeffit::get_array("l___cf.eee");
1661 @earray = grep {($_ > $emin) and ($_ < $emax)} @earray;
1662 Ifeffit::put_array("l___cf.energy", \@earray);
1663 $command .= "set l___cf_npts = npts(l___cf.energy)\n";
1664 if ($$hash_pointer{noise} > 0) {
1665 $command .= "random(output=l___cf.noise, npts=l___cf_npts, dist=normal, sigma=$$hash_pointer{noise})\n"
1666 if $$hash_pointer{fitting}; # only regenerate noise for a new fit
1667 $command .= "set l___cf.data = splint(l___cf.eee, $function, l___cf.energy) + l___cf.noise\n";
1668 } else {
1669 $command .= "set l___cf.data = splint(l___cf.eee, $function, l___cf.energy)\n";
1670 };
1671 } else {
1672 my @en = Ifeffit::get_array("$group.energy");
1673 ##my ($emin, $emax) = ($en[0]+$eshift, $en[-1]+$eshift);
1674 $command .= "set l___cf.energy = range($emin, $emax, $config{linearcombo}{grid})\n";
1675 $command .= "set l___cf_npts = npts(l___cf.energy)\n";
1676 $command .= "set l___cf.eee = $group.energy+$eshift\n";
1677 if ($$hash_pointer{noise} > 0) {
1678 $command .= "random(output=l___cf.noise, npts=l___cf_npts, dist=normal, sigma=$$hash_pointer{noise})\n"
1679 if $$hash_pointer{fitting};
1680 $command .= "set l___cf.data = splint(l___cf.eee, $function, l___cf.energy) + l___cf.noise\n";
1681 } else {
1682 $command .= "set l___cf.data = splint(l___cf.eee, $function, l___cf.energy)\n";
1683 };
1684 };
1685
1686 unless ($just_data) {
1687 $command .= "set l___cf.mix = zeros(l___cf_npts)\n";
1688 ## interpolate each standard onto the grid of the unknown, apply the
1689 ## appropriate weight and e0 shift
1690 foreach my $i (1 .. $config{linearcombo}{maxspectra}) {
1691 next if ($$hash_pointer{"standard$i"} eq 'None');
1692 my $w = $$hash_pointer{"value$i"};
1693 my $this = $$hash_pointer{"standard$i"};
1694 my $e = $$hash_pointer{"e0val$i"};
1695 my $esh = sprintf("%.3f",$groups{$this}->{bkg_eshift});
1696 my $suff = ($groups{$this}->{bkg_flatten}) ? 'flat' : 'norm';
1697 ($suff = 'norm') if ($$hash_pointer{fitspace} eq 'd');
1698 $groups{$this}->dispatch_bkg($dmode) if $groups{$this}->{update_bkg};
1699 my $function = ($$hash_pointer{fitspace} eq 'd') ? "deriv($this.$suff)/deriv($this.energy)" : "$this.$suff";
1700 $command .= "set l___cf.$i = $w*splint($this.energy+$esh+$e, $function, l___cf.energy)\n";
1701 $command .= "set l___cf.mix = l___cf.mix + l___cf.$i\n";
1702 };
1703 ## add on a linear offset, if appropriate
1704 if ($$hash_pointer{linear}) {
1705 $command .= "set l___cf.line = l___cf.theta*($$hash_pointer{slope}*($$hash_pointer{yint} + l___cf.energy-$$hash_pointer{enot}))\n";
1706 $command .= "set l___cf.mix = l___cf.mix + l___cf.line\n";
1707 };
1708 $command .= "set l___cf.diff = l___cf.data - l___cf.mix\n";
1709 };
1710
1711 $groups{$current}->dispose($command, $dmode);
1712 };
1713
1714 sub lcf_arrays_k {
1715 my $just_data = $_[0];
1716 my $group = $groups{$current}->{group};
1717 ##my $kw = $groups{$current}->{fft_kw};
1718 my $kw = $plot_features{kw};
1719 my $command .= "## Making arrays for fit in k to $groups{$current}->{label}\n";
1720 $command .= "set l___cf_npts = npts($group.k)\n";
1721 if ($$hash_pointer{noise} > 0) {
1722 $command .= "random(output=l___cf.noise, npts=l___cf_npts, dist=normal, sigma=$$hash_pointer{noise})\n";
1723 my $function = "($group.chi+l___cf.noise)*$group.k^$kw";
1724 $command .= "set l___cf.data = $function + l___cf.noise\n";
1725 } else {
1726 my $function = "$group.chi*$group.k^$kw";
1727 $command .= "set l___cf.data = $function\n";
1728 };
1729 unless ($just_data) {
1730 $command .= "set l___cf.mix = zeros(l___cf_npts)\n";
1731 foreach my $i (1 .. $config{linearcombo}{maxspectra}) {
1732 next if ($$hash_pointer{"standard$i"} eq 'None');
1733 my $this = $$hash_pointer{"standard$i"};
1734 my $value = $$hash_pointer{'value'.$i};
1735 my $key = $groups{$$hash_pointer{"standard$i"}}->{label};
1736 $groups{$this} -> dispatch_bkg($dmode) if ($groups{$this}->{update_bkg});
1737 ##$command .= "set l___cf.$i = $value*$this.chi*$this.k**$groups{$current}->{fft_kw}\n";
1738 $command .= "set l___cf.$i = $value*$this.chi*$this.k**$plot_features{kw}\n";
1739 $command .= "set l___cf.mix = l___cf.mix + l___cf.$i\n";
1740 #$groups{$current}->dispose($command, $dmode);
1741 };
1742 $command .= "set l___cf.diff = l___cf.resid\n";
1743 };
1744 $groups{$current}->dispose($command, $dmode);
1745 };
1746
1747 sub lcf_use_marked {
1748 my $rlp = $_[0];
1749 my $count = 0;
1750 foreach my $i (1 .. $config{linearcombo}{maxspectra}) {
1751 $$rlp{"standard$i"} = 'None';
1752 $$rlp{"standard_lab$i"} = '0: None';
1753 $$rlp{"value$i"} = 0;
1754 $$rlp{"delta_value$i"} = 0;
1755 $$rlp{"e0val$i"} = 0;
1756 $$rlp{"delta_e0val$i"} = 0;
1757 };
1758 MG: foreach my $k (&sorted_group_list) {
1759 next MG unless $marked{$k};
1760 next if ($k eq $current);
1761 ## need to make sure that the record type is appropriate for this fit
1762 next MG if $groups{$k}->{is_rsp};
1763 next MG if $groups{$k}->{is_qsp};
1764 next MG if $groups{$k}->{not_data};
1765 if ($$rlp{fitspace} eq 'k') {
1766 next MG if $groups{$k}->{is_xanes};
1767 } else {
1768 next MG if $groups{$k}->{is_chi};
1769 };
1770 ++$count;
1771 next if ($count > $config{linearcombo}{maxspectra});
1772 $$rlp{"standard$count"} = $k;
1773 $$rlp{"standard_lab$count"} = $groups{$k}->{lcf_menu_label};
1774 $groups{$current} -> MAKE("lcf_standard$count" => $k,
1775 "lcf_standard_lab$count" => $groups{$k}->{lcf_menu_label});
1776 };
1777 lcf_initialize($rlp, 2);
1778 };
1779
1780 sub lcf_results {
1781 my $rlp = $_[0];
1782 my $bg = $config{colors}{background};
1783 $widget{lcf_maxfit} -> configure(-foreground=>'black',
1784 -background=>$bg,
1785 -text=>"") unless $$rlp{doing_combinatorics};
1786 ## deal with project files from older versions of Athena's LCF dialog
1787 map {$groups{$current}->{"lcf_$_"} ||= 0} (qw(sumsqr rfact chisqr chinu nvarys ndata kw));
1788
1789 my $last_error = 0;
1790 my $how = "";
1791 SWITCH: {
1792 ($how = 'norm(E)'), last SWITCH if ($groups{$current}->{lcf_fitspace} eq 'e');
1793 ($how = 'deriv(E)'), last SWITCH if ($groups{$current}->{lcf_fitspace} eq 'd');
1794 ($how = 'chi(k)'), last SWITCH if ($groups{$current}->{lcf_fitspace} eq 'k');
1795 };
1796 my $report = sprintf("Fitting %s as $how from %.3f to %.3f\n", $groups{$current}->{label}, $groups{$current}->{lcf_fitmin}, $groups{$current}->{lcf_fitmax});
1797 $report .= " fit done use k-weight = $groups{$current}->{lcf_kw}\n" if ($groups{$current}->{lcf_fitspace} eq 'k');
1798 $report .= "\n";
1799
1800 my $variables = ($groups{$current}->{lcf_nvarys} > 1) ? 'variables' : 'variable';
1801 $report .= "Fit included $groups{$current}->{lcf_ndata} data points and $groups{$current}->{lcf_nvarys} $variables\n";
1802 $report .= sprintf("R-factor = %.6f\nchi-square = %.5f\nreduced chi-square = %.7f\n\n",
1803 $groups{$current}->{lcf_rfact},
1804 $groups{$current}->{lcf_chisqr},
1805 $groups{$current}->{lcf_chinu}
1806 );
1807
1808 if ($groups{$current}->{lcf_sumsqr} == 1) {$report .= "Uh oh! something went wrong with the sum of squares...\n"};
1809
1810 $report .= " group weight\n";
1811 $report .= "=======================================\n";
1812 my $is_neg = 0;
1813 foreach my $i (1 .. $config{linearcombo}{maxspectra}) {
1814 next unless (exists $groups{$current}->{"lcf_standard$i"});
1815 next if ($groups{$current}->{"lcf_standard$i"} eq 'None');
1816 $groups{$current}->{"lcf_value$i"} ||= 0;
1817 $groups{$current}->{"lcf_delta_value$i"} ||= 0;
1818 $report .= sprintf(" %-20s %5.3f(%5.3f)\n",
1819 $groups{$current}->{"lcf_standard_lab$i"},
1820 $groups{$current}->{"lcf_value$i"},
1821 $groups{$current}->{"lcf_delta_value$i"},);
1822 ++$is_neg if ($groups{$current}->{"lcf_value$i"} < 0 );
1823 };
1824
1825 unless ($groups{$current}->{lcf_fitspace} eq 'k') {
1826 $report .= "\n\n group e0 shift\n";
1827 $report .= "=======================================\n";
1828 foreach my $i (1 .. $config{linearcombo}{maxspectra}) {
1829 next unless (exists $groups{$current}->{"lcf_standard$i"});
1830 next if ($groups{$current}->{"lcf_standard$i"} eq 'None');
1831 $groups{$current}->{"lcf_e0val$i"} ||= 0;
1832 $groups{$current}->{"lcf_delta_e0val$i"} ||= 0;
1833 $report .= sprintf(" %-20s %6.3f(%6.3f)\n",
1834 $groups{$current}->{"lcf_standard_lab$i"},
1835 $groups{$current}->{"lcf_e0val$i"},
1836 $groups{$current}->{"lcf_delta_e0val$i"},
1837 );
1838 };
1839
1840 if ($groups{$current}->{lcf_linear}) {
1841 $report .= sprintf("\n\n with linear term %.3f(%.3f) + %.3g(%.3g) * (E-E0)\n",
1842 $groups{$current}->{lcf_yint},
1843 $groups{$current}->{lcf_delta_yint},
1844 $groups{$current}->{lcf_slope},
1845 $groups{$current}->{lcf_delta_slope},)
1846 };
1847 };
1848 $widget{lcf_text} -> delete('1.0', 'end');
1849 $widget{lcf_text} -> insert('end', $report, 'text');
1850
1851 ## error handling
1852
1853 my $red = $config{colors}{single};
1854 $groups{$current}->{lcf_fit_status} ||= 0;
1855 if ($groups{$current}->{lcf_fit_status} == 2) { # error bars not calculated
1856 $widget{lcf_maxfit} -> configure(-foreground=>$red,
1857 -background=>'white',
1858 -text=>"Fit returned a warning!") unless $$rlp{doing_combinatorics};
1859 my $addendum = "
1860 This fit flagged a warning -- probably that error bars
1861 could not be calculated. That is probably an indication
1862 that one or more of your standards are innapropriate for
1863 this fit.
1864
1865 ";
1866 $widget{lcf_text} -> insert('end', $/);
1867 $widget{lcf_text} -> insert('end', $addendum, 'error');
1868
1869 } elsif ($groups{$current}->{lcf_fit_status} > 2) { # something bad!
1870 $widget{lcf_maxfit} -> configure(-foreground=>$red,
1871 -background=>'white',
1872 -text=>"Fit returned an error!") unless $$rlp{doing_combinatorics};
1873 my $addendum = "
1874 This fit flagged a error. You will need to check the
1875 Ifeffit buffer for details. One possible cause is that
1876 the standards are inappropriate for this fit and that
1877 the maximum number of iterations in the fit was exceeded.
1878
1879 ";
1880 $widget{lcf_text} -> insert('end', $/);
1881 $widget{lcf_text} -> insert('end', $addendum, 'error');
1882 };
1883
1884 if ($groups{$current}->{lcf_100} and $groups{$current}->{lcf_nonneg} and $is_neg) {
1885 $widget{lcf_maxfit} -> configure(-foreground=>$red,
1886 -background=>'white',
1887 -text=>"Poorly constrained fit!") unless $$rlp{doing_combinatorics};
1888 my $addendum = "
1889 This fit yielded a negative weight. One or more
1890 of your standards are innapropriate for this fit
1891 and should be removed from the list.
1892
1893 ";
1894 $widget{lcf_text} -> insert('end', $/);
1895 $widget{lcf_text} -> insert('end', $addendum, 'error');
1896 };
1897
1898 };
1899
1900 ## prompt for a filename and write the report from the text box to
1901 ## that file
1902 sub lcf_report {
1903 my $path = $current_data_dir || Cwd::cwd;
1904 my $f = $groups{$current}->{label} . ".lcf";
1905 $f =~ s/ /_/g;
1906 my $types = [['Linear combination fits', '.lcf'], ['All files', '*']];
1907 my $file = $top -> getSaveFile(-filetypes=>$types,
1908 #(not $is_windows) ?
1909 # (-sortcmd=>sub{$Tk::FBox::a cmp $Tk::FBox::b}) : () ,
1910 -initialdir=>$path,
1911 -initialfile=>$f,
1912 -title => "Athena: Write linear combination fitting report");
1913 Echo("Not writing linear combination fit report"), return unless $file;
1914
1915 open F, ">".$file;
1916 foreach (split "\n", $widget{lcf_text}->get('1.0', 'end')) {
1917 print F "# ", $_, $/;
1918 };
1919 print F "# ", "-" x 40, $/;
1920 my $x = ($$hash_pointer{fitspace} eq 'k') ? "k" : "energy";
1921 print F "# ", " $x data fit residual";
1922 foreach my $i (1 .. $config{linearcombo}{maxspectra}) {
1923 next if ($$hash_pointer{"standard$i"} eq 'None');
1924 my $label = $groups{$$hash_pointer{"standard$i"}}->{label};
1925 $label =~ s/\s+/_/g;
1926 print F " ", $label;
1927 };
1928 print F $/;
1929
1930 if ($$hash_pointer{fitspace} eq 'k') {
1931 lcf_arrays_k(0);
1932 } else {
1933 lcf_arrays_e(0);
1934 };
1935
1936 my $group = $groups{$current}->{group};
1937 ## not flat, k-weight
1938 my $suff = ($groups{$current}->{bkg_flatten}) ? 'flat' : 'norm';
1939 ($suff = 'norm') if ($$hash_pointer{fitspace} eq 'd');
1940 ($suff = 'chi') if ($$hash_pointer{fitspace} eq 'k');
1941 my @x = Ifeffit::get_array("$group.$x");
1942 unless ($$hash_pointer{fitspace} eq 'k') {
1943 @x = Ifeffit::get_array("l___cf.energy");
1944 };
1945 my @data;
1946 if ($$hash_pointer{fitspace} eq 'd') {
1947 ##$groups{$current}->dispose("t___oss.y = deriv($group.$suff)/deriv($group.energy)\n", 1);
1948 $groups{$current}->dispose("t___oss.y = deriv(l___cf.data)/deriv(l___cf.energy)\n", 1);
1949 @data = Ifeffit::get_array("t___oss.y");
1950 $groups{$current}->dispose("erase t___oss.y\n", 1);
1951 } else {
1952 ##@data = Ifeffit::get_array("$group.$suff");
1953 @data = Ifeffit::get_array("l___cf.data");
1954 };
1955 my @fit = Ifeffit::get_array("l___cf.mix");
1956 my @diff = Ifeffit::get_array("l___cf.diff");
1957 my @components = ();
1958 foreach my $i (1 .. $config{linearcombo}{maxspectra}) {
1959 next if ($$hash_pointer{"standard$i"} eq 'None');
1960 my @this = Ifeffit::get_array("l___cf.$i");
1961 $components[$i] = \@this;
1962 };
1963 my $kw = -1 * $$hash_pointer{kw}; # remove the k-weighting from the fit
1964 foreach my $i (0 .. $#x) {
1965 if ($$hash_pointer{fitspace} eq 'k') {
1966 next if ($i==0);
1967 printf F " %.3f %.5f %.5f %.5f", $x[$i], $data[$i], $fit[$i]*$x[$i]**$kw, $diff[$i]*$x[$i]**$kw;
1968 foreach my $j (1 .. $config{linearcombo}{maxspectra}) {
1969 next if ($$hash_pointer{"standard$j"} eq 'None');
1970 printf F " %.5f", $components[$j]->[$i]*$x[$i]**$kw;
1971 };
1972 print F $/;
1973 } else {
1974 printf F " %.3f %.5f %.5f %.5f", $x[$i], $data[$i], $fit[$i], $diff[$i];
1975 foreach my $j (1 .. $config{linearcombo}{maxspectra}) {
1976 next if ($$hash_pointer{"standard$j"} eq 'None');
1977 printf F " %.5f", $components[$j]->[$i];
1978 };
1979 print F $/;
1980 };
1981 };
1982 close F;
1983 Echo("Wrote linear combination fit report to \"$file\"");
1984 };
1985
1986 sub lcf_marked_report {
1987 ## write the header information
1988 my $how = "";
1989 SWITCH: {
1990 ($how = 'norm(E)'), last SWITCH if ($$hash_pointer{fitspace} eq 'e');
1991 ($how = 'deriv(E)'), last SWITCH if ($$hash_pointer{fitspace} eq 'd');
1992 ($how = 'chi(k)'), last SWITCH if ($$hash_pointer{fitspace} eq 'k');
1993 };
1994 my $head = $groups{$current} -> project_header;
1995 $head =~ s/,/ /g;
1996 $head .= "# Linear combination fits to marked groups as $how$/";
1997 $head .= "# fit done use k-weight = $$hash_pointer{kw}$/" if ($$hash_pointer{fitspace} eq 'k');
1998 $head .= "# noise level: $$hash_pointer{noise}$/";
1999 $head .= "# values between 0 and 1: ";
2000 $head .= ($$hash_pointer{nonneg}) ? "yes" : "no";
2001 $head .= "$/";
2002 $head .= "# values sum to 1: ";
2003 $head .= ($$hash_pointer{100}) ? "yes" : "no";
2004 $head .= "$/";
2005 $head =~ s/^\#/\#,/g;
2006
2007 open F, ">".$groups{"Default Parameters"} -> find('athena', 'temp_lcf');
2008 print F $head;
2009
2010 ## write the column labels for the standards
2011 print F ",,,,,,,";
2012 foreach my $i (1..$config{linearcombo}{maxspectra}) {
2013 next if ($$hash_pointer{"standard$i"} eq 'None');
2014 print F ",", $$hash_pointer{"standard_lab$i"}, ",,,";
2015 };
2016 print F ",linear term,,,";
2017 print F $/;
2018
2019 ## write the column labels for the parameters
2020 print F "Group,R-factor,chi square,chi nu,nvar,ndata,fit min,fit max",
2021 ",value,+/-,e shift,+/-" x $$hash_pointer{nstandards},
2022 ",slope,+/-,y-intercept,+/-",
2023 $/;
2024
2025 ## loop through the marked groups
2026 foreach my $g (&sorted_group_list) {
2027 next unless $marked{$g};
2028 my $is_ok = 1;
2029 foreach my $i (1 .. $config{linearcombo}{maxspectra}) {
2030 $is_ok = 0 if ($g eq $$hash_pointer{"standard$i"});
2031 };
2032 next unless $is_ok;
2033 (my $label = $groups{$g}->{label}) =~ s/,//g;
2034 print F join(",",
2035 $label,
2036 $groups{$g}->{lcf_rfact},
2037 $groups{$g}->{lcf_chisqr},
2038 $groups{$g}->{lcf_chinu},
2039 $groups{$g}->{lcf_nvarys},
2040 $groups{$g}->{lcf_ndata},
2041 $groups{$g}->{lcf_fitmin},
2042 $groups{$g}->{lcf_fitmax},
2043 );
2044 foreach my $i (1..$config{linearcombo}{maxspectra}) {
2045 next if ($$hash_pointer{"standard$i"} eq 'None');
2046 print F join(",", q{},
2047 $groups{$g}->{"lcf_value$i"},
2048 $groups{$g}->{"lcf_delta_value$i"});
2049 if ($$hash_pointer{fitspace} eq 'k') {
2050 print F ",0,0";
2051 } else {
2052 print F join(",", q{},
2053 $groups{$g}->{"lcf_e0val$i"},
2054 $groups{$g}->{"lcf_delta_e0val$i"});
2055 };
2056 };
2057 if ($$hash_pointer{fitspace} eq 'k') {
2058 print F ",0,0,0,0";
2059 } else {
2060 print F join(",", q{},
2061 $groups{$g}->{"lcf_slope"},
2062 $groups{$g}->{"lcf_delta_slope"},
2063 $groups{$g}->{"lcf_yint"},
2064 $groups{$g}->{"lcf_delta_yint"},
2065 );
2066 };
2067 print F $/;
2068 };
2069 close F;
2070 };
2071
2072 sub lcf_save_marked_report {
2073 Error("You have not made a marked groups fit!"), return unless (-e $groups{"Default Parameters"}->find('athena', 'temp_lcf'));
2074 my $path = $current_data_dir || Cwd::cwd;
2075 my $f = "lcf_marked.csv";
2076 my $types = [['Comma separated values', '.csv'], ['All files', '*']];
2077 my $file = $top -> getSaveFile(-filetypes=>$types,
2078 #(not $is_windows) ?
2079 # (-sortcmd=>sub{$Tk::FBox::a cmp $Tk::FBox::b}) : () ,
2080 -initialdir=>$path,
2081 -initialfile=>$f,
2082 -title => "Athena: Write marked groups fitting report");
2083 Echo("Not writing marked groups fit report"), return unless $file;
2084 copy($groups{"Default Parameters"}->find('athena', 'temp_lcf'), $file);
2085 Echo("Saved marked fit report as \"$file\"");
2086 };
2087
2088 sub lcf_csv_report {
2089
2090 my $path = $current_data_dir || Cwd::cwd;
2091 my $f = $groups{$current}->{label} . "_lcf.csv";
2092 $f =~ s/ /_/g;
2093 my $types = [['Comma separated values', '.csv'], ['All files', '*']];
2094 my $file = $top -> getSaveFile(-filetypes=>$types,
2095 #(not $is_windows) ?
2096 # (-sortcmd=>sub{$Tk::FBox::a cmp $Tk::FBox::b}) : () ,
2097 -initialdir=>$path,
2098 -initialfile=>$f,
2099 -title => "Athena: Write linear combination fitting report");
2100 Echo("Not writing linear combination fit report"), return unless $file;
2101
2102 my @order = $widget{lcf_result_table}->info('children');
2103 my @labels = map {$groups{$_}->{label}} @order;
2104 push(@labels, 'linear term') if ($$hash_pointer{linear});
2105
2106 my $how = "";
2107 SWITCH: {
2108 ($how = 'norm(E)'), last SWITCH if ($$hash_pointer{fitspace} eq 'e');
2109 ($how = 'deriv(E)'), last SWITCH if ($$hash_pointer{fitspace} eq 'd');
2110 ($how = 'chi(k)'), last SWITCH if ($$hash_pointer{fitspace} eq 'k');
2111 };
2112 my $head = $groups{$current} -> project_header;
2113 $head =~ s/,/ /g;
2114 $head .= sprintf("# Linear combination fits to %s as $how\n", $groups{$current}->{label});
2115 $head .= "# fit done use k-weight = $$hash_pointer{kw}\n" if ($$hash_pointer{fitspace} eq 'k');
2116
2117 open F, ">".$file;
2118 print F $head;
2119 print F "," x 13, join(",,,,", @labels), $/;
2120 my $n = $#labels+1;
2121 print F "R-factor,chisqr,chinu,fit_status,Nvar,Ndata,fit_min,fit_max,,y_intercept,delta_y_intercept,slope,delta_slope" .
2122 ",weight,delta_weight,e0,delta_e0" x $n . $/;
2123
2124 my @all = $widget{lcf_select_table}->info('children');
2125 foreach my $i (@all) {
2126 $widget{lcf_select_table} -> selectionClear;
2127 $widget{lcf_select_table} -> selectionSet($i);
2128 my $data = $widget{lcf_select_table}->info('data', $i);
2129 $data =~ s/^[^\|]*\|//;
2130 $data =~ s/\|/,/g;
2131 print F $data, $/;
2132 };
2133 close F;
2134 $widget{lcf_select_table} -> selectionClear;
2135 $widget{lcf_select_table} -> selectionSet(0);
2136 $$hash_pointer{toggle} = 1;
2137 lcf_fill_result(\@order, $hash_pointer, 1, 0);
2138 Echo("Wrote linear combination fit report to \"$file\"");
2139 };
2140
2141
2142 ## make a new data group out of the best fit function. make this a
2143 ## detector group so it can only be plotted in E
2144 sub lcf_group {
2145 my $rlp = $_[0];
2146 my $array = $_[1];
2147 my $group = $groups{$current}->{group};
2148 my $name = ($array eq "fit") ? "LCF " : "LCF diff ";
2149 my ($new, $label) = group_name($name . $groups{$current}->{label});
2150 $groups{$new} = Ifeffit::Group -> new(group=>$new, label=>$label);
2151 $groups{$new} -> set_to_another($groups{$group});
2152 if ($$rlp{fitspace} eq 'k') {
2153 $groups{$new} -> MAKE(is_xmu => 0, is_chi => 1, is_rsp => 0,
2154 is_qsp => 0, is_bkg => 0,
2155 not_data => 0,
2156 file => $$rlp{filestring});
2157 } else {
2158 $groups{$new} -> MAKE(is_xmu => 1, is_chi => 0, is_rsp => 0,
2159 is_qsp => 0, is_bkg => 0, is_nor => 1,
2160 not_data => 0, bkg_flatten => 0,
2161 file => $$rlp{filestring});
2162 $groups{$new} -> MAKE(bkg_e0 => $groups{$group}->{bkg_e0});
2163 };
2164 $groups{$new}->{titles} = [];
2165 my $text = $widget{lcf_text} -> get(qw(1.0 end));
2166 ## see refresh_titles for explanation
2167 foreach (split(/\n/, $text)) {
2168 next if ($_ =~ /^\s*$/);
2169 my $count = 0;
2170 foreach my $i (0..length($_)) {
2171 ++$count if (substr($_, $i, 1) eq '(');
2172 --$count if ($count and (substr($_, $i, 1) eq ')'));
2173 };
2174 $_ .= ')' x $count;
2175 push @{$groups{$new}->{titles}}, $_;
2176 };
2177 $groups{$new} -> put_titles;
2178 my $which = ($array eq "fit") ? "mix" : "diff";
2179 if ($$rlp{fitspace} eq 'k') {
2180 lcf_arrays_k(0);
2181 my $kw = -1 * $$rlp{kw}; # remove the k-weighting from the fit
2182 $groups{$new} -> dispose("set $new.k = $group.k", $dmode);
2183 $groups{$new} -> dispose("set $new.chi = l___cf.$which*$group.k^$kw", $dmode);
2184 } else {
2185 my $was = $$rlp{fitspace};
2186 $$rlp{fitspace} = 'e';
2187 lcf_arrays_e(0);
2188 $$rlp{fitspace} = $was;
2189 ##$groups{$new} -> dispose("set $new.energy = $group.energy + " . $groups{$group}->{bkg_eshift}, $dmode);
2190 $groups{$new} -> dispose("set $new.energy = l___cf.energy", $dmode);
2191 $groups{$new} -> dispose("set $new.xmu = l___cf.$which", $dmode);
2192 };
2193 ++$line_count;
2194 fill_skinny($list, $new, 1, 1);
2195 my $memory_ok = $groups{$new}
2196 -> memory_check($top, \&Echo, \%groups, $max_heap, 0, 0);
2197 Echo("WARNING: Ifeffit is out of memory!"), return if ($memory_ok == -1);
2198 Echo("Saved linear combination fit as a new data group");
2199 };
2200
2201 ## restore all the widgets except the optionmenus to their original
2202 ## state
2203 sub lcf_reset {
2204 my $rlp = $_[0];
2205 my $skip_toggles= $_[1];
2206 my $bg = $config{colors}{background};
2207 $widget{lcf_maxfit} -> configure(-foreground=>'black',
2208 -background=>$bg,
2209 -text=>"") unless $$rlp{doing_combinatorics};
2210 $groups{$current}->dispose("\n## reseting the LCF parameters:\n");
2211 $widget{lcf_text} -> delete(qw(1.0 end));
2212 unless ($skip_toggles) {
2213 $widget{lcf_nonneg} -> select;
2214 $widget{lcf_linear} -> deselect;
2215 $widget{lcf_100} -> select;
2216 $widget{lcf_e0all} -> deselect;
2217 };
2218 lcf_initialize($rlp, 2);
2219 foreach my $i (1 .. $config{linearcombo}{maxspectra}) {
2220 unless ($skip_toggles) {
2221 $$rlp{"e0$i"} = $config{linearcombo}{fite0};
2222 $$rlp{"e0val$i"} = 0;
2223 };
2224 $$rlp{"delta_e0val$i"} = 0;
2225 };
2226 $$rlp{req} = q{};
2227 $$rlp{slope} = 0;
2228 $$rlp{delta_slope} = 0;
2229 $$rlp{yint} = 0;
2230 $$rlp{delta_yint} = 0;
2231 $groups{$current}->dispose("unguess\n");
2232 #$groups{$current}->dispose("erase \@group l___cf\n");
2233 };
2234
2235 sub lcf_pluck{
2236 my $rlp = $_[0];
2237 my $which = $_[1];
2238 my $e0 = $groups{$current}->{bkg_e0};
2239 my $how = ($$rlp{fitspace} eq 'k') ? 'k' : 'e';
2240 &pluck("lcf_$which", 0, $how);
2241 my $e = $widget{"lcf_$which"}->get();
2242 if (($$rlp{fitspace} =~ /[ed]/) and ($last_plot eq 'e')) {
2243 $e = $e-$e0;
2244 } elsif (($$rlp{fitspace} =~ /[ed]/) and ($last_plot eq 'k')) {
2245 $e = $groups{$current}->k2e($e);
2246 } elsif (($$rlp{fitspace} eq 'k') and ($last_plot eq 'e')) {
2247 $e = $groups{$current}->e2k($e);
2248 } elsif (($$rlp{fitspace} eq 'k') and ($last_plot eq 'k')) {
2249 1;
2250 };
2251 $e = sprintf("%.3f", $e);
2252 $widget{"lcf_$which"}->delete(0, 'end');
2253 $widget{"lcf_$which"}->insert(0, $e);
2254 if ($$rlp{fitspace} eq 'k') {
2255 my $key = join("_", "lcf", $which, "k");
2256 $groups{$current}->MAKE($key => $e);
2257 } else {
2258 my $key = join("_", "lcf", $which, "e");
2259 $groups{$current}->MAKE($key => $e);
2260 };
2261 };
2262
2263 ## compute an r-factor and generate a couple of lines containing the
2264 ## basic fitting statistics
2265 sub lcf_statistics {
2266 my $rlp = $_[0];
2267 my $group = $groups{$current}->{group};
2268 my ($emin, $emax, @x, @y, @z);
2269 if ($$rlp{fitspace} eq 'e') {
2270 my $suff = ($groups{$current}->{bkg_flatten}) ? 'flat' : 'norm';
2271 ($emin, $emax) = ($$rlp{enot}+$$rlp{fitmin},
2272 $$rlp{enot}+$$rlp{fitmax});
2273 @x = Ifeffit::get_array("l___cf.energy");
2274 @z = Ifeffit::get_array("l___cf.data");
2275 } elsif ($$rlp{fitspace} eq 'd') {
2276 ($emin, $emax) = ($$rlp{enot}+$$rlp{fitmin},
2277 $$rlp{enot}+$$rlp{fitmax});
2278 @x = Ifeffit::get_array("l___cf.energy");
2279 @z = Ifeffit::get_array("l___cf.data");
2280 } else {
2281 ($emin, $emax) = ($$rlp{fitmin},$$rlp{fitmax});
2282 @x = Ifeffit::get_array("$group.k");
2283 @z = Ifeffit::get_array("$group.chi");
2284 };
2285 @y = Ifeffit::get_array("l___cf.resid");
2286 my ($sumsqr, $npts, $rfact) = (0, 0, 0);
2287 foreach my $i (0 .. $#x) {
2288 next if $x[$i] < $emin;
2289 next if $x[$i] > $emax;
2290 last if $i > $#z;
2291 ++$npts;
2292 $rfact += $y[$i]**2;
2293 if ($$rlp{fitspace} =~ /[ed]/) {
2294 $sumsqr += $z[$i]**2;
2295 } else {
2296 $sumsqr += ($z[$i]*$x[$i]**$$rlp{kw})**2;
2297 };
2298 };
2299 $sumsqr ||= 1;
2300 $rfact /= $sumsqr;
2301 $$rlp{sumsqr} = $sumsqr;
2302 $$rlp{rfact} = $rfact;
2303 $$rlp{chisqr} = Ifeffit::get_scalar("chi_square");
2304 $$rlp{chinu} = Ifeffit::get_scalar("chi_reduced");
2305 $$rlp{nvarys} = Ifeffit::get_scalar("n_varys");
2306 $$rlp{ndata} = $npts;
2307 ## also save a group data
2308 $groups{$current}->{lcf_sumsqr} = $sumsqr;
2309 $groups{$current}->{lcf_rfact} = $rfact;
2310 $groups{$current}->{lcf_chisqr} = Ifeffit::get_scalar("chi_square");
2311 $groups{$current}->{lcf_chinu} = Ifeffit::get_scalar("chi_reduced");
2312 $groups{$current}->{lcf_nvarys} = Ifeffit::get_scalar("n_varys");
2313 $groups{$current}->{lcf_ndata} = $npts;
2314 };
2315
2316
2317 sub lcf_combinatorics {
2318 my $rlp = $_[0];
2319 Echo("Combinatorial fitting ...");
2320 if ($$rlp{fitspace} eq 'k') {
2321 $$rlp{fitmin_k} = $$rlp{fitmin};
2322 $$rlp{fitmax_k} = $$rlp{fitmax};
2323 } else {
2324 $$rlp{fitmin_e} = $$rlp{fitmin};
2325 $$rlp{fitmax_e} = $$rlp{fitmax};
2326 };
2327 my @save = ();
2328 my @standards = ();
2329 my @order = ();
2330 foreach my $i (1 .. $config{linearcombo}{maxspectra}) {
2331 push(@order, $$rlp{"standard".$i});
2332 push(@standards, $$rlp{"standard".$i}) unless ($$rlp{"standard".$i} eq 'None');
2333 $save[$i] = $$rlp{"standard".$i};
2334 ##$$rlp{"standard".$i} = 'None';
2335 };
2336 my @biglist = ();
2337 my $req_save = $$rlp{req};
2338 my $required = ($$rlp{req}) ? $$rlp{"standard".$$rlp{req}} : q{};
2339 foreach my $n (2 .. $#standards+1) {
2340 last if ($n > $$rlp{maxstan});
2341 my $combinat = Math::Combinatorics->new(count => $n,
2342 data => \@standards,
2343 );
2344 while (my @combo = $combinat->next_combination) {
2345 my $stringified = join(" ", @combo);
2346 ##print ">$required< $stringified\n";
2347 next if ($required and not ($stringified =~ /$required/));
2348 push @biglist, \@combo;
2349 };
2350 };
2351
2352 if ($#biglist > 50) {
2353 my ($n, $ns, $ms) = ($#biglist+1, $#standards+1, $$rlp{maxstan});
2354 my $message = "You have asked that $n fits be performed ($ns possible standards with each fit using up to $ms of them). That will take some time. Do you want to continue?";
2355 my $dialog =
2356 $top -> Dialog(-bitmap => 'questhead',
2357 -text => $message,
2358 -title => 'Athena: Start fitting?',
2359 -buttons => ['Continue', 'Abort'],
2360 -default_button => 'Continue',);
2361 my $response = $dialog->Show();
2362 Echo("Combinatorial fitting ... aborted!"), return if ($response eq 'Abort');
2363 };
2364 $top -> Busy;
2365 my @results;
2366 $$rlp{iterator} = 0;
2367 $$rlp{doing_combinatorics} = 1;
2368 my $orange = $config{colors}{current};
2369 my $blue = $config{colors}{activehighlightcolor};
2370 $widget{lcf_maxfit} -> configure(-foreground=>$blue,
2371 -background=>$orange);
2372 my $nbl = $#biglist + 1;
2373 tie my $timer, 'Time::Stopwatch';
2374 foreach my $l (@biglist) {
2375 #map {print("$groups{$_}->{label} ")} @$l;
2376 #print $/;
2377
2378 my $i = 1;
2379 foreach my $s (@order) {
2380 if (grep(/$s/, @$l)) {
2381 $$rlp{"standard".$i} = $s;
2382 $$rlp{"standard_lab$i"} = $groups{$s}->{lcf_menu_label};
2383 } else {
2384 $$rlp{"standard".$i} = 'None';
2385 $$rlp{"standard_lab$i"} = '0: None';
2386 };
2387 ++$i;
2388 };
2389 lcf_reset($rlp,1);
2390 $$rlp{req} = $req_save;
2391 $top -> update;
2392
2393 ++$$rlp{iterator};
2394 $widget{lcf_maxfit} -> configure(-text=>"fit $$rlp{iterator} of $nbl");
2395 ## run this fit
2396 lcf_fit($rlp, 0);
2397 $$rlp{fit_status} = Ifeffit::get_scalar('&status');
2398
2399 ## store the results of this fit
2400 my @this = ();
2401 push @this, join(",", @$l), $$rlp{rfact}, $$rlp{chisqr}, $$rlp{chinu}, $$rlp{fit_status}, $$rlp{nvarys},
2402 $$rlp{ndata}, $$rlp{fitmin}, $$rlp{fitmax}, 0,
2403 $$rlp{yint}, $$rlp{delta_yint}, $$rlp{slope}, $$rlp{delta_slope};
2404 foreach my $i (1 .. $config{linearcombo}{maxspectra}) {
2405 push @this, $$rlp{"value".$i}, $$rlp{"delta_value".$i}, $$rlp{"e0val".$i}, $$rlp{"delta_e0val".$i};
2406 };
2407 push @results, \@this;
2408 };
2409 my $elapsed = $timer;
2410 undef $timer;
2411 $elapsed = sprintf("%d fits in %.0f min, %.0f sec", $nbl, $elapsed/60, $elapsed%60);
2412 $$rlp{doing_combinatorics} = 0;
2413 $$rlp{fit_status} = 0;
2414 $$rlp{req} = $req_save;
2415 $groups{$current} -> dispose("set &status = 0\n", $dmode);
2416
2417 ## sort by increasing R-factor
2418 @results = sort {$a->[1] <=> $b->[1]} @results;
2419 $lcf_data{$current}{order} = \@order;
2420 $lcf_data{$current}{results} = \@results;
2421 my $brown = $config{colors}{background};
2422 $widget{lcf_maxfit} -> configure(-text=>"", -background=>$brown);
2423
2424 lcf_display();
2425
2426 $widget{lcf_combo_group} -> configure(-text=>"Fits to \"$groups{$current}->{label}\" with up to $$rlp{maxstan} standards");
2427 $top -> Unbusy;
2428 Echo("Combinatorial fitting ... done! (Displaying and plotting the best fit.) ($elapsed)");
2429 };
2430
2431
2432 sub lcf_display {
2433
2434 my @results = @{ $lcf_data{$current}{results} };
2435 my @order = @{ $lcf_data{$current}{order} };
2436 ## need to translate between the integers in the result table and
2437 ## the groups used in the fit
2438 my %names;
2439 $names{$order[$_]} = $_+1 foreach (0 .. $#order);
2440
2441
2442 ## empty out both tables
2443 $widget{lcf_select_table}->delete('all');
2444 $widget{lcf_result_table}->delete('all');
2445 my $j = 0;
2446 my $combo_selected = $j;
2447 ## fill the select table with all these fits
2448 foreach (@results) {
2449 $widget{lcf_select_table}->add($j, -data=>join("|", @$_));
2450 #my @these = split(/,/, $_->[0]);
2451 #print join(" ", @these, $_->[1]), $/;
2452 (my $text = $_->[0]) =~ s/([a-z]{4})/$names{$1}/g;
2453 $text = join(",", sort {$a <=> $b} ( split(/,/, $text))); # sort the indeces
2454 $widget{lcf_select_table}->itemCreate($j, 0, -itemtype=>'text', -text=>$text);
2455 $widget{lcf_select_table}->itemCreate($j, 1, -itemtype=>'text', -text=>sprintf("%.7g",$_->[1]));
2456 $widget{lcf_select_table}->itemCreate($j, 2, -itemtype=>'text', -text=>sprintf("%.7g",$_->[3]));
2457 ++$j;
2458 };
2459 ## fill the results table
2460 my $k = 1;
2461 foreach my $s (@order) {
2462 next if ($s eq 'None');
2463 $widget{lcf_result_table}->add($s);
2464 $widget{lcf_result_table}->itemCreate($s, 0, -itemtype=>'text', -text=>$k);
2465 $widget{lcf_result_table}->itemCreate($s, 1, -itemtype=>'text', -text=>$groups{$s}->{label});
2466 my $v = 6+4*$k;
2467 $widget{lcf_result_table}->itemCreate($s, 2, -itemtype=>'text',
2468 -text=>sprintf("%.3f (%.3f)", $results[0]->[$v], $results[0]->[$v+1]));
2469 $widget{lcf_result_table}->itemCreate($s, 3, -itemtype=>'text',
2470 -text=>sprintf("%.3f (%.3f)", $results[0]->[$v+2], $results[0]->[$v+3]));
2471 ++$k;
2472 };
2473 if ($$hash_pointer{linear}) {
2474 $widget{lcf_result_table}->add('linear');
2475 $widget{lcf_result_table}->itemCreate('linear', 1, -itemtype=>'text', -text=>'linear term');
2476 $widget{lcf_result_table}->itemCreate('linear', 2, -itemtype=>'text',
2477 -text=>sprintf("%.3f (%.3f)", $$hash_pointer{yint}, $$hash_pointer{delta_yint}));
2478 $widget{lcf_result_table}->itemCreate('linear', 3, -itemtype=>'text',
2479 -text=>sprintf("%.6f (%.6f)", $$hash_pointer{slope}, $$hash_pointer{delta_slope}));
2480 };
2481
2482 @order = $widget{lcf_result_table}->info('children');
2483 $widget{lcf_select_table} -> configure(-browsecmd=>sub{lcf_fill_result(\@order, $hash_pointer, 1)});
2484 $widget{lcf_select_table} -> selectionSet(0);
2485 $widget{lcf_select_table} -> anchorSet(0);
2486 $$hash_pointer{toggle} = 1;
2487 lcf_fill_result(\@order, $hash_pointer, 1, 0);
2488 $widget{lcf_combo_group} -> configure(-text=>"Fits to \"$groups{$current}->{label}\"");
2489 $widget{lcf_notebook} -> pageconfigure('combinatorics', -state=>'normal');
2490 $widget{lcf_notebook} -> raise('combinatorics');
2491 };
2492
2493 sub lcf_fill_result {
2494 #print join(" ", @_), $/;
2495 my ($rorder, $rlp, $plot, $j) = @_;
2496 $$rlp{toggle} = not $$rlp{toggle};
2497 return if $$rlp{toggle}; # only on the release
2498 $j = $widget{lcf_select_table} -> selectionGet();
2499 my $data = $widget{lcf_select_table} -> info('data', $j);
2500 my @list = split(/\|/, $data);
2501 my $i = 0;
2502 ##my %local = ();
2503 foreach my $s (@$rorder) {
2504 ++$i;
2505 if ($s eq 'None') {
2506 $$rlp{"standard$i"} = 'None';
2507 $$rlp{"standard_lab$i"} = '0: None';
2508 $$rlp{"value$i"} = 0;
2509 $$rlp{"delta_value$i"} = 0;
2510 $$rlp{"e0val$i"} = 0;
2511 $$rlp{"delta_e0val$i"} = 0;
2512 next;
2513 };
2514 ## fill the other two tabs
2515 if ($list[0] =~ /$s/) {
2516
2517 my $ii = 0;
2518 foreach my $ke (@{$$rlp{keys}}) {
2519 next if ($ke eq 'None');
2520 ++$ii;
2521 last if ($ke eq $s);
2522 };
2523 $$rlp{"standard$i"} = $s;
2524 $$rlp{"standard_lab$i"} = $groups{$s}->{lcf_menu_label};
2525
2526 my ($v, $w) = (10+4*$i, 11+4*$i);
2527 $widget{lcf_result_table}->itemConfigure($s, 2,
2528 -text=>sprintf("%.3f (%.3f)", $list[$v]||0, $list[$w]||0));
2529 $$rlp{"value$i"} = $list[$v];
2530 $$rlp{"delta_value$i"} = $list[$w];
2531
2532 ($v, $w) = (12+4*$i, 13+4*$i);
2533 $widget{lcf_result_table}->itemConfigure($s, 3,
2534 -text=>sprintf("%.3f (%.3f)", $list[$v]||0, $list[$w]||0));
2535 $$rlp{"e0val$i"} = $list[$v];
2536 $$rlp{"delta_e0val$i"} = $list[$w];
2537
2538 } else {
2539
2540 $widget{lcf_result_table}->itemConfigure($s, 2, -text=>" ");
2541 $widget{lcf_result_table}->itemConfigure($s, 3, -text=>" ");
2542
2543 $$rlp{"standard$i"} = 'None';
2544 $$rlp{"standard_lab$i"} = '0: None';
2545 $$rlp{"value$i"} = 0;
2546 $$rlp{"delta_value$i"} = 0;
2547 $$rlp{"e0val$i"} = 0;
2548 $$rlp{"delta_e0val$i"} = 0;
2549 };
2550 $groups{$current} -> MAKE("lcf_standard$i" => $$rlp{"standard$i"},
2551 "lcf_standard_lab$i" => $$rlp{"standard_lab$i"},
2552 "lcf_value$i" => $$rlp{"value$i"},
2553 "lcf_delta_value$i" => $$rlp{"delta_value$i"},
2554 "lcf_e0val$i" => $$rlp{"e0val$i"},
2555 "lcf_delta_e0val$i" => $$rlp{"delta_e0val$i"},
2556 );
2557 };
2558 ## fill up stats and others
2559 $$rlp{rfact} = $list[1];
2560 $$rlp{chisqr} = $list[2];
2561 $$rlp{chinu} = $list[3];
2562 $$rlp{fit_status} = $list[4];
2563 $$rlp{nvarys} = $list[5];
2564 $$rlp{ndata} = $list[6];
2565 if ($$rlp{linear}) {
2566 $widget{lcf_result_table}->itemConfigure('linear', 2,
2567 -text=>sprintf("%.3f (%.3f)", $list[10], $list[11]));
2568 $widget{lcf_result_table}->itemConfigure('linear', 3,
2569 -text=>sprintf("%.6f (%.6f)", $list[12], $list[13]));
2570 };
2571
2572 $groups{$current} -> MAKE(lcf_rfact => $list[1],
2573 lcf_chisqr => $list[2],
2574 lcf_chinu => $list[3],
2575 lcf_fit_status => $list[4],
2576 lcf_nvarys => $list[5],
2577 lcf_ndata => $list[6],
2578 lcf_fitmin => $list[7],
2579 lcf_fitmax => $list[8],
2580 lcf_yint => $list[10],
2581 lcf_delta_yint => $list[11],
2582 lcf_slope => $list[12],
2583 lcf_delta_slope => $list[13],
2584 );
2585
2586
2587 $top -> update;
2588 $widget{lcf_operations} -> entryconfigure(1, -state=>'normal', -style=>$$rlp{normal_style});
2589 $widget{lcf_operations} -> entryconfigure(3, -state=>'normal', -style=>$$rlp{normal_style});
2590 $widget{lcf_operations} -> entryconfigure(4, -state=>'normal', -style=>$$rlp{normal_style});
2591 $widget{lcf_operations} -> entryconfigure(7, -state=>'normal', -style=>$$rlp{normal_style})
2592 if ($$rlp{fitspace} eq 'k');
2593 if ($plot) {
2594 if ($$rlp{fitspace} eq 'k') { lcf_arrays_k(0) } else { lcf_arrays_e() };
2595 lcf_results($rlp);
2596 lcf_plot($rlp);
2597 };
2598 };
2599
2600
2601 sub lcf_post_menu {
2602
2603 ## figure out where the user clicked
2604 my $w = shift;
2605 my $Ev = $w->XEvent;
2606 delete $w->{'shiftanchor'};
2607 my $entry = $w->GetNearest($Ev->y, 1);
2608 return unless (defined($entry) and length($entry));
2609
2610 ## select and anchor the right-clicked parameter
2611 #$w->selectionClear;
2612 $w->anchorSet($entry);
2613 #$w->selectionSet($entry);
2614
2615 #my @order = $widget{lcf_result_table}->info('children');
2616 #$$hash_pointer{toggle} = 1;
2617 #lcf_fill_result(\@order, $hash_pointer, 1);
2618
2619
2620 ## post the message with parameter-appropriate text
2621 my $which = $w->info('anchor');
2622 $which = (ref($which) eq 'ARRAY') ? $$which[0] : $which;
2623 my $id = $widget{lcf_select_table}->itemCget($entry, 0, '-text');
2624 my ($X, $Y) = ($Ev->X, $Ev->Y);
2625 $top ->
2626 Menu(-tearoff=>0,
2627 -menuitems=>[[ command=>"Write column data file for fit using $id",
2628 -command=>sub{$top->Busy;
2629 $w->selectionClear;
2630 $w->selectionSet($entry);
2631 my @order = $widget{lcf_result_table}->info('children');
2632 $$hash_pointer{toggle} = 1;
2633 lcf_fill_result(\@order, $hash_pointer, 1);
2634 &lcf_save_fit;
2635 $top->Unbusy;}
2636 ],
2637 [ command=>"Make data group for fit using $id",
2638 -command=>sub{$top->Busy;
2639 $w->selectionClear;
2640 $w->selectionSet($entry);
2641 my @order = $widget{lcf_result_table}->info('children');
2642 $$hash_pointer{toggle} = 1;
2643 lcf_fill_result(\@order, $hash_pointer, 1);
2644 &lcf_group($hash_pointer);
2645 $top->Unbusy;},
2646 ],
2647 [ command=>"Write report for fit using $id",
2648 -command=>sub{$top->Busy;
2649 $w->selectionClear;
2650 $w->selectionSet($entry);
2651 my @order = $widget{lcf_result_table}->info('children');
2652 $$hash_pointer{toggle} = 1;
2653 lcf_fill_result(\@order, $hash_pointer, 1);
2654 &lcf_report;
2655 $top->Unbusy;}
2656 ],
2657 "-",
2658 [ command=>"Write CSV report for all fits",
2659 -command=>\&lcf_csv_report,
2660 ],
2661 ])
2662 -> Post($X, $Y);
2663 $w -> break;
2664 };
2665
2666
2667 sub lcf_save_fit {
2668 my $path = $current_data_dir || Cwd::cwd;
2669 my $id = $widget{lcf_select_table} -> itemCget($widget{lcf_select_table}->selectionGet, 0, "-text");
2670 $id =~ s/,/_/g;
2671 my $f = $groups{$current}->{label} . ".fit_$id";
2672 $f =~ s/ /_/g;
2673 my $types = [['Comma separated values', '.csv'], ['All files', '*']];
2674 my $file = $top -> getSaveFile(-filetypes=>$types,
2675 #(not $is_windows) ?
2676 # (-sortcmd=>sub{$Tk::FBox::a cmp $Tk::FBox::b}) : () ,
2677 -initialdir=>$path,
2678 -initialfile=>$f,
2679 -title => "Athena: Write linear combination fitting result");
2680 Echo("Not writing linear combination fit result file"), return unless $file;
2681
2682 if ($$hash_pointer{fitspace} eq 'k') { lcf_arrays_k(0) } else { lcf_arrays_e() };
2683
2684 refresh_titles($groups{$current}); # make sure titles are up-to-date
2685 $groups{$current}->dispose("\$id_line_1 = \"Athena data file -- Athena version $VERSION\"", $dmode);
2686 $groups{$current}->dispose("\$id_line_2 = \"Saving LCF fit to $groups{$current}->{label}\"", $dmode);
2687 my $n = 3;
2688
2689 my $arrays = "l___cf.mix, l___cf.diff";
2690 foreach my $i (1 .. $config{linearcombo}{maxspectra}) {
2691 next if ($$hash_pointer{"standard$i"} eq 'None');
2692 my $line = "\$id_line_$n = \"~ $i: " . $$hash_pointer{"standard_lab$i"} . "\"";
2693 $groups{$current}->dispose($line, $dmode);
2694 $arrays .= ", l___cf.$i";
2695 ++$n;
2696 };
2697 $groups{$current}->dispose("\$id_line_$n = \"~\"\n", $dmode);
2698 my $i = 0;
2699 foreach my $l (split(/\n/, $groups{$current}->param_summary)) {
2700 ++$i;
2701 $groups{$current}->dispose("\$param_line_$i = \"$l\"", $dmode);
2702 };
2703 if ($$hash_pointer{fitspace} eq 'k') {
2704 $groups{$current}->dispose("write_data(file=\"$file\", \$id_line_\*, \$param_line_\*, \$${current}_title_\*, $current.k, l___cf.data, $arrays)\n", $dmode);
2705 } else {
2706 my $suff = ($groups{$current}->{bkg_flatten}) ? 'flat' : 'norm';
2707 ($suff = 'norm') if ($$hash_pointer{fitspace} eq 'd');
2708 $groups{$current}->dispose("write_data(file=\"$file\", \$id_line_\*, \$param_line_\*, \$${current}_title_\*, $current.energy, $current.$suff, $arrays)\n", $dmode);
2709 };
2710
2711 };
2712
2713 sub lcf_constrain {
2714 my $how = $_[0];
2715 my @keys = qw(lcf_nonneg lcf_100 lcf_linear lcf_noise lcf_fitspace
2716 lcf_fitmin_k lcf_fitmin_e
2717 lcf_fitmax_k lcf_fitmax_e
2718 );
2719 foreach my $i (1 .. $config{linearcombo}{maxspectra}) {
2720 next if ($$hash_pointer{"standard$i"} eq 'None');
2721 push @keys, "lcf_standard$i", "lcf_standard_lab$i", "lcf_value$i", "lcf_e0$i", "lcf_e0val$i";
2722 };
2723 set_params($how, @keys);
2724 };
2725
2726
2727 sub lcf_purge {
2728 Echo("No data!"), return unless $current;
2729 Echo("No data!"), return if ($current eq "Default Parameters");
2730 if ($fat_showing eq 'lcf') {
2731 Error("You may not purge LCF results while the LCF dialog is showing.");
2732 return;
2733 };
2734 foreach my $g (keys %groups) {
2735 foreach my $k (keys %{$groups{$g}}) {
2736 #print "$g $k\n";
2737 next unless ($k =~ /^lcf/);
2738 delete $groups{$g}->{$k};
2739 };
2740 };
2741 %lcf_data = ();
2742 project_state(0);
2743 };
2744
2745 ## END OF LINEAR COMBINATION FITTING SUBSECTION
2746 ##########################################################################################