Debian Codegraph @

artemis_parts/fit.pl

raw
1 # -*- cperl -*-
2 ## This file is part of Artemis, copyright (c) 2002-2006 Bruce Ravel
3 ##
4 ## THE FITTING SUBSECTION
5
6
7
8 sub generate_script {
9 my $first = &first_data;
10 my $how = $_[0]; # 0=write to file buffer
11 # 1=dispose fit + plot
12 # 2=dispose ff2chi + plot
13 my $how_many = $_[1] || 'all';
14 Echo("You have not opened a data file yet."), return unless (($how == 2) or $paths{$first}->get('file'));
15 ECHO: {
16 Echo("Writing script ..."), last ECHO if ($how == 0);
17 Echo("Writing script and fitting ..."), last ECHO if ($how == 1);
18 Echo("Writing script and summing for data set \"" . $paths{$paths{$current}->data}->descriptor . " ..."), last ECHO if ($how == 2);
19 };
20
21 ## this cannot proceed unless merge parameters have been resolved
22 my ($nmerge, $first_merge) = &count_merge;
23 if ($nmerge) {
24 display_page("gsd");
25 gds2_display($first_merge);
26 # message to echo area
27 Error("You must resolve all merged parameters before " .
28 ("writing a script.", "running a fit.", "making a summation.")[$how] );
29 return;
30 };
31
32 ## empty out the space where the list of ill posed variables will go
33 @Ifeffit::Tools::buffer = ();
34
35 ## deal with the situation of hitting the big green button while
36 ## editing a parameter
37 gds2_update_mathexp($widgets{gds2list}, \%gds_selected) if ($current_canvas eq 'gsd');
38
39 ## --- Save autosave file
40 &save_project(0,1);
41
42 my ($wbg, $wfn, $wbt) = ($config{colors}{warning_bg},
43 $config{fonts}{smbold},
44 $config{colors}{warning_fg});
45 my ($bg, $fn, $bt) = ($config{colors}{background},
46 $config{fonts}{small},
47 $config{colors}{button});
48
49 ## --- need a list of the selected paths for writing the log file in
50 ## the case of a summation of selected paths
51 my %selection;
52 if ($how == 2) {
53 map {$selection{$_} = 1} ($list->selectionGet);
54 };
55
56 my $warnings = "";
57 ## make sure that the data and feffNNNN files actually exist as indicated
58 my @ok = ();
59 my $missing_feff = 0;
60 my $missing = "Error finding data and/or FEFF files:\n\nArtemis could not find the following files:\n";
61
62 ## --- check to see that all the files needed for the fit can be found
63 foreach my $p (keys %paths) {
64 next unless (ref($paths{$p}) =~ /Ifeffit/);
65 next if ($p =~ /^\s*$/);
66 next if ($p eq 'journal');
67 next if (($paths{$p}->type eq 'gsd') or ($paths{$p}->type eq 'feff') or
68 ($paths{$p}->type eq 'fit') or ($paths{$p}->type eq 'bkg') or
69 ($paths{$p}->type eq 'res'));
70 next if (($paths{$p}->type eq 'data') and (not $paths{$p}->get('file')));
71 my $file;
72 my $data = $paths{$p}->data;
73 ## --- data file, if included in the fit
74 if ($paths{$p}->type eq 'data') {
75 next unless $paths{$p}->included;
76 $file = $paths{$p}->get('file');
77 unless (-e $file) {
78 push @ok, $paths{$p}->get('lab');
79 $missing .= " Data:\t$file\n";
80 };
81 };
82 ## --- paths, if included in the fit
83 if ($paths{$p}->type eq 'path') {
84 next unless $paths{$data}->included;
85 next unless $paths{$p}->included;
86 $file = File::Spec->catfile($paths{$p}->get('path'),
87 $paths{$p}->get('feff'));
88 unless (-e $file) {
89 ++$missing_feff;
90 $missing .= " Path \`" . $paths{$p}->descriptor() . "\':\t$file\n";
91 };
92 };
93 };
94 $missing_feff && push @ok, "one or more feffNNN.dat files";
95 my $message = join(" and ", @ok);
96 ## --- post a message identifying the missing files, then bail
97 if ($message) {
98 Error("Artemis could not find $message.");
99 post_message($missing, 'Error messages');
100 return 0
101 };
102
103
104 ## --- check that every data set has at least one path associated
105 ## with it, post message explaining problem if problem found
106 my $datafeff = "";
107 foreach my $d (&all_data) {
108 ($datafeff .= "The data set \"" . $paths{$d}->descriptor() . "\" has no included feff paths\n\tassociated with it.\n\n")
109 unless data_paths($d);
110 };
111 if ($datafeff) {
112 $datafeff .= "\nArtemis cannot continue.\n\tYou must either add some paths to the indicated data\n\tset(s) or exclude those data set(s) from the fit.\n";
113 Error("There are severe errors in the fitting model!");
114 post_message($datafeff, 'Error messages');
115 return 0;
116 };
117
118 ## --- trying to do an ff2chi on a data file not included in the fit
119 my $ff2chi_data;
120 ($ff2chi_data = $paths{$current}->data) if ($how == 2);
121 Error("You cannot do ff2chi on " . $paths{$ff2chi_data}->get('lab') . " because it is excluded from fitting."),
122 return if (($how==2) and (not $paths{$ff2chi_data}->included));
123
124 my $is_busy = grep (/Busy/, $top->bindtags);
125 $is_busy or $top -> Busy();
126
127
128 ## --- make sure that there are included paths in the fit
129 my @paths = grep {exists($paths{$_}->{type}) and
130 ($paths{$_}->type eq 'path')} &path_list;
131 my $selected_paths = 0;
132 foreach (@paths) {
133 $selected_paths ||= $paths{$_}->included;
134 };
135 unless ($selected_paths) {
136 Echo ("You have not included any paths for fitting.");
137 $top->Unbusy;
138 return;
139 };
140
141 ## --- just about ready to start fitting
142 my $string .= "\n" . "#" x 40 .
143 "\n# Starting a new fit\n" .
144 "\n# Guess, def, and set parameters:\n";
145 $string .= "unguess\n";
146 ##&read_gds2(0); # update gsd object
147
148 ## --- do some error checking on the parameters...
149 my $is_err = 0;
150 my $error = ($how==1) ? &check_idp : "";
151 my ($this_err, $must_stop) = ("", 0);
152 ++$is_err if $error;
153 ## data parameters
154 ($error) and ($error .= "\n\n");
155 $this_err = &verify_data_parameters;
156 $error .= $this_err;
157 #($must_stop = 1) if $this_err;
158 ++$is_err if $this_err;
159 ## number of paths
160 ($error) and ($error .= "\n\n");
161 $this_err = &verify_number_of_paths;
162 $error .= $this_err;
163 ($must_stop = 1) if $this_err;
164 ++$is_err if $this_err;
165 ## number of variables
166 ($error) and ($error .= "\n\n");
167 $this_err = &verify_number_of_variables;
168 $error .= $this_err;
169 ($must_stop = 1) if $this_err;
170 ++$is_err if $this_err;
171 ## rmin < Rbkg
172 ($error) and ($error .= "\n\n");
173 $this_err = &verify_rmin_rbkg;
174 $error .= $this_err;
175 ($must_stop = 1) if $this_err;
176 ++$is_err if $this_err;
177 ## binary operators
178 ($error =~ /^\s$/m) or ($error .= "\n\n");
179 $this_err = &verify_operators;
180 $error .= $this_err;
181 ($must_stop = 1) if $this_err;
182 ++$is_err if $this_err;
183 ## matching parens
184 ($error =~ /^\s$/m) or ($error .= "\n\n");
185 $this_err = &verify_parens;
186 $error .= $this_err;
187 ($must_stop = 1) if $this_err;
188 ++$is_err if $this_err;
189 ## parameters named like program variables
190 ($error =~ /^\s$/m) or ($error .= "\n\n");
191 $this_err = &verify_ifeffit_program_variables;
192 $error .= $this_err;
193 ($must_stop = 1) if $this_err;
194 ++$is_err if $this_err;
195 ## parameters defined and used
196 ($error =~ /^\s$/m) or ($error .= "\n\n");
197 my $unused_defs = 0;
198 ($this_err, $unused_defs) = &verify_parameters;
199 $error .= $this_err;
200 ++$is_err if $this_err;
201
202 if ($how != 2) {
203 ## R-range compared to Reff values
204 ($error =~ /^\s$/m) or ($error .= "\n\n");
205 $this_err = &verify_reffs;
206 $error .= $this_err;
207 ++$is_err if $this_err;
208 };
209
210 ## --- clear out the Messages tab
211 $notes{messages} -> delete(qw(1.0 end));
212 ##$current_file = "";
213 $top -> update;
214
215 ## --- post a message if trouble was found among the parameters
216 if ($must_stop) {
217 post_message($error, "Error Messages");
218 Error("Fit aborted due to unrecoverable errors in your project. See Messages buffer (control-4)");
219 $top->Unbusy;
220 $update->raise;
221 return;
222 } elsif ($is_err) {
223 post_message($error, "Error Messages");
224 my $dialog =
225 $top -> Dialog(-bitmap => 'warning',
226 -text => "There are errors in your math expressions. Do you want to abort this fit or carry on regardless?",
227 -title => 'Artemis: Errors...',
228 -buttons => [qw/Continue Abort/],
229 -default_button => 'Abort',
230 -font => $config{fonts}{med},
231 -popover => 'cursor');
232 &posted_Dialog;
233 my $response = $dialog->Show();
234 $top->update;
235 ## offer to convert any unused def parameters into either skip or
236 ## after parameters, then issue the right message for aborted or
237 ## continued fits
238 if (@$unused_defs) {
239 my $string = '("'.join('", "', @$unused_defs).'")';
240 my $dia =
241 $top -> Dialog(-bitmap => 'questhead',
242 -text => "Would you like to change the unused def parameters $string into skip or after parameters?",
243 -title => 'Artemis: Def parameters...',
244 -buttons => ["Change to skip", "Change to after", "Do nothing"],
245 -default_button => 'Change to skip',
246 -font => $config{fonts}{med},
247 -popover => 'cursor'
248 );
249 &posted_Dialog;
250 my $resp = $dia->Show();
251 unless ($resp eq "Do nothing") {
252 my $changeto = (split(" ", $resp))[2];
253 gds2_def_to_other($changeto, $unused_defs);
254 if ($response eq 'Abort') {
255 Error("Fit aborted and all unused def parameters were converted to $changeto parameters.");
256 $top->Unbusy;
257 return;
258 } else {
259 Echo("All unused def parameters were converted to $changeto parameters.");
260 };
261 };
262 };
263 if ($response eq 'Abort') {
264 Error("Fit aborted due to errors in parameters and math expressions.");
265 $top->Unbusy;
266 $update->raise;
267 return;
268 };
269 } else {
270 post_message if ($notes{messages} -> get(qw(1.0 end)) =~ /^\s*Errors/);
271 $update->raise;
272 };
273
274
275 ## --- make this fit folder, get fit meta data
276 my $project_fit_dir;
277 ##my ($fit_label, $fit_comment, $fit_fom) = ("", "", 0);
278 if ($how) {
279 Echo("Making fit folder ...");
280 my %save = (label => $fit{label}, comment => $fit{comment},
281 count => $fit{count}, count_full => $fit{count_full},
282 fom => $fit{fom});
283 my $prev_label = "";
284 if (-e File::Spec->catfile($project_folder, "fits",
285 sprintf("fit%4.4d", $fit{count}), 'label')) {
286 open PL, File::Spec->catfile($project_folder, "fits",
287 sprintf("fit%4.4d", $fit{count}), 'label');
288 $prev_label = <PL>;
289 close PL;
290 };
291 ($prev_label =~ s/\bsum\b/fit/) if ($how == 1);
292 ($prev_label =~ s/\bfit\b/sum/) if ($how == 2);
293
294 ## get the most recent fit number, then set $fit{count} according
295 ## to the value of $fit{new}
296 opendir F, File::Spec->catfile($project_folder, "fits");
297 my @fits = sort( grep {/fit\d+/ and -d File::Spec->catfile($project_folder, "fits", $_)} readdir(F) );
298 closedir F;
299 my $prev = (@fits) ? sprintf("%d", substr($fits[$#fits],3)) : 0;
300 $fit{count} = ($fit{new}) ? $prev+1 : $prev;
301 ++$fit{count_full};
302 $fit{label} = $prev_label;
303 $fit{label} ||= ($how == 1) ? "fit $fit{count}" : "sum $fit{count}";
304 $fit{label} =~ s/\b$prev\b/$fit{count}/g;
305 $fit{comment} = $props{Comment};
306 ($fit{comment} =~ s/\bSummation\b/Fit/) if ($how == 1);
307 ($fit{comment} =~ s/\bFit\b/Sum/) if ($how == 2);
308 $fit{comment} ||= ($how == 1) ? "Fit #$fit{count}" : "Summation #$fit{count}";
309 #$fit{comment} =~ s/\b$prev\b/$fit{count}/g;
310 $fit{fom} = $fit{count};
311 $project_fit_dir = File::Spec->catfile($project_folder, "fits",
312 sprintf("fit%4.4d", $fit{count}));
313 if ($config{general}{fit_query}) {
314 Echo("Getting fit information ...");
315 my $chore = ($how == 1) ? "Run fit" : "Make sum";
316 my $title = ($how == 1) ? "fit" : "summation";
317 my $db = $top -> DialogBox(-title=>"Artemis: Information about this $title",
318 -buttons=>[$chore, 'Cancel'],
319 -default_button=>$chore);
320 my $fr = $db->Frame(-borderwidth=>2, -relief=>'flat')->pack(-pady=>5);
321 $title = ($how == 1) ? "run a fit" : "make a summation";
322 $fr -> Label(-text=>"You are about to $title. Artemis needs some",
323 -font=>$config{fonts}{large},
324 -foreground=>$config{colors}{activehighlightcolor})
325 -> pack(-side=>'top');
326 $fr -> Label(-text=>"information to help you organize your project.",
327 -font=>$config{fonts}{large},
328 -foreground=>$config{colors}{activehighlightcolor})
329 -> pack(-side=>'top');
330
331 my @button = (-foreground=>$config{colors}{activehighlightcolor},
332 -font=>$config{fonts}{med},
333 -activeforeground=>$config{colors}{mbutton},
334 -relief=>'flat', -borderwidth=>0,);
335 $fr = $db->Frame(-borderwidth=>2, -relief=>'groove')->pack;
336 $fr -> Button(-text=>"Label: ", @button,
337 -command=>[\&Echo, 'The label that will be used in the Paths list'])
338 -> grid(-column=>0, -row=>0, -sticky=>'w', -pady=>2);
339 $fr -> Entry(-width=>20, -textvariable=>\$fit{label})
340 -> grid(-column=>1, -row=>0, -sticky=>'w', -pady=>2);
341 $fr -> Button(-text=>"Comment: ", @button,
342 -command=>[\&Echo, 'A brief description of this fit. This will the Comment on the Project Properties page.'])
343 -> grid(-column=>0, -row=>1, -sticky=>'w', -pady=>2);
344 $fr -> Entry(-width=>60, -textvariable=>\$fit{comment})
345 -> grid(-column=>1, -row=>1, -sticky=>'w', -pady=>2);
346 $fr -> Button(-text=>"Figure of merit: ", @button,
347 -command=>[\&Echo, 'A number associated with this fit (for instance, the temperature in a temperature series)'])
348 -> grid(-column=>0, -row=>2, -sticky=>'w', -pady=>2);
349 $fr -> Entry(-width=>6, -textvariable=>\$fit{fom})
350 -> grid(-column=>1, -row=>2, -sticky=>'w', -pady=>2);
351 my $rfr = $fr -> Frame
352 -> grid(-column=>0, -row=>3, -columnspan=>2, -sticky=>'w', -padx=>8, -pady=>2);
353 $rfr -> Radiobutton(-text=>"Make a new fit entry",
354 -variable=>\$fit{new},
355 -value=>1,
356 -selectcolor=>$config{colors}{check},
357 -foreground=>$config{colors}{activehighlightcolor},
358 -activeforeground=>$config{colors}{activehighlightcolor},
359 -state=>($fit{count_full}>1) ? 'normal' : 'disabled',
360 -command=>sub{&fit_toggle_new(\$project_fit_dir, $how)})
361 -> pack(-side=>'left');
362 $rfr -> Radiobutton(-text=>"Reuse previous fit entry",
363 -variable=>\$fit{new},
364 -value=>0,
365 -selectcolor=>$config{colors}{check},
366 -foreground=>$config{colors}{activehighlightcolor},
367 -activeforeground=>$config{colors}{activehighlightcolor},
368 -state=>($fit{count_full}>1) ? 'normal' : 'disabled',
369 -command=>sub{&fit_toggle_new(\$project_fit_dir, $how)})
370 -> pack(-side=>'left');
371 $fr -> Button(-text=>"Document: fit information dialog", @button2_list,
372 -command=>sub{pod_display("artemis_fitinfo.pod")})
373 -> grid(-column=>0, -row=>4, -columnspan=>2, -sticky=>'ew', -pady=>2, -padx=>2);
374 my $answer = $db -> Show;
375 if ($answer eq 'Cancel') {
376 ## restore the fit hash upon canceling
377 foreach my $k (qw(label comment count count_full fom)) {
378 $fit{$k} = $save{$k};
379 };
380 Echo("Fit aborted!");
381 $top -> Unbusy;
382 return;
383 };
384 };
385 $fit{label} =~ s/\'/\"/g; # care with quotes
386 $fit{label} =~ s/\s+$//; # trim railing spaces
387 $props{Comment} = $fit{comment};
388 mkpath $project_fit_dir unless (-d $project_fit_dir);
389 };
390
391
392 ## --- and carry on if there are no obvious problems
393 set_status(0);
394 Echo("Generating ifeffit commands ...");
395
396 ## --- define all the GDS parameters
397 my @sets = ();
398 foreach (@gds) {
399 push @sets, $_ if ($_->type eq 'set');
400 };
401 if ($config{general}{sort_set}) {
402 foreach (sort byuse @sets) { $string .= $_ -> write_gsd(0) };
403 } else {
404 foreach (@sets) { $string .= $_ -> write_gsd(0) };
405 };
406 $string .= $/;
407 if ($how == 2) {
408 ## use bestfit values for the summation
409 foreach (@gds) { $string .= $_ -> write_gsd(1) if ($_->type eq 'guess'); };
410 } else {
411 ## otherwise use the mathexp values
412 foreach (@gds) { $string .= $_ -> write_gsd(0) if ($_->type eq 'guess'); };
413 };
414 $string .= $/;
415 foreach (@gds) { $string .= $_ -> write_gsd(0) if ($_->type eq 'def'); };
416 $string .= $/;
417 foreach (@gds) { $string .= $_ -> write_gsd(0) if ($_->type eq 'restrain'); };
418
419 ## --- now read in all the data
420 $string .= "\n\n# Read data:\n";
421 foreach my $d (&all_data) {
422 next if (($how==2) and ($ff2chi_data ne $d));
423 last if (($how==2) and (not -e $paths{$d}->get('file')));
424 my $this = $paths{$d}->get('lab');
425 $paths{$d} -> make(included=>[], inc_mapping=>[]);
426 ## read_data
427 if ($paths{$d}->{is_rec}) {
428 $string .= "# The data was for $this was imported from an Athena record file:\n";
429 $string .= "# " . $paths{$d}->get('file') . "\n";
430 } else {
431 $string .= "## read data for $this:\n";
432 $string .= "read_data(file=\"" . $paths{$d}->get('file') . "\",\n";
433 $string .= " type=chi, group=" . $paths{$d}->get('group') . ")\n";
434 };
435 };
436
437 ## --- write all the paths
438 $string .= "\n\n# Paths:\n";
439 my $i = 0;
440 my @included;
441 my @inc_mapping = ();
442 foreach my $p (@paths) {
443 next unless (($how_many eq 'all selected') or ($paths{$p}->included)); # skip paths deselected for fit
444 next if (($how_many eq 'all selected') and (not $list->selectionIncludes($p)));
445 ++$i;
446 my $ind = $paths{$p} -> index;
447 ##my $parent = $paths{$p}->get('parent');
448 my $data = $paths{$p}->data;
449 my $pathto = $paths{$p}->get('path');
450 push @{$paths{$data}->{included}}, $ind;
451 $paths{$data}->{inc_mapping}->[$ind] = $p;
452 $string .= $paths{$p} -> write_path($ind, $pathto, $config{paths}{extpp}, $stash_dir);
453 };
454
455 ## --- get the list of restraints
456 my $restraints = "";
457 foreach my $p (@gds) {
458 next unless ($p->{type} eq "restrain");
459 $restraints .= "restraint=" . $p->name . ", ";
460 }
461
462 ## --- generate a feffit() of ff2chi() command for each data set
463 my $npaths = $i;
464 my $nsets = $paths{data0} -> count_data_sets();
465 my $iset = 1;
466 ($string .= "\n\n# Do the fit!\n") if ($how==1);
467 foreach my $d (&all_data) {
468 my $this = $paths{$d}->get('lab');
469 if ($how == 2) { ## --- only do ff2chi for the current data
470 next unless ($ff2chi_data eq $d);
471 $string .= "\n\n# Run ff2chi!\n";
472 ## --- an ff2chi can be on all paths or on the selected paths
473 if ($how_many =~ /sel/) { # selected and included
474 my @sel = ();
475 foreach my $p ($list->selectionGet) {
476 next unless (ref($paths{$p}) =~ /Ifeffit/);
477 next unless ($paths{$p}->type eq 'path');
478 next unless ($paths{$p}->data eq $d);
479 next unless ($paths{$p}->included);
480 push @sel, $paths{$p}->get('fit_index');
481 };
482 unless (@sel) {
483 Echo("There are no selected paths for data set \"$this\".");
484 --$fit{count};
485 $top -> Unbusy;
486 return;
487 };
488 $string .= $paths{$d} -> write_ff2chi( &normalize_paths(\@sel) );
489 } else {
490
491 my @sel = ();
492 foreach my $p (keys(%paths)) {
493 next unless (ref($paths{$p}) =~ /Ifeffit/);
494 next unless ($paths{$p}->type eq 'path');
495 next unless ($paths{$p}->data eq $d);
496 next unless ($paths{$p}->included);
497 push @sel, $paths{$p}->get('fit_index');
498 };
499 unless (@sel) {
500 Echo("There are no included paths for data set \"$this\".");
501 --$fit{count};
502 $top -> Unbusy;
503 return;
504 };
505 $string .= $paths{$d} ->
506 write_ff2chi( &normalize_paths(\@sel) );
507 };
508 $string .= "\n\n# Plot data and simulation in fitting space\n";
509 } else {
510 $string .= "\n## fitting $this ...\n" ;
511 $string .= "## === data set \#$iset of $nsets\n";
512 ## --- need to keep track of which data set this in in this fit
513 ## so that background parameters can be found later on
514 $paths{$d} -> make(data_index=>$iset);
515 my $res_list = ($iset == $nsets) ? $restraints : "";
516 $string .= $paths{$d} ->
517 write_feffit( &normalize_paths($paths{$d}->{included}), $iset, $nsets, $res_list);
518 ++$iset;
519 $string .= "\n";
520 }
521 }
522
523 ## --- establish ifeffit's current path for def parameter evaluation
524 my $which = &which_set_path;
525 if ($which) {
526 $string .= "## set default path for def parameter evaluation\n";
527 $string .= "set path_index = " . $paths{$which}->get('fit_index');
528 };
529
530 ## --- prep the bkg data
531 if ($how!=2) {
532 foreach my $d (&all_data) {
533 my $this = $paths{$d}->get('lab');
534 my $g = $paths{$d}->get('group');
535 $string .= "\n\n## Background data for $this ...\n";
536 if ($paths{$d}->get('do_bkg') eq 'yes') {
537 $string .= "set(" . $g . "_bkg.k = $g.k)\n";
538 $string .= "set(" . $g . "_bkg.chi = " . $g . "_fit.kbkg)\n";
539 ##$string .= "## the following line is a crude hack to sidestep a bug Bruce cannot figure out\n";
540 ##$string .= " set foo.x = " . $g . "_bkg.chi\n";
541 ##$paths{$g.".2"}->make(do_r=>1);
542 $plot_features{bkg} = "b";
543 } else {
544 $plot_features{bkg} = 0;
545 };
546 };
547 };
548
549 ## --- make residual data (need to zero values outside fit range)
550 foreach my $d (&all_data) {
551 next if (($how==2) and ($ff2chi_data ne $d));
552 last if (($how==2) and (not -e $paths{$d}->get('file')));
553 my $this = $paths{$d}->get('lab');
554 my $g = $paths{$d}->get('group');
555 $string .= "\n## Residual data for $this ...\n";
556 $string .= sprintf("set(%s_res.k = %s.k)\n", $g, $g);
557 $string .= sprintf("set(%s_res.chi = %s.chi - %s_fit.chi)\n", $g, $g, $g);
558 };
559
560 ## --- make sure do_k flag is set throughout the project
561 foreach (keys %paths) {
562 next unless (ref($paths{$_}) =~ /Ifeffit/);
563 next unless ($paths{$_}->type);
564 next if (/$no_plot_regex$/o);
565 next if (/^\s*$/);
566 $paths{$_}->make(do_k=>1);
567 };
568
569 ### somewhere in the following block data0.0 etc get unhidden see
570 ### earlier versions for examples of list entries being made on
571 ### the fly
572
573 ## --- show Fit, Background, and Residual list entries
574 foreach my $d (&all_data) {
575 next if (($how==2) and ($ff2chi_data ne $d));
576 if ($how) {
577 $paths{$d.'.0'} ||= Ifeffit::Path -> new(id=>$d.".0", type=>'fit', group=>$d.'_fit',
578 sameas=>$d, lab=>'Fit',
579 parent=>0, family=>\%paths);
580 $list -> show('entry', $paths{$d}->get('id').".0");
581 $paths{$d}->make(with_fit=>1);
582 };
583 };
584 ## if ($how == 1) {
585 ## $list -> show('entry', $paths{$d}->get('id').".1");
586 ## $paths{$d}->make(with_res=>1);
587 ## };
588 ## if (($how == 1) and ($paths{$d}->get('do_bkg') eq 'yes')) {
589 ## $list -> show('entry', $paths{$d}->get('id').".2");
590 ## $paths{$d}->make(with_bkg=>1);
591 ## };
592 ##};
593
594
595 ## --- select and anchor the plotted data set
596 my $to_plot;
597 foreach (&all_data) {
598 ($to_plot = $_), last if $paths{$_}->get('plot');
599 };
600 unless ($to_plot) {
601 $to_plot = &first_data;
602 $paths{$to_plot}->make(plot=>1);
603 };
604 ($to_plot = $ff2chi_data) if ($how == 2);
605 if ($how) {
606 $list -> see($list->info('prev', $paths{$to_plot}->get('id')));
607 $list -> anchorSet($to_plot);
608 };
609 ## foreach (&all_data) {
610 ## $paths{$_}->make(plot=>0);
611 ## };
612 ## $paths{$to_plot}->make(plot=>1);
613 ## what does this next block do?? is it a remnant of the ancient
614 ## difference spectrum scheme??
615 ## unless (($how==2) and (not -e $paths{$to_plot}->get('file'))) {
616 ## $list -> selectionClear;
617 ## $list -> anchorSet($to_plot.'.0') if ($how_many =~ /sel/);
618 ## if ($paths{$to_plot}->{fit_diff}) {
619 ## $list -> selectionSet($to_plot.'.3');
620 ## $list -> anchorSet($to_plot.'.3');
621 ## } else {
622 ## $list -> selectionSet($to_plot);
623 ## $list -> anchorSet($to_plot);
624 ## };
625 ## $list -> see($paths{$to_plot}->get('id').'.0') if $how;
626 ## display_properties if $how;
627 ## };
628
629
630 ## -- plot the data and fit of the chosen (or first) data set
631 my $plot_string = "\n\n# Plot data and fit in fitting space\n";
632 $list -> selectionClear;
633 if ($how==1) { # fitting
634 $list -> selectionSet($paths{$to_plot}->get('id').'.0');
635 foreach my $d (&all_data) {
636 $list -> entryconfigure($paths{$d}->get('id').".0",
637 -text=>"Fit");
638 ##-text=>"Fit [$fit{count_full}]");
639 $paths{$d}->make(count_full=>$fit{count_full});
640 if ($paths{$d}->get('plot')) {
641 $list -> selectionSet($paths{$d}->get('id'));
642 $list -> selectionSet($paths{$d}->get('id').".0");
643 };
644 };
645 } elsif ($how==2) { # ff2chi-ing
646 $list -> selectionSet($paths{$ff2chi_data}->get('id').'.0');
647 $list -> entryconfigure($paths{$ff2chi_data}->get('id').".0",
648 -text=>"Sum");
649 ##-text=>"Sum [$fit{count_full}]");
650 foreach my $d (&all_data) {
651 $paths{$d}->make(count_full=>$fit{count_full});
652 };
653 };
654 unless ($how == 0) {
655 foreach my $p (keys %paths) {
656 next unless (exists($paths{$p}) and $paths{$p});
657 next unless ($paths{$p}->type eq 'path');
658 $list -> selectionSet($paths{$p}->get('id')) if $paths{$p}->get('plotpath');
659 };
660 };
661
662 unless (($how==2) and (not -e $paths{$to_plot}->get('file'))) {
663 $plot_string .= "read_data(file=\"" . $paths{$to_plot}->get('file') . "\",\n" .
664 " type=chi, group=". $paths{$to_plot}->get('group') . ")\n";
665 };
666
667 $plot_string .= plot($paths{$to_plot}->get('fit_space'), 1, 1);
668 ($how) or ($plot_string .= "echo \"...and you need to FT and plot the fit as well...\"\n");
669
670 ## --- ready to dispose this fitting script
671 Echo("Generating ifefit commands ... done!");
672 if ($how == 0) {
673 post_message($string.$plot_string, 'Ifeffit script');
674 $update->raise;
675 } else {
676 Running(($how == 2) ?
677 "Making the sum of paths (this could take a few minutes, please be patient) ..." :
678 "Running fit (this could take a few minutes, please be patient) ...");
679 @bad_params = ();
680 $paths{data0} -> dispose($string, $dmode);
681 $parameters_changed = 0 if $how; # flag parameters as not changed
682
683 $props{'Last fit'} = $paths{data0} -> date_of_file;
684
685 foreach (keys %paths) { # flag all for updating
686 next unless (ref($paths{$_}) =~ /Ifeffit/);
687 next unless $paths{$_}->type;
688 next if (/$no_plot_regex$/);
689 $paths{$_}->make(do_k=>1);
690 };
691
692 ## --- set state of various File menu options based on how the fit was done
693 ##$file_menu->menu->entryconfigure($save_index+1, -state=>'normal'); # fit
694 ## if ($paths{$paths{$current}->data}->get('with_bkg')) {
695 ## $data_menu->menu->entryconfigure(2, -state=>'normal');# bkgsub
696 ## #$file_menu->menu->entryconfigure($save_index+2, -state=>'normal');# bkg
697 ## };
698 ## if (-e $paths{$paths{$current}->data}->get('file')) { # don't enable in case of data-less ff2chi
699 ## ##$file_menu->menu->entryconfigure($save_index+3, -state=>'normal'); # resid
700 ## $fit_menu->menu->entryconfigure(4, -state=>'normal'); # running R-factor
701 ## };
702 };
703
704 ### --- put best fit & error values in the parameter objects
705 if ($how) {
706 $paths{data0} -> dispose( "\n## Evaluate after-fit parameters ...\n", $dmode);
707 foreach my $p (@gds) {
708 if ($p->{type} eq 'guess') {
709 $p->make(bestfit => sprintf("%.6f", Ifeffit::get_scalar($p->name)),
710 error => 0);
711 if ($how == 1) {
712 $p->make(error => sprintf("%.6f", Ifeffit::get_scalar("delta_".$p->name)));
713 $p->make(note => sprintf("%s = %s +/- %s", $p->name, $p->bestfit, $p->error))
714 if $p->autonote;
715 };
716 } elsif ($p->{type} eq 'def') {
717 $p->make(bestfit => sprintf("%.6f", Ifeffit::get_scalar($p->name)));
718 if ($how == 1) {
719 $p->make(note => sprintf("%s = %s", $p->name, $p->bestfit)) if $p->autonote;
720 };
721 } elsif ($p->{type} eq 'restrain') {
722 $p->make(bestfit => sprintf("%.6f", Ifeffit::get_scalar($p->name)));
723 if ($how == 1) {
724 $p->make(note => sprintf("%s = %s", $p->name, $p->bestfit)) if $p->autonote;
725 };
726 } elsif ($p->{type} eq 'after') {
727 ## evaluate the after, then store its value
728 my $after_string = sprintf("%s = %s\n", $p->name, $p->mathexp);
729 $paths{data0} -> dispose($after_string, $dmode);
730 $p->make(bestfit => sprintf("%.6f", Ifeffit::get_scalar($p->name)));
731 if ($how == 1) {
732 $p->make(note => sprintf("%s = %s", $p->name, $p->bestfit)) if $p->autonote;
733 };
734 };
735 };
736 $paths{data0} -> dispose( "\n\n", $dmode);
737 repopulate_gds2();
738 };
739
740 ## --- post fitting chores
741 if ($how) {
742
743 Running("Writing log file ...");
744 $widgets{results_save} -> configure(-state=>'normal');
745 $notes{results} -> configure(-state=>'normal');
746 $notes{results} -> delete(qw(1.0 end));
747 my $fh;
748 ## --- save the log file to this fit folder
749 open $fh, ">".File::Spec->catfile($project_fit_dir, "log");
750 #my @a;
751 #@a=localtime; print "$a[1]:$a[0] calling results_header\n";
752 &write_results_header($fh, \%fit);
753 #@a=localtime; print "$a[1]:$a[0] calling results\n";
754 &write_results($fh, $how, $how_many);
755 #@a=localtime; print "$a[1]:$a[0] calling show_correlations\n";
756 &show_correlations($fh) if ($how == 1);
757 foreach my $d (&all_data) {
758 next if (($how == 2) and ($d ne $paths{$current}->data));
759 my $lab = $paths{$d}->get('lab');
760 print $fh join("", "\n\n\n", "=" x 5,
761 " Data set >>$lab<< ", "=" x 40, "\n\n");
762 #@a=localtime; print "$a[1]:$a[0] calling write_opparams\n";
763 &write_opparams($fh, $d);
764 print $fh join("", "\n\n ", "=" x 5,
765 " Paths used to fit $lab\n");
766 #@a=localtime; print "$a[1]:$a[0] calling write_paths\n";
767 if ($paths{data0} -> vstr >= 1.02005) {
768 $warnings .= &write_paths($fh, $d, $how, $how_many, \%selection);
769 } else {
770 $warnings .= &write_paths_pre_1_2_5($fh, $d, $how, $how_many, \%selection);
771 };
772 };
773 close $fh;
774 #@a=localtime; print "$a[1]:$a[0] calling log_file_display\n";
775 log_file_display();
776 $widgets{results_choose} -> configure(-state=>'normal');
777 $notes{results} -> yviewMoveto(0);
778 raise_palette('results');
779 $update->raise;
780
781 ## --- save the fits to this fit folder
782 Running("Saving fit information ...");
783 my $ll = ($how ==1) ? "fit" : "sum";
784 my $id = "";
785 foreach my $d (&all_data) {
786 ## remember whether the most recent was a fit or a sum, this is
787 ## needed for labeling the DPL when deleting fits
788 $fit{recent} = ($how == 1) ? 'fit' : 'sum';
789 next if (($how == 2) and ($d ne $paths{$current}->data));
790 my $fname = $d . ".fit";
791 my $bname = $d . ".bkg";
792 my $rname = $d . ".res";
793 ##my $id = join(".", $d, '0', $fit{count});
794 if ($fit{new}) {
795 $id = $d.".0.".$fit{count};
796 $list->add($id);
797 $fit{label} ||= join(" ", $ll, $fit{count});
798 $paths{$id} = Ifeffit::Path -> new(id => $id,
799 type => 'fit',
800 group => $d.'_fit_'.$fit{count},
801 sameas => $d,
802 lab => $fit{label},
803 value => $fit{fom},
804 folder => sprintf("fit%4.4d", $fit{count}),
805 filename => $fname,
806 parent => $d.".0",
807 family => \%paths,
808 );
809 } else {
810 my $i = $fit{count}; #-1;
811 $id = "$d.0.$i";
812 $paths{$id} -> make(lab => $fit{label},
813 value => $fit{fom},
814 imported => 0,
815 imported_bkg => 0,
816 imported_res => 0,
817 );
818 };
819 ## store whether the most recent call to this subroutine was for
820 ## a fit or a sum. this is needed so that DPL label can be set
821 ## correctly when importing a project file.
822 my $fsfile = File::Spec->catfile($project_fit_dir, "$d.fs");
823 open FS, ">".$fsfile;
824 print FS $fit{recent};
825 close FS;
826
827 ## store FT and fit parameters in this fit object
828 my $ftfile = File::Spec->catfile($project_fit_dir, "$d.FT");
829 open FT, ">".$ftfile;
830 foreach my $k (qw(kmin kmax dk kwindow rmin rmax dr rwindow)) {
831 my $val = $paths{$d}->get($k);
832 $paths{$id} -> make($k => $val);
833 print FT $k, "=", $val, $/;
834 };
835 close FT;
836 $paths{$d.".0"} -> make(plot=>$d.'_fit_'.$fit{count},
837 thisfit=>$id);
838 $list -> entryconfigure($id, -style=>$list_styles{$paths{$id}->pathstate("enabled")},
839 -text=>$paths{$id}->get('lab'));
840 my $group = $paths{$d.".0"}->get('group');
841 $fname = File::Spec->catfile($project_fit_dir, $fname);
842 ## store the fit, bkg, and res filenames for quick reference
843 ## when plottings
844 $paths{$id} -> make(fitfile=>$fname);
845 $paths{$id} -> make(bkgfile=>File::Spec->catfile($project_fit_dir, $bname))
846 if ($paths{$d}->get('do_bkg') eq 'yes');;
847 $paths{$id} -> make(resfile=>File::Spec->catfile($project_fit_dir, $rname));
848 $paths{$d} -> dispose("write_data(file=$fname,\n label=\"k chi\", $group.k, $group.chi)");
849 ## --- save the bkg and residual data to the fit folder
850 if ($paths{$d}->get('do_bkg') eq 'yes') {
851 $fname = File::Spec->catfile($project_fit_dir, $d.".bkg");
852 $paths{$d} -> dispose("write_data(file=$fname,\n label=\"k chi\", ${d}_bkg.k, ${d}_bkg.chi)");
853 };
854 $fname = File::Spec->catfile($project_fit_dir, $d.".res");
855 $paths{$d} -> dispose("write_data(file=$fname,\n label=\"k chi\", ${d}_res.k, ${d}_res.chi)");
856 ## --- save the header to the fit folder
857 foreach my $d (&all_data) {
858 next if (($how == 2) and ($d ne $paths{$current}->data));
859 my $header = "";
860 foreach ('Project title', 'Comment', 'Prepared by', 'Contact', 'Started', 'Last fit', 'Environment') {
861 my $this = $_;
862 ($this = "This fit at") if ($this eq 'Last fit');
863 $header .= sprintf("# %-15s : ", $this);
864 $header .= "\n", next if (not defined($props{$_}));
865 $header .= "\n", next if ($props{$_} =~ /^\<.*\>$/);
866 $header .= "\n", next if ($props{$_} =~ /^\s*$/);
867 $header .= "$props{$_}\n";
868 };
869 $header .= sprintf("# %-15s : %s\n", "Figure of merit", $fit{fom});
870 foreach my $l (split(/\n/, $paths{$d}->param_summary($plot_features{kweight}))) {
871 $header .= "# ".$l.$/;
872 };
873 open H, ">".File::Spec->catfile($project_fit_dir, "header.$d");
874 print H $header;
875 close H;
876 };
877 };
878
879 ## --- save the description to this fit folder
880 &save_description;
881 my $description = File::Spec->catfile($project_folder, 'descriptions', 'artemis');
882 copy($description, File::Spec->catfile($project_fit_dir, "description"));
883 ##@-fp-@ save_fingerprint(File::Spec->catfile($project_fit_dir, "description"));
884
885 ## --- touch the label file
886 open L, ">".File::Spec->catfile($project_fit_dir, "label");
887 print L $fit{label};
888 close L;
889
890 ## --- plot the fit
891 Running("Plotting fit results ...");
892 $list -> selectionClear;
893 if ($how==1) { # fitting
894 foreach my $d (&all_data) {
895 next unless ($paths{$d}->get('plot'));
896 $list -> selectionSet($paths{$d}->get('id'));
897 $list -> selectionSet($paths{$d}->get('id').".0");
898 };
899 #$list -> selectionSet($paths{$to_plot}->get('id'));
900 #$list -> selectionSet($paths{$to_plot}->get('id').'.0');
901 } elsif ($how==2) { # ff2chi-ing
902 $list -> selectionSet($paths{$ff2chi_data}->get('id'));
903 $list -> selectionSet($paths{$ff2chi_data}->get('id').'.0');
904 };
905 unless ($how == 0) {
906 foreach my $p (keys %paths) {
907 next unless ($paths{$p}->type eq 'path');
908 $list -> selectionSet($paths{$p}->get('id')) if $paths{$p}->get('plotpath');
909 };
910 };
911 $plot_string = "\n\n# Plot data and fit in fitting space\n";
912 unless (($how==2) and (not -e $paths{$to_plot}->get('file'))) {
913 $plot_string .= "read_data(file=\"" . $paths{$to_plot}->get('file') . "\",\n" .
914 " type=chi, group=". $paths{$to_plot}->get('group') . ")\n";
915 };
916 $plot_string .= plot($paths{$to_plot}->get('fit_space'), 1, 1);
917 $paths{data0} -> dispose($plot_string, $dmode);
918
919 };
920
921 ## --- if there were some bad guess parameters ...
922 if (@bad_params) {
923 my $all = join("\n\t", @bad_params);
924 my $these = ($#bad_params) ? 'these' : 'this';
925 my $dialog =
926 $top -> Dialog(-bitmap => 'warning',
927 -text => "The guess parameters:\n\t$all\ncould not be determined by the fit.\n\nShould Artemis change $these from guess to set?",
928 -title => 'Artemis: Bad guess parameters...',
929 -buttons => [qw/Yes No/],
930 -default_button => 'No',
931 -font => $config{fonts}{med},
932 -popover => 'cursor');
933 &posted_Dialog;
934 my $response = $dialog->Show();
935 if ($response eq 'Yes') {
936 foreach my $b (@bad_params) {
937 G: foreach my $g (@gds) {
938 if (lc($b) eq lc($g->name)) {
939 $g->make(type=>"set");
940 last G;
941 };
942 };
943 };
944 repopulate_gds2();
945 Echo("The ill-defined guess parameters were changed to set. You might want to re-run the fit now.")
946 };
947 };
948
949 ## --- almost done...
950 $is_busy or $top->Unbusy;
951 display_properties if $how;
952 if ($warnings) {
953 open W, ">".File::Spec->catfile($project_fit_dir, 'warnings');
954 print W $warnings;
955 close W;
956 Error("Artemis found possible problems with the fit. Check the \"Messages\" tab (Control-4) for details.");
957 post_message($warnings, 'Fit warnings', 1);
958 raise_palette('results');
959 $update->raise;
960 } elsif ($echo -> cget('-text') =~ /trap/) {
961 1;
962 } elsif ($echo -> cget('-text') =~ /ill-defined/) {
963 1;
964 } else {
965 Echo(($how == 2) ?
966 "Making the sum of paths ... done!" :
967 "Running fit ... done!");
968 };
969 $log_params{force} = 1 if ($how_many =~ /sel/);
970 project_state(0) if $how;
971 };
972
973
974
975 # swiped from the old Ifeffit::IO:
976 # change (3,1,14,5,15,2,13,7,8,6,12) to "1-3,5-8,12-15"
977 sub normalize_paths {
978 my @tmplist; # expand 'X-Y'
979 map { push @tmplist, ($_ =~ /(\d+)-(\d+)/) ? $1 .. $2 : $_ } @{$_[0]};
980 my @list = grep /\d+/, @tmplist; # weed out non-integers
981 @list = sort {$a<=>$b} @list; # sort 'em
982 my $this = shift(@list);
983 my $string = $this;
984 my ($prev, $concat) = ('', '');
985 while (@list) {
986 $prev = $this;
987 $this = shift(@list);
988 if ($this == $prev+1) {
989 $concat = "-";
990 } else {
991 $concat = ",";
992 $string .= join("", "-", $prev, $concat, $this);
993 };
994 $prev = $this;
995 };
996 ($concat eq "-") and $string .= $concat . $this;
997 return $string;
998 };
999
1000
1001 ## this sorts the set parameter objects in an order such that the sets that
1002 ## depend on other sets are declared after the ones they depend upon. The
1003 ## logic is this: $a is greater than $b if $a's math expression uses $b's name
1004 ## or else sort alphabetically by math expression (which puts the
1005 ## number-valued sets first)
1006 sub byuse {
1007 ($a->mathexp =~ /\b$b->{name}\b/i) <=> ($b->mathexp =~ /\b$a->{name}\b/i)
1008 ||
1009 (lc($a->mathexp) cmp lc($b->mathexp))
1010 };
1011
1012
1013 sub fix_residuals {
1014 my $d = $_[0];
1015 my $g = $paths{$d}->get('group');
1016 if (lc($paths{$d}->get('fit_space')) eq 'k') {
1017 my @xarray = Ifeffit::get_array($g."_res.k");
1018 my @yarray = Ifeffit::get_array($g."_res.chi");
1019 my ($min, $max) = (0, $#xarray);
1020 foreach my $i (0 .. $#xarray) {
1021 next if (($xarray[$i] > $paths{$d}->get('rmin')) and
1022 ($xarray[$i] < $paths{$d}->get('rmax')));
1023 $yarray[$i] = 0;
1024 ## ($min = $i-1), last if ($xarray[$i] > $paths{$d}->get('kmin'));
1025 };
1026 ## foreach my $i (reverse (0 .. $#xarray)) {
1027 ## ($max = $i+1), last if ($xarray[$i] < $paths{$d}->get('kmax'));
1028 ## };
1029 ## @xarray = splice(@xarray, $min, $max-$min+1);
1030 ## @yarray = splice(@yarray, $min, $max-$min+1);
1031 Ifeffit::put_array($g."_res.k", \@xarray);
1032 Ifeffit::put_array($g."_res.chi", \@yarray);
1033 } elsif (lc($paths{$d}->get('fit_space')) eq 'r') {
1034 my @xarray = Ifeffit::get_array($g."_res.r");
1035 my @yarray = Ifeffit::get_array($g."_res.chir_re");
1036 my @zarray = Ifeffit::get_array($g."_res.chir_im");
1037 my ($min, $max) = (0, $#xarray);
1038 foreach my $i (0 .. $#xarray) {
1039 next if (($xarray[$i] > $paths{$d}->get('rmin')) and
1040 ($xarray[$i] < $paths{$d}->get('rmax')));
1041 $yarray[$i]=EPSILON, $zarray[$i]=0;
1042 ## ($min = $i-1), last if ($xarray[$i] > $paths{$d}->get('rmin'));
1043 };
1044 ## foreach my $i (reverse (0 .. $#xarray)) {
1045 ## ($max = $i+1), last if ($xarray[$i] < $paths{$d}->get('rmax'));
1046 ## };
1047 ## @xarray = splice(@xarray, $min, $max-$min+1);
1048 ## @yarray = splice(@yarray, $min, $max-$min+1);
1049 ## @zarray = splice(@zarray, $min, $max-$min+1);
1050 Ifeffit::put_array($g."_res.r", \@xarray);
1051 Ifeffit::put_array($g."_res.chir_re", \@yarray);
1052 Ifeffit::put_array($g."_res.chir_im", \@zarray);
1053 } elsif (lc($paths{$d}->get('fit_space')) eq 'q') {
1054 my @xarray = Ifeffit::get_array($g."_res.q");
1055 my @yarray = Ifeffit::get_array($g."_res.chiq_re");
1056 my @zarray = Ifeffit::get_array($g."_res.chiq_im");
1057 my ($min, $max) = (0, $#xarray);
1058 foreach my $i (0 .. $#xarray) {
1059 next if (($xarray[$i] > $paths{$d}->get('rmin')) and
1060 ($xarray[$i] < $paths{$d}->get('rmax')));
1061 $yarray[$i]=EPSILON, $zarray[$i]=0;
1062 ## ($min = $i-1), last if ($xarray[$i] > $paths{$d}->get('kmin'));
1063 };
1064 ## foreach my $i (reverse (0 .. $#xarray)) {
1065 ## ($max = $i+1), last if ($xarray[$i] < $paths{$d}->get('kmax'));
1066 ## };
1067 ## @xarray = splice(@xarray, $min, $max-$min+1);
1068 ## @zarray = splice(@zarray, $min, $max-$min+1);
1069 Ifeffit::put_array($g."_res.q", \@xarray);
1070 Ifeffit::put_array($g."_res.chiq_re", \@yarray);
1071 Ifeffit::put_array($g."_res.chiq_im", \@zarray);
1072 };
1073 };
1074
1075
1076 sub erase_all_variables { &unguess };
1077
1078 sub unguess {
1079 return "unguess\n";
1080 };
1081
1082 sub fit_toggle_new {
1083 my ($rpfd, $how) = @_;
1084 my $prev_label = "";
1085 if (-e File::Spec->catfile($project_folder, "fits",
1086 sprintf("fit%4.4d", $fit{count}), 'label')) {
1087 open PL, File::Spec->catfile($project_folder, "fits",
1088 sprintf("fit%4.4d", $fit{count}), 'label');
1089 $prev_label = <PL>;
1090 close PL;
1091 };
1092 ($prev_label =~ s/\bsum\b/fit/) if ($how == 1);
1093 ($prev_label =~ s/\bfit\b/sum/) if ($how == 2);
1094
1095 ## get the previous fit count number and set $fit{count} according
1096 ## to how it is being toggled.
1097 opendir F, File::Spec->catfile($project_folder, "fits");
1098 my @fits = sort( grep {/fit\d+/ and -d File::Spec->catfile($project_folder, "fits", $_)} readdir(F) );
1099 closedir F;
1100 my $prev = sprintf("%d", substr($fits[$#fits],3));
1101 if ($fit{new}) {
1102 $fit{count} = $prev+1;
1103 } else {
1104 $fit{count} = $prev;
1105 };
1106 ## only fix the label and comment if the user is sticking with the
1107 ## defaults, don't change them is they appear to be user chosen
1108 if ($fit{label} =~ /^(fit|sum)\s+\d+$/) {
1109 $fit{label} = $prev_label;
1110 $fit{label} ||= ($how == 1) ? "fit $fit{count}" : "sum $fit{count}";
1111 $fit{label} =~ s/\b$prev\b/$fit{count}/g;
1112 };
1113 ## if ($fit{comment} =~ /^(Fit|Sum)\s+\#\d+$/) {
1114 ## $fit{comment} = $props{Comment};
1115 ## ($fit{comment} =~ s/\bSummation\b/Fit/) if ($how == 1);
1116 ## ($fit{comment} =~ s/\bFit\b/Sum/) if ($how == 2);
1117 ## $fit{comment} ||= ($how == 1) ? "Fit #$fit{count}" : "Summation #$fit{count}";
1118 ## $fit{comment} =~ s/\b$prev\b/$fit{count}/g;
1119 ## };
1120 $fit{fom} = $fit{count};
1121 $$rpfd = File::Spec->catfile($project_folder, "fits",
1122 sprintf("fit%4.4d", $fit{count}));
1123 };
1124
1125 ## END OF THE FITTING SUBSECTION
1126