Debian Codegraph @

artemis_parts/file.pl

raw
1 # -*- cperl -*-
2 ## This file is part of Artemis, copyright (c) 2002-2008 Bruce Ravel
3 ##
4
5 ###===================================================================
6 ### file I/O
7 ###===================================================================
8
9 sub open_file {
10 ##local $Tk::FBox::a;
11 ##local $Tk::FBox::b;
12 my $path = $current_data_dir || cwd;
13 ##print ">>> --$from_project-- --$current_data_dir-- --$path--\n";
14 my @atoms_ext = ($STAR_Parser_exists) ? ('*.inp', '*.cif') : ('*.inp');
15 my $types = [['All Artemis file types', ['*.prj', '*.chi', '*.apj', @atoms_ext]],
16 ['Athena projects', '*.prj'],
17 ['chi(k) data', '*.chi'],
18 ['Artemis projects', '*.apj'],
19 ['Atoms/Feff input files', [@atoms_ext]],
20 ['All files', '*'],];
21 my $file = $top -> getOpenFile(-filetypes=>$types,
22 ##(not $is_windows) ?
23 ## (-sortcmd=>sub{$Tk::FBox::a cmp $Tk::FBox::b}) : () ,
24 -initialdir=>$path,
25 -title => "Artemis: Open a file");
26 return unless ($file);
27 Error("$file does not exist!"), return unless (-e $file);
28 track({file=>$file, mode=>"reading from", command=>sub{my $size = -s $file; print "size : $size\n"}}) if $debug_file_path;
29 SWITCH: {
30 import_atoms($file), last SWITCH if ($STAR_Parser_exists and Ifeffit::Files->is_cif($file));
31 import_atoms($file), last SWITCH if (Ifeffit::Files->is_atoms($file));
32 read_feff($file), last SWITCH if (Ifeffit::Files->is_feff($file));
33 read_athena($file), last SWITCH if (Ifeffit::Files->is_athena($file));
34 read_data(0, $file), last SWITCH if (Ifeffit::Files->is_artemis($file));
35 do {
36 my @data = &every_data;
37 my $this = $paths{$current}->data;
38 if ($#data or $paths{$this}->get('file')) {
39 my $message = "Do you wish to read in a new data file (that is, to do multiple data set fitting), or do you wish to change the current data file (that is, to apply this fitting model to a different data set) ?";
40 my $dialog =
41 $top -> Dialog(-bitmap => 'questhead',
42 -text => $message,
43 -title => 'Athena: Reading data',
44 -buttons => [qw/Change New Cancel/],
45 -default_button => 'Change',
46 -font => $config{fonts}{med},
47 -popover => 'cursor');
48 &posted_Dialog;
49 Echo("Not reading data"), my $response = $dialog->Show();
50 return if ($response eq 'Cancel');
51 my $change = ($response eq 'Change') ? $this : 0;
52 ($change) ? Echo("Changing data") : Echo("Importing new data");
53 read_data($change, $file);
54 } else {
55 read_data(0, $file);
56 };
57 };
58 };
59 ## make sure something is to be plotted after the fit
60 my @all = &all_data;
61 foreach (@all) {
62 return if $paths{$_}->get('plot');
63 };
64 $paths{$all[0]}->make(plot=>1);
65 };
66
67 ## This dispatcher handles all the possibilities for different avenues
68 ## of reading in files and decided whether it should be a new data set
69 ## in an MDS fit or if it should be a change of data in the current
70 ## data set.
71 sub dispatch_read_data {
72 my ($change, $file, $from_project) = @_;
73 ##&read_data(@_), return unless ($config{general}{read_data_query});
74
75 track({file=>$file, mode=>"reading from", command=>sub{my $size = -s $file; print "size : $size\n"}}) if $debug_file_path;
76 my @data = &every_data;
77 my $this_data = $paths{$current}->data;
78 &read_data, return unless ($#data or $paths{$this_data}->get('file'));
79
80 ## test to see if this is a zip-style project
81 if ($file) {
82 Archive::Zip::setErrorHandler( \&is_zip_error_handler );
83 my $zip = Archive::Zip->new();
84 my $is_zipstyle = ($zip->read($file) == AZ_OK);
85 undef $zip;
86 Archive::Zip::setErrorHandler( undef );
87 &read_data($paths{$current}->data, $file), return if $is_zipstyle;
88 };
89
90 ##if (($change) and ($change ne "1") and ($change !~ /Tk::Tree/) and (not $from_project)) {
91 if ($#data or $paths{$this_data}->get('file')) {
92 my $message = "Do you wish to read in a new data file (that is, to do multiple data set fitting), or do you wish to change the current data file (that is, to apply this fitting model to a different data set) ?";
93 my $dialog =
94 $top -> Dialog(-bitmap => 'questhead',
95 -text => $message,
96 -title => 'Athena: Reading data',
97 -buttons => [qw/Change New Cancel/],
98 -default_button => 'Change',
99 -font => $config{fonts}{med},
100 -popover => 'cursor');
101 &posted_Dialog;
102 my $response = $dialog->Show();
103 Echo("Not reading data"), return if ($response eq 'Cancel');
104 if ($response eq 'Change') {
105 Echo("Changing data");
106 ## this is needed to handle an mru file
107 if ($file) {
108 &read_data($paths{$current}->data, $file);
109 } elsif ($from_project) {
110 &read_data($paths{$current}->data, $file, 1);
111 } else {
112 &renew_data;
113 };
114 } else {
115 Echo("Importing new data.");
116 &read_data(@_);
117 };
118 } else {
119 &renew_data;
120 };
121 };
122
123 sub renew_data {
124 #track({file=>$file, mode=>"reading from", command=>sub{my $size = -s $file; print "size : $size\n"}}) if $debug_file_path;
125 &read_data($paths{$current}->data);
126 };
127
128 ## this suppresses a nattering message that warns, in cryptic fashion,
129 ## when you attempt to read a non-zip file as a zip file. since that
130 ## is the only way to test for zippiness of a file using Archive::Zip,
131 ## simply suppressing the message seems appropriate.
132 sub is_zip_error_handler { 1; };
133
134 sub read_data {
135 my $change = $_[0];
136 my $file = $_[1];
137 my $from_project = $_[2] || 0;
138 my $force_chi = $_[3] || 0;
139 ((defined $change) and ($change =~ /data\d+/)) or ($change = 0);
140 ##local $Tk::FBox::a;
141 ##local $Tk::FBox::b;
142 my $path = $current_data_dir || cwd;
143 $path = File::Spec->catfile($project_folder, "chi_data", "") if $from_project;
144 ##print ">>> --$from_project-- --$current_data_dir-- --$path--\n";
145 my $types = [['Athena projects, chi(k) data, or Artemis projects', ['*.prj', '*.chi', '*.apj']],
146 ['Athena projects', '*.prj'],
147 ['chi(k) data', '*.chi'],
148 ['Artemis projects', '*.apj'],
149 ['All files', '*'],];
150 if ($from_project) {
151 @$types[0,1,2] = @$types[2,0,1];
152 } elsif ($change) {
153 @$types[0,1] = @$types[1,0];
154 };
155 $file ||= $top -> getOpenFile(-filetypes=>$types,
156 ##(not $is_windows) ?
157 ## (-sortcmd=>sub{$Tk::FBox::a cmp $Tk::FBox::b}) : () ,
158 -initialdir=>$path,
159 -title => "Artemis: Open a data file");
160 return unless ($file);
161 Error("$file does not exist!"), return unless (-e $file);
162
163 track({file=>$file, mode=>"reading from", command=>sub{my $size = -s $file; print "size : $size\n"}}) if $debug_file_path;
164 ## test to see if this is a zip-style project
165 Archive::Zip::setErrorHandler( \&is_zip_error_handler );
166 my $zip = Archive::Zip->new();
167 my $is_zipstyle = ($zip->read($file) == AZ_OK);
168 undef $zip;
169 Archive::Zip::setErrorHandler( undef );
170 ##Archive::Zip::setErrorHandler( \&Carp::carp );
171
172 my $stash = $file;
173
174 unless ($is_zipstyle) {
175 track({file=>$file, mode=>"reading from", command=>sub{my $size = -s $file; print "size : $size\n"}}) if $debug_file_path;
176 my $was_mac = $paths{gsd} ->
177 fix_mac($file, $stash_dir, lc($config{general}{mac_eol}), $top);
178 track({file=>$file, mode=>"reading from", command=>sub{my $size = -s $file; print "size : $size\n"}}) if $debug_file_path;
179 return, Echo("\"$file\" had Macintosh EOL characters and was skipped.") if ($was_mac eq "-1");
180 if ($was_mac) {
181 Echo("\"$file\" had Macintosh EOL characters and was fixed.");
182 $stash = $was_mac;
183 };
184 };
185
186 ## bad things happen if the data file name is longer than 128
187 ## characters. when this happens, transfer the file to the stash
188 ## directory so ifeffit can read it from there. if the filename is
189 ## not too long, then $stash and $file will be the same
190 ## if (length($stash) > 127) {
191 ## my ($nme, $pth, $suffix) = fileparse($stash);
192 ## my $new = File::Spec->catfile($stash_dir, $nme);
193 ## ($new = File::Spec->catfile($stash_dir, "toss")) if (length($new) > 127);
194 ## copy($stash, $new);
195 ## $stash = $new;
196 ## };
197
198 ## this is a zip-style project
199 if ($is_zipstyle) {
200 #$project_folder =
201 ## my $made_by = determine_version_from_project($file);
202 $top -> Busy;
203 my $is_error = unpack_zip($file); ## pass reference to zip object??
204 $top->Unbusy, return 0 if $is_error;
205 $project_name = $file;
206 ##@-fp-@ my $fp_exists = (-e File::Spec->catfile($project_folder, "descriptions", "...fp"));
207 ##@-fp-@ if ($fp_exists) {
208 ##@-fp-@ my $is_ok = compare_fingerprint(File::Spec->catfile($project_folder, "descriptions", "...fp"),
209 ##@-fp-@ File::Spec->catfile($project_folder, "descriptions", "artemis"));
210 ##@-fp-@ unless ($is_ok) {
211 ##@-fp-@ my $dialog =
212 ##@-fp-@ $top -> Dialog(-bitmap => 'warning',
213 ##@-fp-@ -text => "The fingerprint of the description file has changed. This could indicate that this project file has been tampered with. It may be unsafe to continue reading this project file.",
214 ##@-fp-@ -title => 'Artemis: Possibly tainted project file...',
215 ##@-fp-@ -buttons => [qw/Continue Abort/],
216 ##@-fp-@ -default_button => 'Abort',
217 ##@-fp-@ -popover => 'cursor');
218 ##@-fp-@ &posted_Dialog;
219 ##@-fp-@ my $response = $dialog->Show();
220 ##@-fp-@ if ($response eq 'Abort') {
221 ##@-fp-@ delete_project(0);
222 ##@-fp-@ return;
223 ##@-fp-@ };
224 ##@-fp-@ };
225 ##@-fp-@ };
226 open_project(File::Spec->catfile($project_folder, "descriptions", "artemis"));
227 set_fit_button('fit');
228 $top->Unbusy;
229 return;
230 ## test to see if this is an old-style project
231 } elsif (is_old_project($stash)) {
232 $project_name = $stash;
233 my $retval = convert_project_to_zip($stash);
234 return 0 unless $retval;
235 #$project_folder =
236 my $is_error = unpack_zip($stash);
237 return 0 if $is_error;
238 open_project(File::Spec->catfile($project_folder, "descriptions", "artemis"));
239 set_fit_button('fit');
240 return;
241 };
242
243 ## or if it is a record from athena
244 if (Ifeffit::Files->is_record($stash)) {
245 Echo("Reading $file as an Athena project");
246 read_athena($stash);
247 return;
248 };
249
250 ## make sure this is interpretable as data
251 $paths{data0} -> dispose("read_data(file=\"$file\", group=t___oss, no_sort)\n", $dmode);
252 unless (Ifeffit::Files->is_datafile) {
253 &posted_Dialog;
254 $top -> Dialog(-bitmap => 'error',
255 -text => "\`$file\' could not be read by ifeffit as a data file",
256 -title => 'Artemis: Error reading file',
257 -buttons => ['OK'],
258 -default_button => "OK",
259 -font => $config{fonts}{med},
260 -popover => 'cursor' )
261 -> Show();
262 Echo("Failed to read \"$file\" as data");
263 $paths{data0} -> dispose("erase \@group t___oss", $dmode);
264 set_status(0);
265 $top->Unbusy, return 0;
266 };
267 my $suff = (split(" ", Ifeffit::get_string('$column_label')))[0];
268 $paths{data0} -> dispose("set ___n = npts(t___oss.$suff)", $dmode);
269 my $nn = Ifeffit::get_scalar("___n");
270 unless ($nn > 10) {
271 &posted_Dialog;
272 $top -> Dialog(-bitmap => 'error',
273 -text => "\`$file\' has fewer than 10 data points.",
274 -title => 'Artemis: Error reading file',
275 -buttons => ['OK'],
276 -default_button => "OK",
277 -font => $config{fonts}{med},
278 -popover => 'cursor' )
279 -> Show();
280 Echo("Failed to read \"$file\" as data");
281 $paths{data0} -> dispose("erase \@group t___oss", $dmode);
282 set_status(0);
283 $top->Unbusy, return 0;
284 };
285 $paths{data0} -> dispose("erase \@group t___oss", $dmode);
286 set_status(0);
287
288 ## if we have multicolumn data, then we need to have the user choose
289 ## the correct column, this column will be written to a data file in
290 ## the chi_data directory of the project space
291
292 ## -1=tagged by Athena 0=two column else &n_arrays_read from Ifeffit
293 my $is_multicolumn = (Ifeffit::Files->is_multicolumn($file) and (not $force_chi));
294 my $bail = 0;
295 if ($is_multicolumn) {
296 Echo("$file is a multicolumn data file");
297 my $cols = $top -> Toplevel(-title=>"Artemis: multicolumn file ($file)",
298 -class=>'horae');
299 $cols -> protocol(WM_DELETE_WINDOW => sub{$bail = 1;
300 $cols->grabRelease;
301 $cols->destroy;});
302 $cols -> bind('<Control-q>' => sub{$bail = 1;
303 $cols->grabRelease;
304 $cols->destroy;});
305 $cols -> iconimage($iconimage);
306 $cols -> grab;
307 my $left = $cols -> Frame()
308 -> pack(-side=>'left', -fill=>'y', -expand=>1);
309 my $right = $cols -> Frame()
310 -> pack(-side=>'right', -fill=>'both', -expand=>1);
311
312 my $databox = $right -> Scrolled('ROText', -scrollbars=>'se', -width=>50,
313 -relief=>'sunken', -borderwidth=>2,
314 -wrap=>'none')
315 -> pack(-fill=>'both', -expand=>1);
316 BindMouseWheel($databox);
317 $databox->Subwidget("xscrollbar")->configure(-background=>$config{colors}{background});
318 $databox->Subwidget("yscrollbar")->configure(-background=>$config{colors}{background});
319 do {
320 local $/ = undef;
321 open F, $file;
322 $databox->insert('1.0', <F>);
323 close F;
324 };
325
326 $left -> Label(-text=>"Select a chi(k) column",
327 @title2)
328 -> pack(-side=>'top', -pady=>5);
329
330 $paths{gsd} -> dispose("read_data(file=$file, group=t___oss)\n", 1);
331 my @cols = split(" ", Ifeffit::get_string('$column_label'));
332 my ($wn, $chi) = (@cols[0..1]);
333 my $i = 0;
334 my $top = $left -> Frame(-relief=>'groove', -borderwidth=>2)
335 -> pack(-side=>'top', -anchor=>'n', -padx=>4, -pady=>4, -pady=>2);
336 $top -> Label(-text=>'wavenumber', -foreground=>$config{colors}{activehighlightcolor})
337 -> grid(-column=>1, -row=>0, -padx=>4, -pady=>2);
338 $top -> Label(-text=>'chi(k)', -foreground=>$config{colors}{activehighlightcolor})
339 -> grid(-column=>2, -row=>0, -pady=>2);
340 foreach my $c (@cols) {
341 ++$i;
342 my $j = $i;
343 $top -> Label(-text=>$c, -foreground=>$config{colors}{activehighlightcolor})
344 -> grid(-column=>0, -row=>$i, -sticky=>'e', -pady=>2);
345 $top -> Radiobutton(-text=>"", -value=>$c, -variable=>\$wn,
346 -command=>sub{($chi = ($j==5) ? $cols[0] : $cols[$j]) if ($wn eq $chi);
347 my $command = "newplot(x=t___oss.$wn, y=t___oss.$chi, ";
348 $command .= "title=\"current column selection\", xlabel=x, ylabel=y)\n";
349 $paths{gsd}->dispose($command, $dmode);
350 })
351 -> grid(-column=>1, -row=>$i, -pady=>2);
352 $top -> Radiobutton(-text=>"", -value=>$c, -variable=>\$chi,
353 -command=>sub{($chi = ($j==5) ? $cols[0] : $cols[$j]) if ($wn eq $chi);
354 my $command = "newplot(x=t___oss.$wn, y=t___oss.$chi, ";
355 $command .= "title=\"current column selection\", xlabel=x, ylabel=y)\n";
356 $paths{gsd}->dispose($command, $dmode);
357 })
358 -> grid(-column=>2, -row=>$i, -pady=>2);
359 };
360
361 my $bottom = $left -> Frame()
362 -> pack(-side=>'bottom', -fill=>'x', -expand=>1);
363 my $ok = $left -> Button(-text=>'OK', @button2_list,
364 -command=>sub{$cols->grabRelease;
365 $cols->destroy})
366 -> pack(-side=>'left', -fill=>'x', -expand=>1);
367 $left -> Button(-text=>'Cancel', @button2_list,
368 -command=>sub{$bail=1;
369 $cols->grabRelease;
370 $cols->destroy})
371 -> pack(-side=>'right', -fill=>'x', -expand=>1);
372 my $command = "newplot(x=t___oss.$wn, y=t___oss.$chi, ";
373 $command .= "title=\"current column selection\", xlabel=x, ylabel=y)\n";
374 $paths{gsd}->dispose($command, $dmode);
375 $ok -> focus;
376 $cols -> waitWindow;
377
378 unless ($bail) {
379 ## transfer this column to its own data file in the project data folder
380 my $fname = File::Spec->catfile($project_folder, "chi_data", "$chi.chi");
381 my ($count, $chi_orig) = (1, $chi);
382 while (-e $fname) {
383 $chi = $chi_orig . "_$count";
384 ++$count;
385 $fname = File::Spec->catfile($project_folder, "chi_data", "$chi.chi");
386 };
387 $paths{gsd} -> dispose("set \$t___oss_title_01 = \"Artemis extracted data file -- Artemis version $VERSION\"\n", $dmode);
388 $paths{gsd} -> dispose("write_data(file=$fname, \$t___oss_title_*, label=\"k chi\", t___oss.$wn, t___oss.$chi_orig)", $dmode);
389 $paths{gsd} -> dispose("erase \@group t___oss\n", 1);
390 &push_mru($file, 1, "data") unless $from_project;
391 $stash = $fname;
392 my $new = File::Spec->catfile($project_folder, "chi_data", basename($file));
393 copy($file, $new) unless ($file eq $new);
394 $from_project = 1;
395 };
396 };
397 Echo("Aborting read of multicolumn data file $file."), return if $bail;
398
399 ## nope... this is a data file. import this data file into the project
400
401 my $name = ($from_project) ? basename($file) : &push_mru($file, 1, "data");
402 $name = basename($stash) if $is_multicolumn;
403 #my ($name, $pth, $suffix) = fileparse($file);
404 #$current_data_dir = $pth;
405
406 ## make a place to put the data
407 my $project_data_dir = File::Spec->catfile($project_folder, "chi_data");
408 my $nme = basename($stash);
409 my $bn = basename($stash, qw(.chi));
410 my $new = File::Spec->catfile($project_data_dir, $nme);
411 ##($new = File::Spec->catfile($stash_dir, "toss")) if (length($new) > 127);
412 my $count = 1;
413 unless ($stash eq $new) {
414 while (-e $new) { # care not to overwrite files
415 $new = File::Spec->catfile($project_data_dir, $bn."_$count.chi");
416 ++$count;
417 };
418 };
419 copy($stash, $new) unless ($stash eq $new);
420 $stash = $new;
421
422 my $label = unique_label($name);
423
424 map {($_ =~ /^op/) and $widgets{$_}->configure(-state=>'normal')} (keys %widgets);
425 map {$grab{$_}->configure(-state=>'normal')} (keys %grab);
426 my $next = &next_data;
427 my $group = $change || 'data' . $next;
428 if ($change) {
429 ## read the new data into ifeffit's memory
430 my $command = "## Renewing data file:\n";
431 #if ($stash ne $file) {
432 # $command .= "## actual file: $file\n";
433 # $command .= "## transfered to stash file: $stash\n";
434 #};
435 $command .= "read_data(file=\"$stash\", type=chi, group=ch___eck)\n\n";
436 $paths{$group} -> dispose($command, $dmode);
437 Error("$file doesn't appear to be a data file"), return unless (&is_datafile);
438 $command = "erase \@group ch___eck\n";
439 $command .= "read_data(file=\"$stash\", type=chi, group=$group)\n\n";
440 ## delete the old title lines from Ifeffit's memory
441 my ($i, $titles) = (1, "");
442 my $string = join("", "\$", $group, "_title_", sprintf("%2.2d",$i));
443 my $str = Ifeffit::get_string(join("", "\$", $group, "_title_", sprintf("%2.2d",$i)));
444 while ($str !~ /^\s*$/) {
445 $string = join("", "\$", $group, "_title_", sprintf("%2.2d",$i));
446 $paths{$group} -> dispose("$string = \"\"", $dmode);
447 ++$i;
448 $str = Ifeffit::get_string(join("", "\$", $group, "_title_", sprintf("%2.2d",$i)));
449 };
450 $paths{$group} -> dispose($command, $dmode);
451 ## put the new item in the path list
452 #$name = (split(/\./, $name))[0];
453 $paths{$group} -> make(file=>$stash, original_file=>$file,
454 lab=>$label, is_rec=>0,
455 with_bkg=>0, with_fit=>0, with_res=>0);
456 ##$list -> hide('entry', $paths{$group}->get('id').".0");
457 ##$list -> hide('entry', $paths{$group}->get('id').".1");
458 ##$list -> hide('entry', $paths{$group}->get('id').".2");
459
460 $list -> entryconfigure($paths{$group}->get('id'), -text=>$label);
461 if (not &uniform_k_grid($group)) {
462 #$paths{$group} -> make(fix_chi => 1);
463 $paths{$group} -> dispose("## this seems to be chi(k) data in need of fixing...\nfix_chik($group)",
464 $dmode);
465 my $command = "\$artemis_title1 = \"Artemis output file, path -- Artemis version $VERSION\"\n";
466 $command .= "\$artemis_title2 = \"Data interpolated onto even grid \"\n";
467 $command .= "write_data(file=$stash,\n";
468 $command .= wrap(" ", " ", "\$artemis_title*, \$${group}_title_*, $group.k, $group.chi)");
469 $paths{$group} -> dispose($command, $dmode);
470 };
471
472 ## load up the new titles
473 $i = 1;
474 $str = Ifeffit::get_string(join("", "\$", $group, "_title_", sprintf("%2.2d",$i)));
475 while ($str !~ /^\s*$/) {
476 $titles .= $str."\n";
477 ++$i;
478 $str = Ifeffit::get_string(join("", "\$", $group, "_title_", sprintf("%2.2d",$i)));
479 };
480 $paths{$group} -> make(titles=>$titles);
481 ## and display the new titles
482 $widgets{op_titles} -> delete(qw(1.0 end));
483 $widgets{op_titles} -> insert('end', $titles);
484 } else {
485 $paths{gsd} -> dispose("## Reading data file: \n", $dmode);
486 #if ($stash ne $file) {
487 # $paths{gsd} -> dispose("## actual file: $file\n", $dmode);
488 # $paths{gsd} -> dispose("## transfered to stash file: $stash\n", $dmode);
489 #};
490 $paths{gsd} -> dispose("read_data(file=\"$stash\", type=chi, group=$group)\n\n", $dmode);
491 Error("$file doesn't appear to be a data file"), return unless (&is_datafile);
492 my $fit = $group . '.0';
493 #$name = (split(/\./, $name))[0];
494
495 ## handle the list entry for this data set
496 if ($next > 0) {
497 $paths{$group} = Ifeffit::Path -> new(id => $group,
498 group => $group,
499 type => 'data',
500 sameas => 0,
501 file => $stash,
502 lab => $label,
503 original_file => $file,
504 family => \%paths);
505 $list -> add($group, -text=>$label, -style=>$list_styles{enabled});
506 $list -> setmode($group, 'none');
507
508 $list -> add($group.".0", -text=>'Fit', -style=>$list_styles{enabled},);
509 $list -> setmode($group.'.0', 'none');
510 $list -> hide('entry', $group.".0");
511 } else { # this is the first data set
512 $list -> entryconfigure($paths{$group}->get('id'), -text=>$label);
513 };
514
515 ## and set all the default values
516 $paths{$group} -> make(group=>$group, file=>$stash, lab=>$label,
517 original_file=>$file,
518 fit_space => $config{data}{fit_space},
519 do_bkg => ($config{data}{fit_bkg}) ? 'yes' : 'no',
520 kmin => $config{data}{kmin},
521 kmax => $config{data}{kmax},
522 dk => $config{data}{dk},
523 k1 => ($config{data}{kweight} == 1),
524 k2 => ($config{data}{kweight} == 2),
525 k3 => ($config{data}{kweight} == 3),
526 rmin => $config{data}{rmin},
527 rmax => $config{data}{rmax},
528 dr => $config{data}{dr},
529 kwindow => $config{data}{kwindow},
530 rwindow => $config{data}{rwindow},
531 cormin => $config{data}{cormin},
532 );
533
534 # interpret the range parameters
535 if ($paths{$group}->get('kmax') == 0) {
536 $paths{$group}->make(kmax=>15);
537 my ($epsk, $epsr, $suggest) = $paths{$group}->chi_noise;
538 $suggest ||= 15;
539 $paths{$group}->make(kmax=>$suggest);
540 };
541 $paths{$group} -> fix_values();
542
543 ## the or-eq is necessary for the situation where an ff2chi was
544 ## done before the data was read in
545 $paths{$fit} ||= Ifeffit::Path -> new(id => $group.".0",
546 type => 'fit',
547 group => $group."_fit",
548 sameas => $group,
549 lab => 'Fit',
550 parent => 0,
551 family => \%paths);
552 if (not &uniform_k_grid($group)) {
553 #$paths{$group} -> make(fix_chi => 1);
554 $paths{$group} -> dispose("## this seems to be chi(k) data in need of fixing...\nfix_chik($group)",
555 $dmode);
556 my $command = "\$artemis_title1 = \"Artemis output file, path -- Artemis version $VERSION\"\n";
557 $command .= "\$artemis_title2 = \"Data interpolated onto even grid \"\n";
558 $command .= "write_data(file=$stash,\n";
559 $command .= wrap(" ", " ", "\$artemis_title*, \$${group}_title_*, $group.k, $group.chi)");
560 $paths{$group} -> dispose($command, $dmode);
561 };
562 ## other possible: eps_r toler do_real do_ph do_mag
563 my ($i, $titles) = (1, "");
564 my $str = Ifeffit::get_string(join("", "\$", $group, "_title_", sprintf("%2.2d",$i)));
565 while ($str !~ /^\s*$/) {
566 $titles .= $str."\n";
567 ++$i;
568 $str = Ifeffit::get_string(join("", "\$", $group, "_title_", sprintf("%2.2d",$i)));
569 };
570 $paths{$group} -> make(titles=>$titles);
571 $widgets{op_titles} -> insert('end', $paths{$group}->get('titles')) if
572 (($group eq 'data0') and ($widgets{op_titles}->get(qw(1.0 end)) =~ /^\s*$/));
573
574 };
575 $props{'Project title'} = "Fitting ".$paths{$group}->descriptor
576 if $props{'Project title'} =~ /^(\<|$)/;
577 &set_fit_button('fit');
578
579 ## save an autosave file...
580 &save_project(0,1);
581
582 ++$n_data;
583 display_page($group);
584 $file_menu->menu->entryconfigure($save_index, -state=>'normal'); # enable save data
585 $file_menu->menu->entryconfigure($save_index+6, -state=>'normal');
586 plot('r', 0);
587 if ($is_multicolumn) {
588 Echo("Read column $name from $file");
589 } else {
590 Echo("Read data from $file");
591 };
592 $top -> update();
593 project_state(0);
594 return $group;
595 };
596
597
598 ## this should be called immediately after a disposal of
599 ## "read_data". It checks the $column_label ifeffit global variable,
600 ## which ifeffit sets to "--undefined--" when it is thinks that it was
601 ## given a file that was not actually data.
602 sub is_datafile {
603 my $col_string = Ifeffit::get_string('$column_label');
604 return (not ($col_string =~ /^--undefined--$/));
605 };
606
607 sub determine_version_from_project {
608 my $zipfile = $_[0];
609 Archive::Zip::setErrorHandler( \&is_zip_error_handler );
610 my $zip = Archive::Zip->new();
611 die 'error reading project file $zipfile' unless $zip->read($zipfile) == AZ_OK;
612 my $tmp = $paths{data0} -> find('artemis', 'tmp');
613 $zip -> extractMember("descriptions/artemis", $tmp);
614 open T, $tmp;
615 my $line = <T>;
616 chomp $line;
617 close T;
618 unlink $tmp;
619 my $vnum = $1 if ($line =~ /version (.+)$/);
620 undef $zip;
621 Archive::Zip::setErrorHandler( undef );
622 ($vnum = "DR" . $1) if ($vnum =~ /Development Branch Release (\d+)/);
623 Echo("This project is from Artemis version $vnum");
624 return $vnum;
625 };
626
627
628 ## check to see that input chi(k) data is on a rigorously uniform
629 ## k-grid. also check that the first point is either 0 or 0.05.
630 ## return 0 if this data fails either test.
631 sub uniform_k_grid {
632 my ($group) = @_;
633 my @x = Ifeffit::get_array("$group.k");
634 return 0 unless ((abs($x[0]) < EPSILON) or ($x[0]-0.05 < EPSILON));
635 my $ok = 1;
636 my $prev = sprintf "%.3f", $x[1] - $x[0];
637 foreach (2 .. $#x) {
638 my $this = sprintf "%.3f", $x[$_] - $x[$_-1];
639 $ok = (
640 ($this eq $prev)
641 and
642 (abs($this-0.05) < EPSILON)
643 )
644 ? 1 : 0;
645 $prev = $this;
646 return 0 if not $ok;
647 };
648 return $ok;
649 };
650
651
652 sub read_feff {
653 my $file = ($_[0] =~ /^\^\^/) ? "" : $_[0];
654 my $nopaths = $_[1];
655 unless ($file) {
656 ##local $Tk::FBox::a;
657 ##local $Tk::FBox::b;
658 my $path = $current_data_dir || cwd;
659 if (($_[0] =~ /^\^\^/) and ($paths{$current}->get('type') =~ /(feff|path)/)) {
660 $path = $paths{$current}->get('path');
661 };
662 ## apparently some windows apps will save a text file with a
663 ## Capitalized File Name...
664 my $types;
665 if ($_[0]) { # add a path
666 $types = [['feffNNNN.dat and input files', [ 'feff*.dat', '*.inp', '*.INP', '*.Inp']],
667 ['FEFF input files', ['feff.inp', 'FEFF.INP', 'Feff.Inp', 'Feff.inp']],
668 ['feffNNNN.dat files', ['feff*.dat', 'FEFF*.DAT', 'Feff*.Dat', 'Feff*.dat']],
669 ['input files', ['*.inp', '*.INP', '*.Inp']],
670 ['All Files', '*'],];
671 } else { # read feff
672 $types = [['FEFF input files', ['feff.inp', 'FEFF.INP', 'Feff.Inp', 'Feff.inp']],
673 #['feffNNNN.dat files', ['feff*.dat', 'FEFF*.DAT', 'Feff*.Dat', 'Feff*.dat']],
674 ['input files', ['*.inp', '*.INP', '*.Inp']],
675 #['feffNNNN.dat and input files', [ 'feff*.dat', 'FEFF.INP', 'Feff.Inp', 'Feff.inp', '*.inp', '*.INP', '*.Inp']],
676 ['All Files', '*'],];
677 };
678 $file = $top -> getOpenFile(-filetypes=>$types,
679 ##(not $is_windows) ?
680 ## (-sortcmd=>sub{$Tk::FBox::a cmp $Tk::FBox::b}) : () ,
681 -initialdir=>$path,
682 -title => "Artemis: Import a Feff calculation");
683 return unless ($file);
684 };
685 Echo("Could not find \"$file\""), return unless (-e $file);
686 my ($name, $feff_path, $suffix) = fileparse($file);
687 $current_data_dir = $feff_path;
688 track({file=>$file, mode=>"reading from", command=>sub{my $size = -s $file; print "size : $size\n"}}) if $debug_file_path;
689
690 my $data = $paths{$current}->data;
691 ## assign an id to this feff calc
692 my $id = $data . '.feff' . $n_feff;
693
694 ## import this feff calc into the project by copying all files
695 ## &initialize_project(0);
696 my $project_feff_dir = &initialize_feff($id);
697 ## copy all these feff files to the project feff folder
698 opendir F, $feff_path;
699 my @list = grep { (-f File::Spec->catfile($feff_path,$_)) and
700 (lc($_) =~ /\.(bin|dat|inp|log|run)$/) } readdir F;
701 closedir F;
702 map { copy(File::Spec->catfile($feff_path,$_), $project_feff_dir) } @list;
703
704 ## make sure that the feff.inp file is "feff.inp"
705 copy($file, File::Spec->catfile($project_feff_dir, 'feff.inp'));
706
707 my $exists = '';
708 my @nnnnlist;
709 ## windows has an intensely stoopid setting where file extensions
710 ## are not displayed in the file selection widget. in that case it
711 ## is difficult to distinguish between feff.inp and feff.bin (a
712 ## feff8 file option). this next line does something reasonable
713 ## when feff.bin is selected.
714 $name =~ s/\.bin$/\.inp/;
715
716 if (lc($name) =~ /inp$/) {
717 ## artemis wants the feff input file to be called feff.inp,
718 ## regardless of what filename the user clicked on
719 copy($file, File::Spec->catfile($project_feff_dir, 'feff.inp'));
720 ## don't push to the MRU if this feff.inp comes from the tmp directory
721 my $tmpdir = File::Spec->catfile($project_folder, "tmp");
722 my $thisdir = dirname($file);
723 push_mru($file, 1, 'feff') unless same_directory($tmpdir, $thisdir);
724 } else {
725 ## this is a feffNNNN.dat file, not a feff.inp file, figure out
726 ## which feff calc it's a part of
727 push @nnnnlist, $name;
728 foreach my $k (keys %paths) {
729 next unless (ref($paths{$k}) =~ /Ifeffit/);
730 next unless ($paths{$k}->type eq 'feff');
731 next unless same_directory($paths{$k}->{path}, $feff_path);
732 $exists = $k;
733 $id = $paths{$k}->get('id');
734 last;
735 };
736 };
737
738 unless ($exists) {
739 ## instantiate a new object
740 $paths{$id} = Ifeffit::Path -> new(id => $id,
741 type => 'feff',
742 path => $project_feff_dir,
743 data => $data,
744 lab => 'FEFF'.$n_feff,
745 mode => 2,
746 family => \%paths,
747 atoms_atoms => []);
748 my @autoparams;
749 $#autoparams = 6;
750 (@autoparams = autoparams_define($id, $n_feff, 0, 0)) if $config{autoparams}{do_autoparams};
751 $paths{$id} -> make(autoparams=>[@autoparams]);
752
753 if (lc($name) =~ /inp$/) {
754
755 opendir D, $project_feff_dir or die "cannot read directory $project_feff_dir\n";
756 @nnnnlist = sort grep /feff\d{4}\.dat/i, readdir D;
757 closedir D;
758 if (@nnnnlist) {
759 my $response;
760 if ($nopaths) {
761 $response = "No paths";
762 } else {
763 my $dialog =
764 $top -> Dialog(-bitmap => 'questhead',
765 -text => "How many feff paths do you want to import right now.",
766 -title => 'Artemis: Question...',
767 -buttons => ['No paths',
768 'Just the first',
769 "The first $config{paths}{firstn}",
770 'All paths'],
771 -default_button => 'All paths',
772 -font => $config{fonts}{med},
773 -popover => 'cursor');
774 &posted_Dialog;
775 $response = $dialog->Show();
776 };
777 $paths{$id} -> make("feff.inp" => File::Spec->catfile($project_feff_dir, $name));
778 ## fetch list of feffNNNN.dat files
779 Echo("Importing " . lc($response));
780 ($#nnnnlist = -1) if ($response eq 'No paths');
781 ($#nnnnlist = 0) if ($response eq 'Just the first');
782 ($#nnnnlist = $config{paths}{firstn}-1) if (($response =~ /^The first/) and
783 ($#nnnnlist > $config{paths}{firstn}-1));
784 } else {
785 ## this is the situation of importing a feff.inp that has not
786 ## been run to produce the feffNNNN.dat files
787 $exists = 1;
788 ## setting this variable flags the incrementing of $n_feff 7
789 ## lines below and precludes a few other actions later in this
790 ## sub
791 };
792 };
793 $list -> add($id, -text=>'FEFF'.$n_feff, -style=>$list_styles{noplot});
794 $list -> setmode($id, 'close');
795 $list -> setmode($paths{$data}->get('id'), 'close')
796 if ($list -> getmode($paths{$data}->get('id')) eq 'none');
797 ++$n_feff if $exists;
798 };
799
800 ## do intrp
801 unless ($exists) {
802 my $intrp_ok = &do_intrp($id);
803 $paths{$id} -> make(mode=>$paths{$id}->get('mode')+4);
804 };
805
806
807 $list->selectionClear;
808 if ($exists and ($exists =~ /^1$/)) {
809 display_page($id);
810 } elsif ($exists) {
811 display_page($exists);
812 } else {
813 display_page($id);
814 };
815 $exists or ++$n_feff;
816 $file_menu -> menu -> entryconfigure($save_index+6, -state=>'normal');
817 $file_menu -> menu -> entryconfigure($save_index+4, -state=>($Tk::VERSION > 804) ? 'normal' : 'disabled'); # all paths
818
819 my $i = 0;
820 foreach my $f (sort {lc($a) cmp lc($b)} (@nnnnlist)) {
821 #my $kid = $list -> addchild($id);
822 (!$i) or ($i % 10) or Echo("Reading the ${i}th feffNNNN.dat file");
823 #fetch_nnnn($project_feff_dir, $f, join('.', $id, $i), $f);
824 my $kid = fetch_nnnn($id, $project_feff_dir, $f);
825 $exists = $kid if $exists;
826 $list -> entryconfigure($kid,
827 -style => $list_styles{$paths{$kid}->pathstate("enabled")},
828 -text => $paths{$kid}->get('lab'));
829 ++$i;
830 };
831
832
833 ## set display and increment feff counter
834 &set_fit_button('fit');
835
836 ## save an autosave file...
837 &save_project(0,1);
838
839 project_state(0);
840 return $id;
841 };
842
843
844 sub save_all_paths {
845 my $space = $_[0];
846 my $suff;
847 SW: {
848 $suff = '.chi', last SW if (lc($space) eq 'k');
849 $suff = '.rsp', last SW if (lc($space) eq 'r');
850 $suff = '.qsp', last SW if (lc($space) eq 'q');
851 };
852 my $dir = $top -> chooseDirectory(-initialdir => $current_data_dir,
853 -title => "Artemis: Select a directory",
854 #-mustexist => 1,
855 );
856 Error("Saving all paths -- aborted. You did not select a directory."), return 0 unless $dir;
857 $current_data_dir = $dir;
858 Echo("Saving all included paths to files ...");
859 $top -> Busy;
860 ## refresh the variables and title glob before writing out the paths
861 my $command = "\n## saving all included paths to files\n";
862 ##$command .= &erase_all_variables;
863 ##&read_gds2(1); # update gsd object
864 if ($parameters_changed) {
865 map { $command .= $_ -> write_gsd } (@gds);
866 $parameters_changed = 0;
867 };
868 my $titles = $widgets{op_titles}->get(qw(1.0 end));
869 my $n = 3;
870 foreach my $t (split(/\n/,$titles)) {
871 next if ($t =~ /^\s*$/);
872 $command .= "\$artemis_title$n = \"$t\"\n";
873 ++$n;
874 };
875 $paths{$current} -> dispose($command, $dmode);
876
877 my $this_data = $paths{$current}->data;
878 my $kw = $plot_features{kweight};
879 ($kw = $paths{$this_data}->default_k_weight) if ($kw eq 'kw');
880
881 foreach my $k (&path_list) {
882 next unless ($k =~ /feff\d+\.(\d+)/);
883 next unless $paths{$k}->get('include');
884
885 my $command = "";
886 my $group = Ifeffit::Path::pathgroup($k, \%paths);
887
888 my $ii = $paths{$k}->index;
889 ## my $parent = $paths{$k}->get('parent');
890 my $pathto = $paths{$k}->get('path');
891 $command .= $paths{$k} -> write_path($ii, $pathto, $config{paths}{extpp}, $stash_dir);
892 $command .= "ff2chi($ii, group=$group)\n";
893
894 $command .= "\$artemis_title1 = \"Artemis output file, path -- Artemis version $VERSION\"\n";
895 $command .= "\$artemis_title2 = \"Path data from " . $paths{$k}->descriptor() . "\"\n";
896 $command .= "\$artemis_title$n = \"artemis: $group in $space space\"\n";
897
898 my $data = $paths{$k}->data;
899 my $name = $paths{$k}->descriptor();
900 $name =~ s/[.:@&\/\\ ]/_/g;
901 my $file = File::Spec->catfile($current_data_dir, $name.$suff);
902 SWITCH: {
903 (lc($space) eq 'k') and do {
904 $command .= "write_data(file=$file,\n" .
905 wrap(" ", " ", "\$artemis_title*, $group.k, $group.chi)");
906 last SWITCH;
907 };
908 (lc($space) eq 'r') and do {
909 #($paths{$k}->get('do_r')) and
910 $command .= $paths{$k} -> write_fft($kw, $config{data}{rmax_out});
911 $command .= "write_data(file=$file,\n" .
912 wrap(" ", " ",
913 "\$artemis_title*, $group.r, $group.chir_re, " .
914 "$group.chir_im, $group.chir_mag, $group.chir_pha)");
915 last SWITCH;
916 };
917 (lc($space) eq 'q') and do {
918 #($paths{$k}->get('do_r')) and
919 #($paths{$k}->get('do_q')) and
920 $command .= $paths{$k} -> write_fft($kw, $config{data}{rmax_out});
921 $command .= $paths{$k} -> write_bft();
922 $command .= "write_data(file=$file,\n" .
923 wrap(" ", " ",
924 "\$artemis_title*, $group.q, $group.chiq_re, " .
925 "$group.chiq_im, $group.chiq_mag, $group.chiq_pha)");
926 last SWITCH;
927 };
928 }; # end of SWITCH
929 $paths{$k} -> dispose($command, $dmode);
930 }; # end of loop over paths
931 $top -> Unbusy;
932 Echo("Saved all paths in $space space to $current_data_dir");
933 };
934
935 ## check to see if fit and bkg exist...
936 sub save_data {
937 my ($which, $space, $dont_ask) = @_;
938 Echo("Want to save $which in $space space");
939 my $command = "";
940 ## get the correct group name
941 my ($group, $lab);
942 my $save = $current;
943 if (($which eq 'path') and ($current_canvas ne 'path')) {
944 Error("A path is not currently displayed.");
945 return;
946 };
947 if ($which eq 'path') { # prep a path for writing
948 ## what about multiple feff calcs and indeces
949 $group = Ifeffit::Path::pathgroup($current, \%paths);
950 if ($current =~ /feff\d\.(\d+)/) {
951 my $ii = $paths{$current}->index;
952 my $pathto = $paths{$current}->get('path');
953 ##$command .= &erase_all_variables;
954 ##&read_gds2(1); # update gsd object
955 if ($parameters_changed) {
956 map { $command .= $_ -> write_gsd } (@gds);
957 $parameters_changed = 0;
958 };
959 $command .= $paths{$current} -> write_path($ii, $pathto, $config{paths}{extpp}, $stash_dir);
960 $command .= "ff2chi($ii, group=$group)\n";
961 };
962 } else { # prep data/fit/background for writing
963 ## need to determine the data that corresponds to this feff|path|fit|bkg|res|diff
964 $group = $paths{$current}->data;
965 $lab = $paths{$group}->get('lab');
966 $lab = (split(/\./, $lab))[0];
967 $save = $group;
968 ($which eq 'fit') and (($group, $lab, $save) =
969 ($group."_fit", $lab."_fit", $group.".0"));
970 ## ($which eq 'bkg') and (($group, $lab, $save) =
971 ## ($group."_bkg", $lab."_bkg", $group.".2"));
972 ## ($which eq 'res') and (($group, $lab, $save) =
973 ## ($group."_res", $lab."_res", $group.".1"));
974 };
975
976 ## get the output filename
977 my $file;
978 my $path = $current_data_dir || cwd;
979 my ($desc, $suff);
980 SW: {
981 ($desc, $suff) = ('chi(k) files', '.chi'), last SW if (lc($space) eq 'k');
982 ($desc, $suff) = ('chi(R) files', '.rsp'), last SW if (lc($space) eq 'r');
983 ($desc, $suff) = ('chi(q) files', '.qsp'), last SW if (lc($space) eq 'q');
984 };
985 my $types = [[$desc, $suff], ['All Files', '*'],];
986 my $init;
987 if ($paths{$current}->type eq 'path'){
988 my $name = $paths{$current}->descriptor();
989 $name =~ s/[.:@&\/\\ ]/_/g;
990 $init = $name.$suff;
991 } else {
992 $init = $group.$suff;
993 ($init = $lab.$suff) if $lab;
994 };
995 ($init =~ s/[\\:\/\*\?\'<>\|]/_/g);# if ($is_windows);
996 $file = $top -> getSaveFile(-filetypes=>$types,
997 ##(not $is_windows) ?
998 ## (-sortcmd=>sub{$Tk::FBox::a cmp $Tk::FBox::b}) : () ,
999 -initialfile=>$init,
1000 -initialdir=>$path,
1001 -title => "Artemis: Save data");
1002 return unless ($file);
1003 ## make sure I can write to $file
1004 open F, ">".$file or do {
1005 Error("You cannot write to \"$file\". Check the permissions of that file."); return
1006 };
1007 close F;
1008 my ($name, $pth, $suffix) = fileparse($file);
1009 $current_data_dir = $pth;
1010 ## make the titles glob
1011 my $titles = $widgets{op_titles}->get(qw(1.0 end));
1012 $command .= "\$artemis_title1 = \"Artemis output file, data -- Artemis version $VERSION\"\n";
1013 my $n = 2;
1014 if ($which eq 'path') {
1015 $command .= "\$artemis_title$n = \"Path data from " . $paths{$current}->get('lab') . "\"\n";
1016 ++$n;
1017 };
1018 foreach my $l (split(/\n/, $paths{$current}->param_summary($plot_features{kweight}))) {
1019 $command .= "\$artemis_title$n = \"$l\"\n";
1020 ++$n;
1021 };
1022
1023 foreach my $t (split(/\n/,$titles)) {
1024 next if ($t =~ /^\s*$/);
1025 $command .= "\$artemis_title$n = \"$t\"\n";
1026 ++$n;
1027 };
1028 $command .= "\$artemis_title$n = \"artemis: <".$paths{$save}->descriptor."> in $space space\"\n";
1029
1030
1031 ## build the write_data command
1032 my $kw = $plot_features{kweight};
1033 ($kw = $paths{$save}->default_k_weight) if ($kw eq 'kw');
1034 SWITCH: {
1035 (lc($space) eq 'k') and do {
1036 my $suff = "chi";
1037 ($paths{$save}->get('do_r')) and do {
1038 my $data = $paths{$current}->data;
1039 my $kw = ($plot_features{kweight} eq 'kw') ? $paths{$data}->default_k_weight() : $plot_features{kweight};
1040 my $this = "$group.chi, k=$group.k, kweight=$kw, kmin=" . $paths{$data}->get('kmin') .
1041 ", kmax=" . $paths{$data}->get('kmax') .
1042 ", dk=" . $paths{$data}->get('dk') .
1043 ", rmax_out=" . $config{data}{rmax_out} .
1044 ", kwindow=" . $paths{$data}->get('kwindow') . ")";
1045 $command .= wrap('fftf(', ' ', $this) . "\n";
1046 $paths{$save} -> make(do_r=>0);
1047 };
1048 $command .= "write_data(file=$file,\n" .
1049 wrap(" ", " ", "\$artemis_title*, $group.k, $group.$suff, $group.win)");
1050 last SWITCH;
1051 };
1052 (lc($space) eq 'r') and do {
1053 #($paths{$current}->get('do_r')) and (
1054 $command .= $paths{$save} -> write_fft($kw, $config{data}{rmax_out});
1055 $command .= $paths{$save} -> write_bft();
1056 $paths{$save} -> dispose("___x = ceil($group.chir_mag)", 1); # scale window to plot
1057 my $scale = $plot_features{window_multiplier} * Ifeffit::get_scalar("___x");
1058 $command .= "set $group.winout = $scale * $group.rwin\n";
1059 $command .= "write_data(file=$file,\n" .
1060 wrap(" ", " ",
1061 "\$artemis_title*, $group.r, $group.chir_re, " .
1062 "$group.chir_im, $group.chir_mag, $group.chir_pha, $group.winout)");
1063 last SWITCH;
1064 };
1065 (lc($space) eq 'q') and do {
1066 $command .= $paths{$save} -> write_fft($kw, $config{data}{rmax_out});
1067 $command .= $paths{$save} -> write_bft();
1068 $command .= "write_data(file=$file,\n" .
1069 wrap(" ", " ",
1070 "\$artemis_title*, $group.q, $group.chiq_re, " .
1071 "$group.chiq_im, $group.chiq_mag, $group.chiq_pha)");
1072 last SWITCH;
1073 };
1074 };
1075 $paths{$current} -> dispose($command, $dmode);
1076 Echo("Saved $which in $space space to $file");
1077 };
1078
1079
1080 sub save_selected {
1081 my $m = 0;
1082 foreach my $p ($list->info('selection')) {
1083 #my $pp = $p;
1084 #($pp = $1 . "_" . ("fit", "res", "bkg")[$2]) if ($p =~ /(data\d)\.(\d)/);
1085 next if ($paths{$p}->type =~ /(feff|gsd)/);
1086 ++$m
1087 };
1088 Error("Saving file aborted. No plottable items are selected."), return 1 unless ($m);
1089 Error("You cannot save more than $limits{output_columns} groups to a single file. Sorry."), return if ($m>$limits{output_columns});
1090 my $sp = $_[0];
1091
1092 $top->Busy;
1093
1094 my ($x, $y, $mess) = ('','','');
1095 SWITCH: {
1096 ($x, $y, $mess)=('k','chi', "chi(k)"), last SWITCH if ($sp eq 'k');
1097 ($x, $y, $mess)=('k','chi', "k weighted chi(k)"), last SWITCH if ($sp eq 'k1');
1098 ($x, $y, $mess)=('k','chi', "k^2 weighted chi(k)"), last SWITCH if ($sp eq 'k2');
1099 ($x, $y, $mess)=('k','chi', "k^3 weighted chi(k)"), last SWITCH if ($sp eq 'k3');
1100 ($x, $y, $mess)=('r','chir_mag', "the magnitude of chi(R)"), last SWITCH if ($sp eq 'rm');
1101 ($x, $y, $mess)=('r','chir_re', "the real part of chi(R)"), last SWITCH if ($sp eq 'rr');
1102 ($x, $y, $mess)=('r','chir_im', "the imaginary part of chi(R)"), last SWITCH if ($sp eq 'ri');
1103 ($x, $y, $mess)=('q','chiq_mag', "the magnitude of chi(q)"), last SWITCH if ($sp eq 'qm');
1104 ($x, $y, $mess)=('q','chiq_re', "the real part of chi(q)"), last SWITCH if ($sp eq 'qr');
1105 ($x, $y, $mess)=('q','chiq_im', "the imaginary part of chi(q)"), last SWITCH if ($sp eq 'qi');
1106 };
1107 my $types = [['All Files', '*'],['Data Files', '*.dat']];
1108 my $path = $current_data_dir || Cwd::cwd;
1109 my $yy = $y;
1110 ($yy = "chi".$1) if ($sp =~ /k(\d)/);
1111 my $file = $top -> getSaveFile(-filetypes=>$types,
1112 #(not $is_windows) ?
1113 # (-sortcmd=>sub{$Tk::FBox::a cmp $Tk::FBox::b}) : () ,
1114 -initialdir=>$path,
1115 -initialfile=>"selected.".$yy,
1116 -title => "Artemis: Save selected data");
1117 $top->Unbusy, return unless $file;
1118 ## make sure I can write to $file
1119 open F, ">".$file or do { Error("You cannot write to \"$file\". Check the permissions of that file.");
1120 $top -> Unbusy;
1121 return };
1122 close F;
1123 my ($name, $pth, $suffix) = fileparse($file);
1124 $current_data_dir = $pth;
1125 Echo("Saving $mess for the selected data ...");
1126
1127 $paths{$current} -> dispose("\n## saving selected data as columns in a file", $dmode);
1128 my @list = $list->info('selection');
1129 my $command = "file=$file, \$selected_title_\*, " . $paths{$list[0]}->get('group') . ".$x";
1130 my $precmd = "";
1131 if ($parameters_changed) {
1132 map { $precmd .= $_ -> write_gsd(1) } (@gds);
1133 $parameters_changed = 0;
1134 };
1135 $paths{$current}->dispose("\$selected_title_1 = \"Artemis output file, selected -- Artemis version $VERSION\"", $dmode);
1136 $paths{$current}->dispose("\$selected_title_2 = \"This file contains $mess from:\"", $dmode);
1137 my $erase = "erase \$selected_title_1\nerase \$selected_title_2\n";
1138 my $ncol = 0;
1139 my $stan;
1140 my $kw = $plot_features{kweight};
1141 my $this_data = $paths{$current}->data;
1142 ($kw = $paths{$this_data}->default_k_weight) if ($kw eq 'kw');
1143 my @column_labels = ($x);
1144 foreach my $g (@list) {
1145 ##($g = $1 . "_" . ("fit", "res", "bkg")[$2]) if $g =~ /(data\d)\.(\d)/;
1146 next if ($paths{$g}->type =~ /(feff|gsd)/);
1147 my $group;
1148 my $this_label = $paths{$g}->descriptor();
1149 push @column_labels, $this_label; # use DPL labels as column labels
1150 if ($paths{$g}->type eq 'path') {
1151 my $ind = $paths{$g} -> index;
1152 my $pathto = $paths{$g}->get('path');
1153 $precmd .= $paths{$g} -> write_path($ind, $pathto, $config{paths}{extpp}, $stash_dir);
1154 $group = Ifeffit::Path::pathgroup($g, \%paths);
1155 next unless $group;
1156 $precmd .= "ff2chi($ind, group=$group)\n";
1157 } elsif (($paths{$g}->{type} eq 'fit') and $paths{$g}->{parent}) {
1158 ## this is a fit, but not the parent of the fit branch
1159 unless ($paths{$g}->get('imported')) {
1160 ## read this fit into its group if it has not already been imported
1161 $precmd .= "read_data(file=\"" .
1162 $paths{$g}->get('fitfile') .
1163 "\",\n" .
1164 " type=chi, group=". $paths{$g}->get('group') . ")\n";
1165 $paths{$g}->make(imported=>1);
1166 };
1167 ## ## bkg plot has been requested
1168 ## if (($do_bkg) and (-e $paths{$g}->get('bkgfile'))) {
1169 ## unless ($paths{$g}->get('imported_bkg')) {
1170 ## (my $gr = $paths{$g}->get('group')) =~ s/fit/bkg/;
1171 ## ## read this fit into its group if it has not already been imported
1172 ## $precmd .= "read_data(file=\"" .
1173 ## $paths{$g}->get('bkgfile') .
1174 ## "\",\n type=chi, group=$gr)\n";
1175 ## $paths{$g}->make(imported_bkg=>1);
1176 ## };
1177 ## };
1178 ## ## residual plot has been requested
1179 ## if ($do_res) {
1180 ## unless ($paths{$g}->get('imported_res')) {
1181 ## (my $gr = $paths{$g}->get('group')) =~ s/fit/res/;
1182 ## ## read this fit into its group if it has not already been imported
1183 ## $precmd .= "read_data(file=\"" .
1184 ## $paths{$g}->get('resfile') .
1185 ## "\",\n type=chi, group=$gr)\n";
1186 ## $paths{$g}->make(imported_res=>1);
1187 ## };
1188 ## };
1189 };
1190
1191
1192 if ($sp =~ /^r/) {
1193 $precmd .= $paths{$g} -> write_fft($kw, $config{data}{rmax_out});
1194 } elsif ($sp =~ /^q/) {
1195 $precmd .= $paths{$g} -> write_fft($kw, $config{data}{rmax_out});
1196 $precmd .= $paths{$g} -> write_bft();
1197 };
1198 my $grp = ($paths{$g}->type eq 'path') ? $group : $paths{$g}->get('group');
1199 if ($sp =~ /k(\d)/) {
1200 $precmd .= "$grp.chi$1 = $grp.$x^$1 * $grp.$y\n";
1201 $command .= ", $grp.chi$1";
1202 $erase .= "erase $grp.chi$1\n";
1203 } else {
1204 $command .= ", $grp.$y";
1205 };
1206 ++$ncol;
1207 my $ntit = $ncol+2;
1208 $paths{$g}->dispose("\$selected_title_$ntit = \"".$paths{$g}->descriptor()." (column " . eval("$ncol+1") . ")\"", $dmode);
1209 $erase .= "erase \$selected_title_$ntit\n"
1210 };
1211 $Text::Wrap::huge = 'overflow';
1212 ## remove blanks from column labels
1213 @column_labels = map { $_ =~ s/\s+/_/g; $_ } @column_labels;
1214 my $label = join(" ", @column_labels);
1215 $command = wrap("write_data(", " ", $command);
1216 $command .= ",\n label=\"$label\")";
1217 $paths{$current} -> dispose($precmd, $dmode);
1218 $paths{$current} -> dispose($command, $dmode);
1219 $paths{$current} -> dispose($erase, $dmode); # clean up the mess
1220 Echo("Saved $mess for the selected data to \`$file\'");
1221 $top->Unbusy;
1222 };
1223
1224
1225 sub save_full_data {
1226 my $data = $paths{$current}->data;
1227 my ($space, $part);
1228 SWITCH: {
1229 ($space, $part) = ('k', 'chi'), last SWITCH if ($_[0] eq 'k');
1230 ($space, $part) = ('r', 'chir_mag'), last SWITCH if ($_[0] eq 'r_mag');
1231 ($space, $part) = ('r', 'chir_re'), last SWITCH if ($_[0] eq 'r_re');
1232 ($space, $part) = ('r', 'chir_im'), last SWITCH if ($_[0] eq 'r_im');
1233 ($space, $part) = ('q', 'chiq_mag'), last SWITCH if ($_[0] eq 'q_mag');
1234 ($space, $part) = ('q', 'chiq_re'), last SWITCH if ($_[0] eq 'q_re');
1235 ($space, $part) = ('q', 'chiq_im'), last SWITCH if ($_[0] eq 'q_im');
1236 };
1237
1238 my $lab = $paths{$data}->descriptor;
1239 my $label = "$space ";
1240 my $kw = $plot_features{kweight};
1241 ($kw = $paths{$data}->default_k_weight) if ($kw eq 'kw');
1242 my $which = (($paths{$current}->type eq 'fit') and $paths{$current}->get('parent')) ?
1243 $current :
1244 $paths{$data.".0"}->get('thisfit');
1245
1246 my $types = [['All Files', '*'],['Data Files', '*.dat']];
1247 my $path = $current_data_dir || Cwd::cwd;
1248 (my $init = $paths{$which}->descriptor) =~ s/[.:@&\/\\ ]+/_/g;
1249 $init .= "_full.$part";
1250 my $file = $top -> getSaveFile(-filetypes=>$types,
1251 #(not $is_windows) ?
1252 # (-sortcmd=>sub{$Tk::FBox::a cmp $Tk::FBox::b}) : () ,
1253 -initialdir=>$path,
1254 -initialfile=>$init,
1255 -title => "Artemis: Save full data and fit");
1256 ## make sure I can write to $file
1257 open F, ">".$file or do { Error("You cannot write to \"$file\". Check the permissions of that file.");
1258 $top -> Unbusy;
1259 return };
1260 close F;
1261 my ($name, $pth, $suffix) = fileparse($file);
1262 $current_data_dir = $pth;
1263 Echo("Saving full data and fit for ". $paths{$which}->descriptor . " ...");
1264 $top->Busy;
1265
1266 my ($command, $precmd) = ("", "");
1267 my $n = 3;
1268 $paths{$data}->dispose("\$full_title_1 = \"Artemis output file, full data -- Artemis version $VERSION\"", $dmode);
1269 $paths{$data}->dispose("\$full_title_2 = \"This file contains the full data from from $lab\"", $dmode);
1270 my $erase = "erase \$full_title_1\nerase \$full_title_2\n";
1271 my $header_file = $paths{$which}->get('fitfile');
1272 $header_file =~ s/(data\d+)\.fit$/header.$1/;
1273 open H, $header_file;
1274 foreach (<H>) {
1275 chomp;
1276 my $l = substr($_, 2);
1277 $precmd .= "\$full_title_$n = \"$l\"\n";
1278 $erase .= "erase \$full_title_$n\n";
1279 ++$n;
1280 };
1281 close H;
1282
1283 ## foreach my $l (split(/\n/, $paths{$data}->param_summary($kw))) {
1284 ## $precmd .= "\$full_title_$n = \"$l\"\n";
1285 ## ++$n;
1286 ## $erase .= "erase \$full_title_1\n";
1287 ## };
1288 (my $nospaces = $lab) =~ s/[.:@&\/\\ ]+/_/g;
1289 $label .= "$nospaces ";
1290 ## foreach my $t (split(/\n/,$titles)) {
1291 ## next if ($t =~ /^\s*$/);
1292 ## $command .= "\$artemis_title$n = \"$t\"\n";
1293 ## ++$n;
1294 ## };
1295
1296 ## take care to do the FTs uising the parameters of the fit and not
1297 ## of the data! this is easiest done by doing write_fft and
1298 ## write_bft on the chosen fit and substituting in the correct
1299 ## ifeffit group name
1300
1301 my $group = $paths{$which}->get('group');
1302 my $data_group = $paths{$data}->get('group');
1303 my $fft_command = $paths{$which} -> write_fft($kw, $config{data}{rmax_out});
1304 my $bft_command = $paths{$which} -> write_bft();
1305
1306 ## --- data
1307 $command .= "\$full_title_\*, " . $paths{$data}->get('group') . ".$space, " .
1308 $paths{$data}->get('group') . ".$part, ";
1309 if ($space =~ /^k/) {
1310 (my $this_fft = $fft_command) =~ s/$group/$data_group/g;
1311 $precmd .= $this_fft;
1312 ##$precmd .= $paths{$data} -> write_fft($kw, $config{data}{rmax_out});
1313 } elsif ($space =~ /^[rq]/) {
1314 (my $this_fft = $fft_command) =~ s/$group/$data_group/g;
1315 $precmd .= $this_fft;
1316 (my $this_bft = $bft_command) =~ s/$group/$data_group/g;
1317 $precmd .= $this_bft;
1318 ##$precmd .= $paths{$data} -> write_bft();
1319 };
1320
1321 ## --- fit
1322 unless ($paths{$which}->get('imported')) {
1323 $precmd .= "read_data(file=\"" .
1324 $paths{$which}->get('fitfile') . "\",\n" . " type=chi, group=$group)\n";
1325 $paths{$which}->make(imported=>1);
1326 };
1327 if ($space =~ /^r/) {
1328 $precmd .= $fft_command;
1329 } elsif ($space =~ /^q/) {
1330 $precmd .= $fft_command;
1331 $precmd .= $bft_command;
1332 };
1333 $command .= "$group.$part, ";
1334 $label .= "fit ";
1335
1336 ## --- background
1337 if (-e $paths{$which}->get('bkgfile')) {
1338 (my $gr = $paths{$which}->get('group')) =~ s/fit/bkg/;
1339 unless ($paths{$which}->get('imported_bkg')) {
1340 ## read this fit into its group if it has not already been imported
1341 $precmd .= "read_data(file=\"" .
1342 $paths{$which}->get('bkgfile') .
1343 "\",\n type=chi, group=$gr)\n";
1344 $paths{$which}->make(imported_bkg=>1);
1345 };
1346 if ($space =~ /^r/) {
1347 (my $this_fft = $fft_command) =~ s/$group/$gr/g;
1348 $precmd .= $this_fft;
1349 } elsif ($space =~ /^q/) {
1350 (my $this_fft = $fft_command) =~ s/$group/$gr/g;
1351 $precmd .= $this_fft;
1352 (my $this_bft = $bft_command) =~ s/$group/$gr/g;
1353 $precmd .= $this_bft;
1354 };
1355 $command .= "$gr.$part, ";
1356 $label .= "background ";
1357 };
1358
1359 ## --- residual
1360 (my $gr = $paths{$which}->get('group')) =~ s/fit/res/;
1361 unless ($paths{$which}->get('imported_res')) {
1362 ## read this fit into its group if it has not already been imported
1363 $precmd .= "read_data(file=\"" .
1364 $paths{$which}->get('resfile') .
1365 "\",\n type=chi, group=$gr)\n";
1366 $paths{$which}->make(imported_res=>1);
1367 };
1368 if ($space =~ /^r/) {
1369 (my $this_fft = $fft_command) =~ s/$group/$gr/g;
1370 $precmd .= $this_fft;
1371 } elsif ($space =~ /^q/) {
1372 (my $this_fft = $fft_command) =~ s/$group/$gr/g;
1373 $precmd .= $this_fft;
1374 (my $this_bft = $bft_command) =~ s/$group/$gr/g;
1375 $precmd .= $this_bft;
1376 };
1377 $command .= "$gr.$part, ";
1378 $label .= "residual ";
1379
1380 ## --- window
1381 $group = $paths{$data}->get('group');
1382 if ($space =~ /^r/) {
1383 $paths{$data} -> dispose("___x = ceil($group.chir_mag)", 1); # scale window to plot
1384 my $scale = $plot_features{window_multiplier} * Ifeffit::get_scalar("___x");
1385 $precmd .= "set $group.winout = $scale * $group.rwin\n";
1386 } else {
1387 $paths{$data} -> dispose("___x = ceil($group.chi)", 1); # scale window to plot
1388 my $scale = $plot_features{window_multiplier} * Ifeffit::get_scalar("___x");
1389 $precmd .= "set $group.winout = $scale * $group.win\n";
1390 };
1391 $command .= "$group.winout, ";
1392 $label .= "window";
1393
1394
1395 $command = "write_data(file=$file,\n" . wrap(" ", " ", $command);
1396 $command .= "\n label=\"$label\")";
1397 $paths{$which} -> dispose($precmd, $dmode);
1398 $paths{$which} -> dispose($command, $dmode);
1399 $paths{$which} -> dispose($erase, $dmode); # clean up the mess
1400 Echo("Saving full data and fit for ". $paths{$which}->descriptor . " ... done!");
1401 $top->Unbusy;
1402
1403 };
1404
1405 sub save_bkgsub_data {
1406 my $data = $paths{$current}->data;
1407 my $label = $paths{$current}->get("lab");
1408 my $types = [['chi Files', '*.chi'],
1409 ['All Files', '*'],];
1410 my $path = File::Spec->catfile($project_folder, "chi_data", "");
1411 my $fname = basename($paths{$data}->get('file'));
1412 my @list = split(/\./, $fname);
1413 $fname = $list[0] . "_bkgsub." . $list[1];
1414 my $file = $top -> getSaveFile(-filetypes=>$types,
1415 #(not $is_windows) ?
1416 # (-sortcmd=>sub{$Tk::FBox::a cmp $Tk::FBox::b}) : () ,
1417 -initialdir=>$path,
1418 -initialfile=>$fname,
1419 -title => "Artemis: Save background subtracted data");
1420 return unless $file;
1421
1422 my $group = $paths{$data}->get('group');
1423 my $command = "\$artemis_title1 = \"Artemis output file, bkgsub -- Artemis version $VERSION\"\n";
1424 my $titles = $widgets{op_titles}->get(qw(1.0 end));
1425 my $n = 2;
1426 foreach my $t (split(/\n/,$titles)) {
1427 next if ($t =~ /^\s*$/);
1428 $command .= "\$artemis_title$n = \"$t\"\n";
1429 ++$n;
1430 };
1431 $command .= "\$artemis_title$n = \"artemis: " . $paths{$data}->get('lab') . " as background subtracted chi(k)\"\n";
1432
1433 ## make and write bkgsub data
1434 if ($config{data}{bkgsub_window}) {
1435 $command .= "## note: weighting spline by window in background subtraction!!\n";
1436 $command .= "set $group.chib = $group.chi - (${group}_bkg.chi*$group.win)\n";
1437 } else {
1438 $command .= "set $group.chib = $group.chi - ${group}_bkg.chi\n";
1439 };
1440 $command .= "write_data(file=$file,\n" .
1441 wrap(" ", " ", "\$artemis_title*, $group.k, $group.chib)");
1442
1443 $paths{$data} -> dispose($command, $dmode);
1444 project_state(0);
1445
1446 ## offer to reload the bkg sub data
1447 my $dialog =
1448 $top -> Dialog(-bitmap => 'questhead',
1449 -text => "Would you like to replace the current data set with the background subtracted data?",
1450 -title => 'Athena: Replace data?',
1451 -buttons => [qw/Yes No/],
1452 -default_button => 'Yes',
1453 -font => $config{fonts}{med},
1454 -popover => 'cursor');
1455 &posted_Dialog;
1456 if ($dialog->Show() eq 'Yes') {
1457 ##my $cdd_save = $current_data_dir;
1458 &read_data($paths{$current}->data, $file, 1);
1459 $paths{$current} -> make(lab=>"bkgsub " . $label);
1460 $list -> entryconfigure($paths{$current}->get('id'), -text=>$paths{$current}->get("lab"));
1461
1462 ##$current_data_dir = $cdd_save;
1463 $paths{$data} -> make(do_bkg=>'no');
1464 $temp{op_do_bkg} = 'no';
1465 $plot_features{bkg} = 0;
1466 };
1467 Echo("Saved background subtracted data to $file");
1468
1469 };
1470
1471 sub bulk_data {
1472 ## get a list of files from some directory to transfer
1473 my $path = $current_data_dir || Cwd::cwd;
1474 my $FSel = $top->FileSelect(-title => 'Artemis: transfer MANY data files to the project data folder',
1475 -width => 40,
1476 -directory=>$path);
1477 $FSel -> configure(-selectmode=>'extended');
1478 my @data = $FSel->Show;
1479 Echo("Data transfer was aborted."), return unless (defined $data[0] and -f $data[0]);
1480 ## transfer 'em
1481 foreach my $d (@data) {
1482 my $new = File::Spec->catfile($project_folder, "chi_data", basename($d));
1483 my $bn = basename($d, qw(.chi));
1484 my $count = 1;
1485 while (-e $new) { # care not to overwrite files
1486 $new = File::Spec->catfile($project_folder, "chi_data", $bn."_$count.chi");
1487 ++$count;
1488 };
1489 copy($d, $new) unless ($d eq $new);
1490 };
1491 project_state(0);
1492 ## offer to read one of these newly transfered data files
1493 &dispatch_read_data($paths{$current}->data, "", 1);
1494 };
1495
1496
1497 sub unique_label {
1498 my $in = $_[0];
1499 my $i = 1;
1500 my $name = $in;
1501 my $there = 0;
1502 map {($in eq $paths{$_}->get('lab')) and $there = 1} (&every_data);
1503 while ($there) {
1504 $there = 0;
1505 ++$i;
1506 $name = join(" ", $in, $i);
1507 map {($name eq $paths{$_}->get('lab')) and $there = 1} (&every_data);
1508 };
1509 return $name;
1510 };
1511
1512
1513 ## END OF THE FILE I/O SUBSECTION
1514