Debian Codegraph @

artemis_parts/gds2.pl

raw
1 # -*- cperl -*-
2 ## This file is part of Artemis, copyright (c) 2002-2006, 2008 Bruce Ravel
3 ##
4
5 ###===================================================================
6 ### GDS page, version 2
7 ###===================================================================
8
9 ## still to do:
10 ## 1. multiple selection + functionality
11 ## 2. separator entry (hmmmm.....)
12
13
14 sub make_gds2 {
15
16 my $parent = $_[0];
17
18 my $gds2 = $parent -> Frame(-relief=>'flat',
19 -borderwidth=>0,
20 #@window_size,
21 -highlightcolor=>$config{colors}{background});
22
23 #$gds2 -> packPropagate(0);
24
25 #$gds2 -> Label(-text=>"Parameters and Restraints", @title2)
26 # -> pack(-side=>'top', -anchor=>'w', -padx=>6);
27
28 my $gds2list;
29 $gds2list = $gds2 -> Scrolled("HList",
30 -columns => 4,
31 -header => 1,
32 -scrollbars => 'se',
33 -background => $config{colors}{background},
34 -font => $config{fonts}{fixed},
35 -selectmode => 'extended',
36 -selectbackground=>$config{colors}{selected},
37 -browsecmd => sub {&gds2_update_mathexp($gds2list, \%gds_selected);
38 &gds2_browse($gds2list, \%gds_selected)
39 },
40 -command => \&gds2_annotation,
41 )
42 -> pack(-side=>'top', -expand=>1, -fill=>'both');
43 $widgets{gds2list} = $gds2list;
44 $gds_styles{header} = $gds2list -> ItemStyle('text',
45 -font=>$config{fonts}{small},
46 -anchor=>'w',
47 -foreground=>$config{colors}{activehighlightcolor});
48
49 ## parameter styles
50 foreach my $p (qw(guess def set restrain skip after merge)) {
51 my $key = $p . "_color";
52 ## normal styles
53 $gds_styles{$p} = $gds2list -> ItemStyle('text',
54 -font=>$config{fonts}{fixed},
55 -foreground=>$config{gds}{$key},
56 -selectforeground=>$config{gds}{$key},
57 -background=>($p eq 'merge') ? $config{gds}{merge_background} : $config{colors}{background});
58 ## highlighted styles
59 $gds_styles{$p."_h"} = $gds2list -> ItemStyle('text',
60 -font=>$config{fonts}{fixed},
61 -foreground=>$config{gds}{$key},
62 -selectforeground=>$config{gds}{$key},
63 -background=>$config{gds}{highlight});
64 ## column 2 styles
65 $gds_styles{$p."_n"} = $gds2list -> ItemStyle('text',
66 -font=>$config{fonts}{fixed},
67 -foreground=>$config{gds}{$key},
68 -selectforeground=>$config{gds}{$key},
69 -background=>($p eq 'merge') ? $config{gds}{merge_background} : $config{colors}{background2});
70 };
71 $gds_styles{sep} = $gds2list -> ItemStyle('text',
72 -font=>$config{fonts}{fixed},
73 -background=>$config{colors}{background},
74 );
75 $gds_styles{sep_n} = $gds2list -> ItemStyle('text',
76 -font=>$config{fonts}{fixed},
77 -background=>$config{colors}{background2});
78
79 $gds2list -> Subwidget("hlist") -> headerCreate(0, -text=>"#", -style=>$gds_styles{header},
80 -headerbackground=>$config{colors}{background},);
81 $gds2list -> Subwidget("hlist") -> headerCreate(1, -text=>" ", -style=>$gds_styles{header},
82 -headerbackground=>$config{colors}{background},);
83 $gds2list -> Subwidget("hlist") -> headerCreate(2, -text=>"Name", -style=>$gds_styles{header},
84 -headerbackground=>$config{colors}{background},);
85 $gds2list -> Subwidget("hlist") -> headerCreate(3, -text=>"Math Expression", -style=>$gds_styles{header},
86 -headerbackground=>$config{colors}{background},);
87
88 $gds2list->bind('<ButtonPress-3>',\&gds2_post_menu);
89 BindMouseWheel($gds2list);
90 $gds2list -> Subwidget("xscrollbar")
91 -> configure(-background=>$config{colors}{background},
92 ($is_windows) ? () : (-width=>8));
93 $gds2list -> Subwidget("yscrollbar")
94 -> configure(-background=>$config{colors}{background},
95 ($is_windows) ? () : (-width=>8));
96
97 $gds2list -> Subwidget("hlist") -> columnWidth(0, -char=>4);
98 $gds2list -> Subwidget("hlist") -> columnWidth(1, -char=>3);
99 $gds2list -> Subwidget("hlist") -> columnWidth(2, "");
100 ##$gds2list -> Subwidget("hlist") -> columnWidth(2, -char=>12);
101 ##$gds2list -> Subwidget("hlist") -> columnWidth(3, -char=>37);
102
103
104 $widgets{gds2_show} =
105 $gds2 -> Button(-text=>'Show editing area', @button2_list, -width=>1,
106 -command=>sub{$widgets{gds2_show}->packForget;
107 $widgets{gds2_editarea}->pack(-side=>=>'top', -fill=>'x', -padx=>4, -pady=>2);
108 $gds_selected{showing}="edit";});
109
110 $widgets{gds2_editarea} = $gds2 -> LabFrame(-label=>'Edit selected parameter',
111 -foreground=>$config{colors}{activehighlightcolor},
112 -labelside=>'acrosstop' )
113 -> pack(-side=>'top', -fill=>'x', -padx=>4, -pady=>2);
114
115 ## presentation of name and math expression
116 my $fr = $widgets{gds2_editarea} -> Frame()
117 -> pack(-side=>=>'top', -expand=>1, -fill=>'both');
118 $widgets{gds2_name} = $fr -> Entry(-width=>10, -textvariable=>\$gds_selected{name})
119 -> pack(-side=>'left', -padx=>4);
120 $fr -> Label(-text=>'=')
121 -> pack(-side=>'left');
122 $widgets{gds2_mathexp} = $fr -> Entry(-width=>10, -textvariable=>\$gds_selected{mathexp})
123 -> pack(-side=>'left', -fill=>'x', -expand=>1, -padx=>4);
124
125 $widgets{gds2_name} -> bind("<KeyPress-Return>", sub{gds2_define($gds2list, \%gds_selected);
126 $widgets{gds2_mathexp}->focus();
127 $widgets{gds2_mathexp}->icursor('end');
128 });
129 $widgets{gds2_mathexp} -> bind("<KeyPress-Return>", sub{gds2_define($gds2list, \%gds_selected)});
130
131
132 ## radio buttons for setting parameter type
133 $fr = $widgets{gds2_editarea} -> Frame()
134 -> pack(-side=>=>'top', -expand=>1, -fill=>'both');
135 foreach (qw(Guess Def Set Skip Restrain After)) {
136 $widgets{"gds2_$_"} = $fr -> Radiobutton(-text=>$_,
137 -value=>lc($_),
138 -selectcolor=>$config{colors}{check},
139 -variable=>\$gds_selected{type},
140 -command=>\&gds2_alter)
141 -> pack(-side=>'left', -fill=>'x', -expand=>1);
142 };
143
144 ## command buttons
145 $fr = $widgets{gds2_editarea} -> Frame()
146 -> pack(-side=>=>'top', -expand=>1, -fill=>'both');
147 $fr -> Button(-text=>'Undo edit', @button2_list, -width=>1,
148 -command=>sub{gds2_browse($gds2list, \%gds_selected)})
149 -> pack(-side=>'left', -fill=>'x', -expand=>1, -padx=>2);
150 $fr -> Button(-text=>'New', @button2_list, -width=>1,
151 -command=>\&gds2_new)
152 -> pack(-side=>'left', -fill=>'x', -expand=>1, -padx=>2);
153 $widgets{gds2_grab} = $fr -> Button(-text=>'Grab', @button2_list,
154 -width=>1,
155 -state=>'disabled',
156 -command=>sub{grab_gds2($gds2list, \%gds_selected)})
157 -> pack(-side=>'left', -fill=>'x', -expand=>1, -padx=>2);
158 $fr -> Button(-text=>'Discard', @button2_list, -width=>1,
159 -command=>\&gds2_discard)
160 -> pack(-side=>'left', -fill=>'x', -expand=>1, -padx=>2);
161 $fr -> Button(-text=>'Hide', @button2_list, -width=>1,
162 -command=>sub{$widgets{gds2_editarea}->packForget;
163 $widgets{gds2_show}->pack(-side=>=>'top', -fill=>'x', -padx=>2, -pady=>2);
164 $gds_selected{showing}="show";})
165 -> pack(-side=>'left', -fill=>'x', -expand=>1, -padx=>2);
166
167 $widgets{help_gds} =
168 $widgets{gds2_editarea}
169 -> Button(-text=>"Document: Guess, Def, Set", @button2_list,
170 -command=>sub{pod_display("artemis_gds.pod")} )
171 -> pack(-side=>'bottom', -fill=>'x', -padx=>2);
172
173 if ($config{gds}{start_hidden}) {
174 $widgets{gds2_editarea}->packForget;
175 $widgets{gds2_show}->pack(-side=>=>'top', -fill=>'x', -padx=>2, -pady=>2);
176 $gds_selected{showing}="show";
177 };
178
179 Echo("Showing new GDS page");
180 $top -> update;
181 return $gds2;
182 };
183
184 sub gds2_display {
185 $widgets{gds2list} -> selectionClear;
186 $widgets{gds2list} -> selectionSet($_[0]);
187 $widgets{gds2list} -> anchorSet($_[0]);
188 gds2_browse($widgets{gds2list}, \%gds_selected);
189 $widgets{gds2list} -> see($_[0]);
190 };
191
192 ## this is the callback for clicking on an item in the list
193 sub gds2_browse {
194 my ($list, $rhash) = @_;
195 my $wh = $list->info('anchor');
196 my $which = (ref($wh) eq 'ARRAY') ? $$wh[0] : $wh;
197 my $type = $list->itemCget($which, 1, '-text') || "";
198 my $is_sep = ($type =~ /^\-/);
199 $$rhash{which} = $which;
200 $$rhash{name} = ($is_sep) ? "" : $list->itemCget($which, 2, '-text');
201 $$rhash{mathexp} = ($is_sep) ? "" : $list->itemCget($which, 3, '-text');
202 S: {
203 $$rhash{type} = 'guess', last S if ($type =~ /^g/);
204 $$rhash{type} = 'def', last S if ($type =~ /^d/);
205 $$rhash{type} = 'set', last S if ($type =~ /^s/);
206 $$rhash{type} = 'restrain', last S if ($type =~ /^r/);
207 $$rhash{type} = 'skip', last S if ($type =~ /^\s*$/);
208 $$rhash{type} = 'after', last S if ($type =~ /^a/);
209 $$rhash{type} = 'merge', last S if ($type =~ /^m/);
210 $$rhash{type} = 'sep', last S if $is_sep;
211 };
212 $widgets{gds2_grab} -> configure(-state=>($$rhash{type} eq 'guess') ? 'normal' : 'disabled');
213 if ($is_sep) {
214 map {$widgets{"gds2_$_"} -> configure(-state=>'disabled')}
215 (qw(name mathexp Guess Def Set Skip Restrain After));
216 } else {
217 map {$widgets{"gds2_$_"} -> configure(-state=>'normal')}
218 (qw(name mathexp Guess Def Set Skip Restrain After));
219 $widgets{gds2_mathexp} -> focus();
220 };
221 Echo($gds[$which-1]->note) if ($current_canvas eq 'gsd');
222 };
223
224
225 sub gds2_new {
226 &gds2_update_mathexp($widgets{gds2list}, \%gds_selected);
227 $widgets{gds2list}->selectionClear;
228 $widgets{gds2list}->anchorClear;
229 $gds_selected{type} = "";
230 $gds_selected{name} = "";
231 $gds_selected{mathexp} = "";
232 $gds_selected{which} = 0;
233 $widgets{gds2_name} -> focus();
234 };
235
236
237 sub gds2_exists {
238 foreach (@gds) {
239 return 1 if (lc($_[0]) eq lc($_->name));
240 };
241 return 0;
242 };
243
244 sub gds2_update_mathexp {
245 my ($list,$rhash) = @_;
246 return if ($$rhash{name} =~ /^\s*$/);
247 my $i = 0;
248 foreach (@gds) {
249 if (lc($$rhash{name}) eq lc($_->name)) {
250 $gds[$i]->make(mathexp=>$$rhash{mathexp});
251 $list -> itemConfigure($i+1, 3, -text=>$$rhash{mathexp}, -style=>($gds[$i]->highlight & 2) ? $gds_styles{$$rhash{type}."_h"} : $gds_styles{$$rhash{type}});
252 return;
253 }
254 ++$i;
255 };
256 return 0;
257 };
258
259
260 ## this is the callback for the Define button -- make a new variable
261 sub gds2_define {
262 my ($list, $rhash) = @_;
263 $$rhash{type} ||= "guess"; # sanity checking...
264 my $type = $$rhash{type};
265 my $tag = ($type eq 'skip') ? "" : substr($type, 0, 1).":";
266 my $which = $list->info('anchor');
267 my $row = (ref($which) eq 'ARRAY') ? $$which[0] : $which;
268 my $ip = -1;
269 $$rhash{name} =~ s/\s//g; # sanity checking...
270 $$rhash{mathexp} =~ s/\n//g;
271 Error("That math expression has mismatched parentheses!"), return if check_parens($$rhash{mathexp});
272 if ($$rhash{mathexp} =~ /(\w+)\(/) {
273 my $fun = $1;
274 Error("\"$fun\" is not a valid function in Ifeffit!"), return
275 unless ($1 =~ /^$function_regex$/);
276 };
277 ($$rhash{mathexp} = '0') if ($$rhash{mathexp} =~ /^\s*$/);
278 Error("\"$$rhash{name}\" is not a valid parameter name!"), return
279 unless ($$rhash{name} =~ /^[a-z_][a-z_0-9]*$/i);
280
281 if ($row) {
282 my $ret = &gds2_alter;
283 return if ($ret == -1);
284 } else {
285 my $found = 0;
286 map { ++$found if (lc($_->name) eq lc($$rhash{name})) } (@gds);
287 Error("You already have a variable named \"$$rhash{name}\"!"), return if $found;
288 push @gds, Ifeffit::Parameter->new(type=>$type,
289 name=>$$rhash{name},
290 mathexp=>$$rhash{mathexp},
291 bestfit=>$$rhash{mathexp},
292 modified=>1,
293 note=>"$$rhash{name}: ",
294 autonote=>1,
295 );
296 $row = $#gds+1;
297 $list -> add($row);
298 $list -> itemCreate($row, 0, -text=>$row, -style=>$gds_styles{$type});
299 $list -> itemCreate($row, 1, -text=>$tag, -style=>$gds_styles{$type});
300 $list -> itemCreate($row, 2, -text=>$$rhash{name}, -style=>$gds_styles{$type."_n"});
301 $list -> itemCreate($row, 3, -text=>$$rhash{mathexp}, -style=>$gds_styles{$type});
302 $widgets{gds2_grab} -> configure(-state=>($$rhash{type} eq 'guess') ? 'normal' : 'disabled');
303 };
304 $list->see($row);
305 $list->selectionSet($row);
306 $list->anchorSet($row);
307 project_state(0);
308 $parameters_changed = 1;
309 Echo("Defined the $type variable $$rhash{name} as $$rhash{mathexp}");
310 };
311
312
313 ## update the currently selected parameter
314 sub gds2_alter {
315 #my ($list, $rhash) = ;
316 my $which = $widgets{gds2list}->info('anchor');
317 my $row = (ref($which) eq 'ARRAY') ? $$which[0] : $which;
318 Error("That math expression has mismatched parentheses!"), return -1 if check_parens($gds_selected{mathexp});
319 if ($gds_selected{mathexp} =~ /(\w+)\(/) {
320 my $fun = $1;
321 Error("\"$fun\" is not a valid function in Ifeffit!"), return -1 unless ($1 =~ /^$function_regex$/);
322 };
323 my $found = 0;
324 my $r = $row || 0;
325 foreach my $i (0..$r-2, $r..$#gds) { ++$found if (lc($gds[$i]->name) eq lc($gds_selected{name})) };
326 Error("There is another variable named \"$gds_selected{name}\"!"), return -1 if $found;
327 my $type = $gds_selected{type};
328 my $tag = ($type eq 'skip') ? "" : substr($type, 0, 1).":";
329 gds2_define($widgets{gds2list}, \%gds_selected), return 0 unless $row;
330 my $ip = $row-1;
331 $gds[$ip]->make(type => $type,
332 name => $gds_selected{name},
333 mathexp => $gds_selected{mathexp},
334 bestfit => $gds_selected{mathexp},
335 modified => 1);
336 $widgets{gds2list} -> itemConfigure($row, 0, -text=>$row, -style=>$gds_styles{$type});
337 $widgets{gds2list} -> itemConfigure($row, 1, -text=>$tag, -style=>$gds_styles{$type});
338 $widgets{gds2list} -> itemConfigure($row, 2, -text=>$gds_selected{name}, -style=>($gds[$ip]->highlight & 1) ? $gds_styles{$type."_h"} : $gds_styles{$type."_n"});
339 $widgets{gds2list} -> itemConfigure($row, 3, -text=>$gds_selected{mathexp}, -style=>($gds[$ip]->highlight & 2) ? $gds_styles{$type."_h"} : $gds_styles{$type});
340 $widgets{gds2_grab} -> configure(-state=>($gds_selected{type} eq 'guess') ? 'normal' : 'disabled');
341 project_state(0);
342 $parameters_changed = 1;
343 return 0;
344 };
345
346
347 ## callback for Grab button on the GDS page -- this queries Ifeffit
348 ## for the best fit value of a guess variable
349 sub grab_gds2 {
350 my ($list, $rhash) = @_;
351 my $which = $list->info('anchor');
352 my $row = (ref($which) eq 'ARRAY') ? $$which[0] : $which;
353 my $ip = $row-1;
354 Error($gds[$ip]->name." is not a guess!"), return unless ($gds[$ip]->type eq 'guess');
355 Error("You have not yet run a fit!"), return if ($gds[$ip]->error =~ /^\s*$/);
356 (my $best = $gds[$ip]->bestfit) =~ s/ \(.*\)//;
357 $$rhash{mathexp} = "$best (" . $gds[$ip]->error . ")";
358 $gds[$ip]->make(mathexp=>$$rhash{mathexp});
359 &gds2_alter;
360 };
361
362
363 sub grab_all_best_fits {
364 foreach my $p (@gds) {
365 next unless ($p->type eq 'guess');
366 (my $best = $p->bestfit) =~ s/ \(.*\)//;
367 $p->make(mathexp=>"$best (" . $p->error . ")");
368 };
369 my $which = $widgets{gds2list} -> selectionGet();
370 my $current = (ref($which) eq 'ARRAY') ? $$which[0] : $which;
371 repopulate_gds2();
372 if ($current) {
373 $widgets{gds2list} -> selectionSet($current);
374 $widgets{gds2list} -> anchorSet($current);
375 };
376 $top -> update;
377 project_state(0);
378 $parameters_changed = 1;
379 };
380
381
382 ## convert all guesses to sets
383 sub gds2_guess_to_set {
384 my $dialog =
385 $top -> Dialog(-bitmap => 'questhead',
386 -text => "Are you quite sure you want to convert all guesses to sets?",
387 -title => 'Artemis: Verifying...',
388 -buttons => [qw/Convert Cancel/],
389 -default_button => 'Cancel',
390 -font => $config{fonts}{med},
391 -popover => 'cursor');
392 &posted_Dialog;
393 my $response = $dialog->Show();
394 Echo("Leaving guesses intact."), return if ($response eq 'Cancel');
395 Echo("Changing guesses to sets ...");
396 foreach my $p (@gds) {
397 next unless ($p->type eq 'guess');
398 $p->make(type=>"set");
399 };
400 my $which = $widgets{gds2list} -> selectionGet();
401 my $current = (ref($which) eq 'ARRAY') ? $$which[0] : $which;
402 repopulate_gds2();
403 if ($current) {
404 $widgets{gds2list} -> selectionSet($current);
405 $widgets{gds2list} -> anchorSet($current);
406 };
407 $top -> update;
408 project_state(0);
409 $parameters_changed = 1;
410 Echo("Changing guesses to sets ... done!");
411 };
412
413
414 sub gds2_def_to_other {
415 my ($changeto, $rlist) = @_;
416 foreach my $n (@$rlist) {
417 foreach my $p (@gds) {
418 next unless (lc($p->name) eq lc($n));
419 $p->make(type=>$changeto);
420 };
421 };
422 repopulate_gds2();
423 project_state(0);
424 $parameters_changed = 1;
425 };
426
427 ## make a copy of the anchored parameter
428 sub gds2_copy {
429 my $which = $widgets{gds2list} -> info('anchor') - 1;
430 my $count = 1;
431 my $orig = $gds[$which]->name;
432 my $name = join("", $orig, "_c", $count);
433 my $ok = 0;
434 while (not $ok) { # find a unique name
435 $ok = 1;
436 LOOP: foreach my $g (@gds) {
437 if (lc($g->name) eq lc($name)) {
438 $ok = 0;
439 $name = join("", $orig, "_c", ++$count);
440 last LOOP;
441 };
442 };
443 };
444 splice(@gds, $which, 1, $gds[$which],
445 Ifeffit::Parameter->new(type => $gds[$which]->type,
446 name => $name,
447 mathexp => $gds[$which]->mathexp,
448 bestfit => 0,
449 modified => 1,
450 note => "$name: ",
451 autonote => 1,
452 ));
453 repopulate_gds2();
454 project_state(0);
455 $parameters_changed = 1;
456 $which+=2;
457 &gds2_display($which);
458 $widgets{gds2_name} -> focus;
459 $widgets{gds2_name} -> selectionRange(0, 'end');
460 Echo("Made a copy of parameter \"$orig\". You may wish to rename it.");
461 };
462
463 ## annotate the anchored parameter
464 sub gds2_annotation {
465 my $which = $widgets{gds2list}->info('anchor');
466 my $row = (ref($which) eq 'ARRAY') ? $$which[0] : $which;
467 my $ip = $row-1;
468 ## return if ($gds[$ip]->type eq 'sep');
469 my $annotation = $gds[$ip]->note;
470 my $prior = $gds[$ip]->note;
471 my $label = ($gds[$ip]->type eq 'sep') ?
472 "Annotate this separator : " : "Describe : " . $gds[$ip]->name;
473 my $dialog = get_string($dmode, $label, \$annotation);
474 $dialog -> waitWindow; # the get_string dialog will be
475 # destroyed once the user hits ok,
476 # then we can move on...
477 return if ($annotation eq $prior); # unchanged
478 if ($gds[$ip]->type eq 'sep') {
479 $gds[$ip]->make(note=>$annotation);
480 my $n = 17 - length($annotation);
481 ($annotation .= " " . "-" x $n) if ($n > 0);
482 $gds[$ip]->make(mathexp=>"----- " . $annotation . "---");
483 repopulate_gds2();
484 } else {
485 ## turn off automatic annotation in favor of the user supplied one
486 $gds[$ip]->make(note=>$annotation, autonote=>0);
487 ## turn automatic annotation back on if $annotation is blank
488 $gds[$ip]->make(autonote=>1) if ($annotation =~ /^\s*$/);
489 };
490 project_state(0);
491 Echo($annotation) if ($current_canvas eq 'gsd');
492 }
493
494
495 ## insert all parameters in @gds into the list on the GDS page
496 sub populate_gds2 {
497 my $i = 1;
498 foreach my $p (@gds) {
499 my $type = $p->type;
500 my $tag = ($type eq 'skip') ? "" : substr($type, 0, 1).":";
501 ($tag = "--") if ($type eq 'sep');
502 $widgets{gds2list} -> add($i);
503 $widgets{gds2list} -> itemCreate($i, 0, -text=>$i, -style=>$gds_styles{$type});
504 $widgets{gds2list} -> itemCreate($i, 1, -text=>$tag, -style=>$gds_styles{$type});
505 $widgets{gds2list} -> itemCreate($i, 2, -text=>$p->name, -style=>($p->highlight & 1) ? $gds_styles{$type."_h"} : $gds_styles{$type."_n"});
506 $widgets{gds2list} -> itemCreate($i, 3, -text=>$p->mathexp, -style=>($p->highlight & 2) ? $gds_styles{$type."_h"} : $gds_styles{$type});
507 ++$i;
508 };
509 $gds_selected{which} ||= 1;
510 };
511
512 sub clear_gds2 {
513 $widgets{gds2list} -> delete('all');
514 $gds_selected{which} = 0;
515 };
516
517 sub repopulate_gds2 {
518 my $which = $gds_selected{which};
519 clear_gds2();
520 populate_gds2();
521 $gds_selected{which} = ($which <= $#gds+1) ? $which : 1;
522 if (@gds) {
523 $gds_selected{which} ||= 1;
524 gds2_display($gds_selected{which});
525 };
526 };
527
528
529
530 ## no not make a new set of autoparams if this is a cloned feff calc
531 ## force all autoparams to be set if this is an older project that
532 ## does not contain autoparams
533 sub autoparams_define {
534 my ($id, $n, $is_clone, $force_set) = @_;
535 my @roman_lower = ("", qw(ii iii iv v vi vii viii ix x xi xii xii xiv xv
536 xvi xvii xviii xix xx xxi xxii xxiii xxiv xxv xxvi));
537 my @roman_upper = ("", qw(II III IV V VI VII VIII IX X XI XII XII XIV XV
538 XVI XVII XVIII XIX XX XXI XXII XXIII XXIV XXV XXVI));
539 my $tag = "_" . $n;
540 INC: {
541 $tag = "", last INC if ($n == 0);
542 $tag = "_" . $n, last INC if ($n > 26);
543 last INC if $config{autoparams}{data_increment} eq 'numbers';
544 $tag = "_" . chr(96+$n), last INC
545 if $config{autoparams}{data_increment} eq 'letters';
546 $tag = "_" . chr(64+$n), last INC
547 if $config{autoparams}{data_increment} eq 'LETTERS';
548 $tag = "_" . $roman_lower[$n], last INC
549 if $config{autoparams}{data_increment} eq 'roman';
550 $tag = "_" . $roman_upper[$n], last INC
551 if $config{autoparams}{data_increment} eq 'ROMAN';
552 };
553 my @list = ();
554 foreach my $p (qw(s02 e0 delr sigma2 ei third fourth)) {
555 my $this = $config{autoparams}{$p} . $tag;
556 push @list, ($config{autoparams}{$p}) ? $this : "";
557 next if (gds2_exists($this)); # do nothing else if this vble already exists
558 next unless $config{autoparams}{$p};
559 my $value = "0";
560 ($value = "1") if ($p eq 's02');
561 ($value = "0.003") if ($p eq 'sigma2');
562 my $type = ($force_set) ? 'set' : $config{autoparams}{$p.'_type'};
563 jump_to_variable($this, $type, 1, $value) unless $is_clone;
564 };
565 return @list;
566 };
567
568
569 ## actually just flag them all as updated, this will force artemis to
570 ## read from the GDS page rather than from ifeffit
571 sub reset_all_variables {
572 foreach (@gds) { $_->make(modified => 1) };
573 Echo("The initial guesses for all variables will be used rather than the best fit values the next time they are needed.");
574 };
575
576
577 sub clear_all_variables {
578 my $dialog =
579 $top -> Dialog(-bitmap => 'questhead',
580 -text => "Are you quite sure you want to discard all your variables?",
581 -title => 'Artemis: Verifying...',
582 -buttons => [qw/Discard Cancel/],
583 -default_button => 'Cancel',
584 -font => $config{fonts}{med},
585 -popover => 'cursor');
586 &posted_Dialog;
587 my $response = $dialog->Show();
588 Echo("Not discarding variables"), return if ($response eq 'Cancel');
589 clear_gds2();
590 $#gds = -1;
591 project_state(0);
592 $parameters_changed = 1;
593 $widgets{gds2_grab} -> configure(-state=>"disabled");
594 $widgets{gds2_name} -> configure(-text=>"");
595 $widgets{gds2_mathexp} -> configure(-text=>"");
596 $widgets{gds2_name} -> focus();
597 Echo("Discarded all variables.");
598 };
599
600
601 sub gds2_discard {
602 my @which = $widgets{gds2list} -> selectionGet();
603 my $this = $which[0] - 1;
604 my $name = ($#which > 0) ? "these parameters" : $gds[$this]->name;
605 ($name = "this separator") if (($#which == 0) and ($gds[$this]->type eq 'sep'));
606 my $dialog =
607 $top -> Dialog(-bitmap => 'questhead',
608 -text => "Do you really want to discard $name?",
609 -title => 'Artemis: Verifying...',
610 -buttons => [qw/Discard Cancel/],
611 -default_button => 'Cancel',
612 -font => $config{fonts}{med},
613 -popover => 'cursor');
614 &posted_Dialog;
615 my $response = $dialog->Show();
616 Echo("Not discarding $name"), return if ($response eq 'Cancel');
617 my $count = 0;
618 foreach my $w (@which) {
619 my $this = $w - 1 - $count;
620 splice(@gds, $this, 1);
621 ++$count;
622 };
623 repopulate_gds2();
624 $widgets{gds2_mathexp} -> focus();
625 project_state(0);
626 $parameters_changed = 1;
627 $name =~ s/these parameters/several parameters/;
628 Echo("Discarded $name");
629 };
630
631
632 ## highlight parameters and mathexps that match a regex
633 sub gds2_highlight {
634 my $regex;
635 my $dialog = get_string($dmode, "Highlight all parameters matching",
636 \$regex, \@gds_regex);
637 $dialog -> waitWindow; # the get_string dialog will be
638 # destroyed once the user hits ok,
639 # then we can move on...
640 Echo("Highlight aborted"), return unless $regex;
641 &gds2_clear_highlights;
642 my $re;
643 my $is_ok = eval '$re = qr/$regex/i';
644 Error("Oops! \"$regex\" is not a valid regular expression"), return unless $is_ok;
645 foreach my $i (0 .. $#gds) {
646 next if ($gds[$i]->type eq 'sep');
647 if ($gds[$i]->name =~ $re) {
648 $gds[$i]->highlight(1); # toggle the name bit
649 my $type = $gds[$i]->type . "_h";
650 $widgets{gds2list}->itemConfigure($i+1, 2, -style=>$gds_styles{$type});
651 };
652 if ($gds[$i]->mathexp =~ $re) {
653 $gds[$i]->highlight(2); # toggle the mathexp bit
654 my $type = $gds[$i]->type . "_h";
655 $widgets{gds2list}->itemConfigure($i+1, 3, -style=>$gds_styles{$type})
656 };
657 };
658 push @gds_regex, $regex;
659 Echo("Highlighted all parameters and math expressions matching /$regex/");
660 };
661
662 sub gds2_clear_highlights {
663 foreach my $i (0 .. $#gds) {
664 $gds[$i]->make(highlight=>0);
665 my $type = $gds[$i]->type;
666 $widgets{gds2list}->itemConfigure($i+1, 2, -style=>$gds_styles{$type."_n"});
667 $widgets{gds2list}->itemConfigure($i+1, 3, -style=>$gds_styles{$type});
668 };
669 };
670
671
672 sub gds2_move {
673 my $which = $_[0];
674 my $where = "";
675 my $whch = $widgets{gds2list}->info('anchor');
676 my $row = (ref($whch) eq 'ARRAY') ? $$whch[0] : $whch;
677 my $ip = $row-1;
678 if (($which eq 'before') or ($which eq 'after')) {
679 my $label = "Move " . $gds[$ip]->name . " $which (name or number): ";
680 my $dialog = get_string($dmode, $label, \$where);
681 $dialog -> waitWindow; # the get_string dialog will be
682 # destroyed once the user hits ok,
683 # then we can move on...
684 return unless ($where);
685 } elsif ($which eq 'up') {
686 return if ($ip == 0);
687 $where = $row - 1;
688 $which = 'before';
689 } elsif ($which eq 'down') {
690 return if ($ip == $#gds);
691 $where = $row + 1;
692 $which = 'after';
693 };
694
695 ## have the target, identify location in @gds array
696 my $target = -1;
697 if ($where =~ /^\d+$/) { # target was a parameter index
698 $target = $where-1;
699 ($target = $#gds) if ($target > $#gds);
700 ($target = 0) if ($target < 0);
701 } else { # target was a parameter name
702 foreach my $i (0..$ip-1, $ip+1..$#gds) {
703 ($target = $i), last if (lc($gds[$i]->name) eq lc($where));
704 };
705 };
706 Error("\"$where\" is not in the parameter list.\""), return if ($target == -1);
707
708 --$target if ($ip < $target);
709 my $save = splice(@gds, $ip, 1);
710 if ($which eq 'before') {
711 @gds = (@gds[0..$target-1], $save, @gds[$target..$#gds]);
712 $target += 1;
713 } elsif ($which eq 'after') {
714 @gds = (@gds[0..$target], $save, @gds[$target+1..$#gds]);
715 $target += 2;
716 };
717 repopulate_gds2();
718 gds2_display($target);
719 $widgets{gds2_mathexp} -> focus();
720 };
721
722
723 sub gds2_find {
724 my $whch = $widgets{gds2list}->info('anchor');
725 my $row = (ref($whch) eq 'ARRAY') ? $$whch[0] : $whch;
726 my $ip = $row-1;
727 my $which = $gds[$ip]->name;
728 my $message = "";
729
730 ## check for this variable's use in all def, set, and restraints
731 ## make sure the gsd data structures are up to date
732 my @all = map { $_->name } @gds;
733
734 foreach my $p (@gds) {
735 ($message .= "\tthe def parameter ".$p->name."\n") if
736 (($p->type eq 'def') and ($p->mathexp =~ /(^|\W)$which($|\W)/i));
737 ($message .= "\tthe set parameter ".$p->name."\n") if
738 (($p->type eq 'set') and ($p->mathexp =~ /(^|\W)$which($|\W)/i));
739 ($message .= "\tthe restraint ".$p->name."\n") if
740 (($p->type eq 'restrain') and ($p->mathexp =~ /(^|\W)$which($|\W)/i));
741 };
742
743
744 ## check for the parameter's use in all math expressions
745 my @paths = grep /feff\d+\.\d+/, keys(%paths); # fetch path list
746 foreach my $f (&path_list) {
747 next unless (ref($paths{$f}) =~ /Ifeffit/);
748 next unless ($paths{$f}->type eq 'path');
749 my $descriptor = $paths{$f}->descriptor();
750 foreach my $p (qw(s02 e0 delr sigma^2 ei 3rd 4th dphase k_array phase_array amp_array)) {
751 ($message .= "\tthe $p of $descriptor\n") if
752 ($paths{$f}->get($p) =~ /(^|\W)$which($|\W)/i);
753 };
754 };
755
756 Error("\"$which\" is not used in any math expression."), return
757 unless $message;
758 $message = "The parameter \"$which\" is used in:\n\n" . $message;
759 post_message($message, "Use of $which");
760
761 };
762
763
764
765 ## normally this is called from t he context menu in the GDS list.
766 ## The arguments allow this to be called as part of an import
767 ## of a feffit.inp file
768 sub gds2_search_replace {
769 my ($specified, $replacement) = @_;;
770 my $whch = $specified || $widgets{gds2list}->info('anchor');
771 my $row = (ref($whch) eq 'ARRAY') ? $$whch[0] : $whch;
772 my $ip = $row-1;
773 my $which = $gds[$ip]->name;
774
775 my $label = "New name for parameter \"$which\": ";
776 my $newname = $replacement || $which;
777 if (not $replacement) {
778 my $dialog = get_string($dmode, $label, \$newname, \@rename_buffer);
779 $dialog -> waitWindow; # the get_string dialog will be
780 # destroyed once the user hits ok,
781 # then we can move on...
782 Echo("Not renaming ". $which), return if ($which eq $newname);
783 Echo("Not renaming ". $which), return if ($newname =~ /^\s*$/);
784 };
785 Error("There is already a parameter called \"$newname\""), return if (grep {$_->name() =~ /^$newname$/} @gds);
786
787 $gds[$ip] -> make(name => $newname);
788 foreach my $p (@gds) {
789 if ($p->mathexp =~ /\b$which\b/) {
790 my $me = $p->mathexp;
791 $me =~ s/\b$which\b/$newname/g;
792 $p -> make(mathexp => $me);
793 };
794 };
795
796 foreach my $f (&path_list) {
797 next unless (ref($paths{$f}) =~ /Ifeffit/);
798 next unless ($paths{$f}->type eq 'path');
799 foreach my $p (qw(s02 e0 delr sigma^2 ei 3rd 4th dphase k_array phase_array amp_array)) {
800 my $me = $paths{$f}->get($p);
801 if ($me =~ /\b$which\b/) {
802 $me =~ s/\b$which\b/$newname/g;
803 $paths{$f} -> make($p => $me);
804 };
805 };
806 };
807
808 repopulate_gds2();
809 project_state(0);
810 Echo("Renamed \"$which\" as \"$newname\" and replaced it throughout the project.");
811 };
812
813 sub gds2_locate {
814 my $label = "Name of variable to locate: ";
815 my $name = "";
816 my $dialog = get_string($dmode, $label, \$name);
817 $dialog -> waitWindow; # the get_string dialog will be
818 # destroyed once the user hits ok,
819 # then we can move on...
820 return if ($name =~ /^\s*$/);
821 my $found = -1;
822 my $i = 0;
823 foreach my $p (@gds) {
824 next if ($p->type eq 'sep');
825 ($found = $i), last if (lc($p->name) eq lc($name));
826 ++$i;
827 };
828
829 Error("You don't have a variable called \"$name\""), return if ($found == -1);
830 gds2_display($found+1);
831 };
832
833
834 sub gds2_show {
835 my $string = "";
836
837 $notes{messages} -> delete(qw(1.0 end));
838 my $len = 0;
839 foreach (@gds) {
840 ($len = length($_->name)) if (length($_->name) > $len);
841 };
842 my $sep = "-" x ($len+25);
843 $len = '%-' . $len . "s";
844 foreach (@gds) {
845 if ($_->type eq 'sep') {
846 $notes{messages} -> insert('end', "-" x 9);
847 } else {
848 $notes{messages} -> insert('end', sprintf("%-8s ", $_->type), $_->type);
849 };
850 if ($_->type eq 'skip') {
851 $notes{messages} -> insert('end', sprintf($len, $_->name), 'skip');
852 $notes{messages} -> insert('end', sprintf(" = %s\n", $_->mathexp), 'skip');
853 } elsif ($_->type eq 'guess') {
854 $notes{messages} -> insert('end', sprintf($len, $_->name), 'guess2');
855 $notes{messages} -> insert('end', sprintf(" = %s\n", $_->mathexp), 'guess2');
856 } elsif ($_->type eq 'sep') {
857 $notes{messages} -> insert('end', $sep . "\n");
858 } else {
859 $notes{messages} -> insert('end', sprintf($len, $_->name));
860 $notes{messages} -> insert('end', sprintf(" = %s\n", $_->mathexp));
861 };
862 };
863 $notes{messages} -> yviewMoveto(0);
864 $top -> update;
865 raise_palette('messages');
866 };
867
868
869
870 sub gds2_up {
871 return unless ($current_canvas eq 'gsd');
872 gds2_move('up');
873 };
874 sub gds2_down {
875 return unless ($current_canvas eq 'gsd');
876 gds2_move('down');
877 };
878
879 sub gds2_post_menu {
880
881 ## figure out where the user clicked
882 my $w = shift;
883 my $Ev = $w->XEvent;
884 delete $w->{'shiftanchor'};
885 my $entry = $w->GetNearest($Ev->y, 1);
886 return unless (defined($entry) and length($entry));
887
888 ## select and anchor the right-clicked parameter
889 my @which = $w->selectionGet();
890 $w->anchorSet($entry);
891 my $clicked = $w->info('anchor');
892
893 if (grep {/^$clicked$/} @which) {
894 ## right click within the current extended selection
895 1;
896 } else {
897 ## right clicked outside the current extended selection
898 $w->selectionClear;
899 $w->selectionSet($entry);
900 @which = $w->selectionGet();
901 };
902 gds2_browse($w, \%gds_selected);
903
904 ## post the message with parameter-appropriate text
905 my ($name, $index, $type);
906 if ($#which > 0) {
907 $index = $w->info('anchor') - 1;
908 $name = "these parameters";
909 $type = 'extended';
910 } else {
911 $index = $which[0] - 1;
912 $name = '"'.$gds[$index]->name.'"';
913 $type = $gds[$index]->type;
914 };
915 return if ($gds[$index]->type eq 'sep');
916 my $anchor = '"'.$gds[$index]->name.'"';
917 my ($X, $Y) = ($Ev->X, $Ev->Y);
918 ## my $isare = ($#which>0) ? "are" : "is";
919 $top ->
920 Menu(-tearoff=>0,
921 -menuitems=>[
922 (($gds_selected{showing} eq 'show') ?
923 ([ command=>"Edit $anchor",
924 #-state =>($#which>0) ? 'disabled' : 'normal',
925 -command=>sub{$widgets{gds2_show}->packForget;
926 $widgets{gds2_editarea}->pack(-side=>=>'top', -fill=>'x', -padx=>4, -pady=>2);
927 $gds_selected{showing}="edit";}],
928 ) :
929 ()),
930 [ cascade=>"Make $name ...",
931 -tearoff=>0,
932 -menuitems=>[
933 [ command => "guess",
934 -command => [\&gds2_make, 'guess']],
935 [ command => "def",
936 -command => [\&gds2_make, 'def']],
937 [ command => "set",
938 -command => [\&gds2_make, 'set']],
939 [ command => "skip",
940 -command => [\&gds2_make, 'skip']],
941 [ command => "restraint",
942 -command => [\&gds2_make, 'restrain']],
943 [ command => "after",
944 -command => [\&gds2_make, 'after']],
945 ]],
946 [ cascade=>"Move $anchor ...",
947 -tearoff=>0,
948 #-state =>($#which>0) ? 'disabled' : 'normal',
949 -menuitems=>[
950 [ command=>"before ...",
951 -command=>sub{gds2_move("before")}],
952 [ command=>"after ...",
953 -command=>sub{gds2_move("after")}],
954 ]],
955 [ cascade=>"Insert separator ...",
956 -tearoff=>0,
957 ##-state =>'disabled',
958 -menuitems=>[
959 [ command=>"before ...",
960 -command=>sub{gds2_sep("before")}],
961 [ command=>"after ...",
962 -command=>sub{gds2_sep("after")}],
963 ]],
964 [ command=>"Copy $anchor",
965 -command=>\&gds2_copy],
966 "-",
967 [ command=>"Build restraint from $anchor",
968 -command=>\&gds2_build_restraint,
969 -state =>($gds[$index]->type =~ /(def|guess)/) ? 'normal' : 'disabled'],
970 [ command=>"Annotate $anchor",
971 #-state =>($#which>0) ? 'disabled' : 'normal',
972 -command=>\&gds2_annotation],
973 [ command=>"Grab best fit for $anchor",
974 #-state=>($type eq 'guess') ? 'normal' : 'disabled'
975 -command=>sub{grab_gds2($widgets{gds2list}, \%gds_selected)},],
976 "-",
977 [ command=>"Find where $anchor is used",
978 #-state =>($#which>0) ? 'disabled' : 'normal',
979 -command=>\&gds2_find],
980 [ command=>"Change name of $anchor globally",
981 #-state =>($#which>0) ? 'disabled' : 'normal',
982 -command=>\&gds2_search_replace],
983 "-",
984 [ command=>"Discard $name",
985 -command=>\&gds2_discard],
986 ])
987 -> Post($X, $Y);
988 $w -> break;
989 };
990
991 sub gds2_sep {
992 my $which = $widgets{gds2list} -> info('anchor') - 1;
993 --$which if ($_[0] eq 'before');
994
995 splice(@gds, $which, 1, $gds[$which],
996 Ifeffit::Parameter->new(type => "sep",));
997
998 repopulate_gds2();
999 project_state(0);
1000 Echo("Inserted separator $_[0] ");
1001 };
1002
1003 sub gds2_build_restraint {
1004 my $which = $widgets{gds2list} -> info('anchor') - 1;
1005 my $name = $gds[$which]->name;
1006
1007 my %restraint;
1008 $restraint{min} = int(Ifeffit::get_scalar($name)/10) || 0;
1009 my $bf = $gds[$which]->bestfit; # watch out for math expressions
1010 ($bf =~ /-?(\d+\.?\d*|\.\d+)/) or ($bf = 0);
1011 $restraint{max} = int(Ifeffit::get_scalar($name)*2) || 2*$bf || 10;
1012 $restraint{amp} = int(Ifeffit::get_scalar("chi_reduced")/20)*100 || 1000;
1013
1014
1015 my $db = $top -> DialogBox(-title=>"Artemis: Restraint builder",
1016 -buttons=>['Build restraint', 'Cancel'],
1017 -default_button=>'Build restraint');
1018 my $fr = $db->Frame(-borderwidth=>2, -relief=>'flat')->pack(-pady=>5);
1019 $fr -> Label(-text=>"Restrain \"$name\" to be within these boundaries",
1020 -font=>$config{fonts}{large},
1021 -foreground=>$config{colors}{activehighlightcolor})
1022 -> pack(-side=>'top');
1023 $fr = $db->Frame(-borderwidth=>2, -relief=>'groove')
1024 -> pack(-fill=>'x', -expand=>1, -padx=>2);
1025 $fr -> Label(-text=>'Minimum value:',
1026 -font=>$config{fonts}{large},
1027 -foreground=>$config{colors}{activehighlightcolor})
1028 -> grid(-row=>0, -column=>0, -sticky=>'w', -pady=>2);
1029 $fr -> Entry(-textvariable=>\$restraint{min},
1030 -width=>8)
1031 -> grid(-row=>0, -column=>1, -sticky=>'e', -pady=>2);
1032
1033 $fr -> Label(-text=>'Maximum value:',
1034 -font=>$config{fonts}{large},
1035 -foreground=>$config{colors}{activehighlightcolor})
1036 -> grid(-row=>1, -column=>0, -sticky=>'w', -pady=>2);
1037 $fr -> Entry(-textvariable=>\$restraint{max},
1038 -width=>8)
1039 -> grid(-row=>1, -column=>1, -sticky=>'e', -pady=>2);
1040
1041 $fr -> Label(-text=>'Amplifier:',
1042 -font=>$config{fonts}{large},
1043 -foreground=>$config{colors}{activehighlightcolor})
1044 -> grid(-row=>2, -column=>0, -sticky=>'w', -pady=>2);
1045 $fr -> Entry(-textvariable=>\$restraint{amp},
1046 -width=>8)
1047 -> grid(-row=>2, -column=>1, -sticky=>'e', -pady=>2);
1048 &posted_Dialog;
1049 my $answer = $db -> Show;
1050 return 0 if ($answer eq 'Cancel');
1051
1052 push @gds, Ifeffit::Parameter->new(type => "restrain",
1053 name => "res_".$name,
1054 mathexp => "penalty($name, $restraint{min}, $restraint{max}) * $restraint{amp}",
1055 bestfit => 0,
1056 modified => 1,
1057 note => "$name: ",
1058 autonote => 1);
1059 repopulate_gds2();
1060 project_state(0);
1061 $parameters_changed = 1;
1062 $which = $#gds + 1;
1063 &gds2_display($which);
1064 $widgets{gds2_name} -> focus;
1065 $widgets{gds2_name} -> icursor('end');
1066 $widgets{gds2_name} -> selectionRange(0, 'end');
1067
1068 Echo("Built restraint " . $gds[-1]->name . " = " . $gds[-1]->mathexp);
1069 };
1070
1071 sub gds2_make {
1072 my @list = $widgets{gds2list}->selectionGet;
1073 foreach my $w (@list) {
1074 gds2_display($w);
1075 $gds_selected{type}=$_[0];
1076 &gds2_alter
1077 }
1078 $widgets{gds2list}->selectionClear;
1079 map {$widgets{gds2list}->selectionSet($_)} @list;
1080 };
1081
1082
1083 sub gds2_keyboard_type {
1084 return unless ($current_canvas eq 'gsd');
1085 my $who = $top->focusCurrent;
1086 $multikey = "";
1087 Echo("Make parameter [gsdkra] (g=guess s=set d=def k=skip r=restraint a=after)");
1088 $echo -> focus();
1089 $echo -> grab;
1090 $echo -> waitVariable(\$multikey);
1091 $echo -> grabRelease;
1092 $who -> focus;
1093 Echo("$multikey is not a parameter type (guess=g set=s def=d skip=k restraint=r after=a)"), return unless (lc($multikey) =~ /^[degksr]$/);
1094 SWITCH: {
1095 $gds_selected{type} = 'guess', last SWITCH if (lc($multikey) eq 'g');
1096 $gds_selected{type} = 'def', last SWITCH if (lc($multikey) eq 'd');
1097 $gds_selected{type} = 'set', last SWITCH if (lc($multikey) eq 's');
1098 $gds_selected{type} = 'skip', last SWITCH if (lc($multikey) eq 'k');
1099 $gds_selected{type} = 'restrain', last SWITCH if (lc($multikey) eq 'r');
1100 $gds_selected{type} = 'after', last SWITCH if (lc($multikey) eq 'a');
1101 };
1102 &gds2_alter;
1103 Echo("Made parameter a $gds_selected{type}");
1104 };
1105
1106
1107
1108 ## various sanity checks to be done before a fit
1109
1110 sub verify_number_of_variables {
1111 my $total = 0;
1112 foreach my $p (@gds) {
1113 ++$total if ($p->type eq 'guess')
1114 };
1115 my $bkg = 0;
1116 foreach my $d (&all_data) {
1117 next unless ($paths{$d}->get('do_bkg') eq 'yes');
1118 my $deltak = $paths{$d}->get('kmax') - $paths{$d}->get('kmin');
1119 my $deltar = $paths{$d}->get('rmax') - $paths{$d}->get('rmin');
1120 my $this = int( 2 * $deltak * $deltar / PI );
1121 ($this = 5) if ($this < 5);
1122 ($this = $limits{spline_knots}) if ($this > $limits{spline_knots});
1123 $total += $this;
1124 $bkg += $this;
1125 };
1126 if ($total > $limits{variables}) {
1127 my $string = "You have used $total guess parameters";
1128 $string .= ($bkg) ? " and $bkg background parameters.\n" : ".\n";
1129 $string .= "This exceeds Ifeffit's limit of $limits{variables} variable parameters.";
1130 return $string;
1131 };
1132 return "";
1133 }
1134
1135
1136 sub verify_parameters {
1137 my @params = ();
1138 foreach my $p (@gds) {
1139 push @params, lc($p->name) unless ($p->type =~ /(after|sep|skip)/);
1140 };
1141 my @def_restraint = ();
1142 foreach my $p (@gds) {
1143 push @def_restraint, lc($p->name) if ($p->type =~ /(def|restrain)/)
1144 }
1145 my $param_regex = lc(join("|", @params, '_^@_'));
1146
1147 my (%not_defined, %used, %functions);
1148 my @unused_defs = ();
1149 ## look at all the path parameters ...
1150 foreach my $k (keys %paths) {
1151 next unless (ref($paths{$k}) =~ /Ifeffit/);
1152 next unless ($paths{$k}->type eq 'path');
1153 next unless ($paths{$k}->get('include'));
1154 my $this_data = $paths{$k}->data;
1155 next unless ($paths{$this_data}->get('include'));
1156 foreach my $p (qw(s02 e0 delr sigma^2 ei 3rd 4th dphase k_array phase_array amp_array)) {
1157 my $str = $paths{$k}->get($p);
1158 if ($str and ($str !~ /^\s+$/)) {
1159 $str =~ s/[ \t]+//g; # remove spaces
1160 $str =~ s/\(/\( /g; # put a space after an open paren
1161 foreach my $w (split(/[^a-zA-Z_0-9.\(]+/, $str)) {
1162 next if (lc($w) =~ /(etok|pi|reff)/); # special words
1163 next if ($w =~ /^(\d+\.?\d*|\.\d+)$/); # a number or float
1164 next if ($w eq ""); # this happens with a leading minus sign
1165 if ($w =~ /\($/) { # this was a function, e.g. debye(
1166 my $ww = lc(substr($w, 0, -1));
1167 push @{$functions{$ww}}, $paths{$k}->get('lab');
1168 next;
1169 };
1170 ## push this path onto the list of paths using this bogus variable
1171 (lc($w) =~ /^($param_regex)$/) or
1172 push @{$not_defined{lc($w)}}, "the $p of " . $paths{$k}->descriptor();
1173 ++$used{lc($w)}; # mark it as used
1174 };
1175 };
1176 };
1177 };
1178 ## ... then look at all the def expressions
1179 foreach my $d (@def_restraint) {
1180 my ($type, $str);
1181 foreach my $p (@gds) {
1182 next unless (lc($p->name) eq lc($d));
1183 $type = $p->type;
1184 $str = $p->mathexp;
1185 last;
1186 };
1187 #print join("|", $d, $type, $str), $/;
1188 if ($str and ($str !~ /^\s+$/)) {
1189 $str =~ s/[ \t]+//g; # remove spaces
1190 $str =~ s/\(/\( /g; # put a space after an open paren
1191 foreach my $w (split(/[^a-zA-Z_0-9.\(]+/, $str)) {
1192 next if (lc($w) =~ /(etok|pi|reff)/); # special words
1193 next if ($w =~ /^(\d+\.?\d*|\.\d+)$/); # a number or float
1194 next if ($w eq ""); # this happens with a leading minus sign
1195 if ($w =~ /\($/) { # this was a function, e.g. debye(
1196 my $ww = lc(substr($w, 0, -1));
1197 push @{$functions{$ww}},
1198 ($type eq 'def') ? "the def parameter \`$d\'" :
1199 "the restraint \`$d\'";
1200 next;
1201 };
1202 ## push this path onto the list of paths using this bogus variable
1203 (lc($w) =~ /^($param_regex)$/) or
1204 push @{$not_defined{lc($w)}},
1205 ($type eq 'def') ? "the def parameter \`$d\'" :
1206 "the restraint \`$d\'";
1207 ++$used{lc($w)}; # mark it as used
1208 };
1209 };
1210 };
1211 my $message = "";
1212 foreach my $p (@params) { # unused guess parameters
1213 next if $used{lc($p)};
1214 my $this;
1215 foreach my $pp (@gds) {
1216 next unless ($pp->name eq $p);
1217 $this = $pp;
1218 last;
1219 };
1220 next unless $this;
1221 my $choice = $this->type;
1222 next if ($choice =~ /(after|restrain|set)/);
1223 $message .= " \`$p\' was defined as a $choice but not used\n";
1224 push @unused_defs, $p if ($choice eq 'def');
1225 };
1226 foreach my $p (keys %not_defined) { # undefined parameters in math expressions
1227 $message .= " \`$p\' was not defined but was used in:\n " .
1228 join("\n ", @{$not_defined{lc($p)}});
1229 $message .= $/;
1230 };
1231 foreach my $f (keys %functions) { # unknown functions
1232 next if ($f =~ /^($function_regex)$/);
1233 next if ($f =~ /^\s*$/);
1234 $message .= " \`$f\' is not a valid Ifeffit function but was used in:\n " .
1235 join("\n ", @{$functions{lc($f)}});
1236 $message .= $/;
1237 };
1238 if ($message) {
1239 $message = "Errors in parameters and math expressions:\n\n" .
1240 $message .
1241 "\n\nRemember that set parameter are evaluated once at the\n" .
1242 "beginning of the fit, def parameters are re-evaluated\n" .
1243 "as the fit progresses, and after parameters are evaluated\n" .
1244 "after the fit is finished.";
1245 };
1246 return ($message, \@unused_defs);
1247 #print "used: ", join(" ", %used), $/;
1248 #print "not_defined: ", join(" ", keys %not_defined), $/;
1249 }
1250
1251
1252 ## see http://www.perlmonks.org/index.pl?node_id=38942
1253 sub check_parens {
1254 my $count = 0;
1255 foreach my $c (split(//, $_[0])) {
1256 ++$count if ($c eq '(');
1257 --$count if ($c eq ')');
1258 return $count if $count < 0;
1259 };
1260 return $count;
1261 };
1262
1263
1264 sub verify_parens {
1265 my @trouble = ();
1266 ## check the params for balanced parens
1267 foreach my $p (@gds) {
1268 next if ($p->type =~ /s(e|ki)p/);
1269 my $tag = "\tthe " . $p->type . " variable " . $p->name;
1270 ($tag = "\tthe restraint " . $p->name) if ($p->type eq 'restrain');
1271 push @trouble, $tag if check_parens($p->mathexp);
1272 };
1273 foreach my $k (keys %paths) {
1274 next unless (ref($paths{$k}) =~ /Ifeffit/);
1275 next unless ($paths{$k}->type eq 'path');
1276 next unless ($paths{$k}->get('include'));
1277 foreach my $p (qw (s02 e0 delr sigma^2 ei 3rd 4th dphase k_array phase_array amp_array)) {
1278 next unless defined $paths{$k}->get($p);
1279 next if ($paths{$k}->get($p) =~ /^\s*$/); # could be empty string
1280 next unless $paths{$k}->get($p); # could be 0
1281 my $tag = "\tthe $p for \"" . $paths{$k}->descriptor() . "\"";
1282 push @trouble, $tag if check_parens($paths{$k}->get($p));
1283 };
1284 };
1285 return "" unless @trouble;
1286 return "These math expressions seem to have unbalanced parentheses:\n" .
1287 join("\n", @trouble) .
1288 "\n\n";
1289 };
1290
1291 sub verify_operators {
1292 my @trouble = ();
1293 my $repeats = '\+\+|\-\-|\/\/|\*\*\*|\^\^';
1294 foreach my $p (@gds) {
1295 next if ($p->type =~ /s(e|ki)p/);
1296 next unless ($p->mathexp =~ /($repeats)/);
1297 push @trouble, sprintf("\tthe %s parameter \"%s\" has: %s",
1298 $p->type, $p->name, $1);
1299 };
1300 foreach my $k (keys %paths) {
1301 next unless (ref($paths{$k}) =~ /Ifeffit/);
1302 next unless ($paths{$k}->type eq 'path');
1303 next unless ($paths{$k}->get('include'));
1304 foreach my $p (qw (s02 e0 delr sigma^2 ei 3rd 4th dphase k_array phase_array amp_array)) {
1305 next unless defined $paths{$k}->get($p);
1306 my $mathexp = $paths{$k}->get($p);
1307 next if ($mathexp =~ /^\s*$/); # could be empty string
1308 next unless $mathexp; # could be 0
1309 next unless ($mathexp =~ /($repeats)/);
1310 push @trouble, sprintf("\tthe %s expression for path \"%s\" has: %s",
1311 $p, $paths{$k}->descriptor, $1);
1312 };
1313 };
1314 return q{} unless @trouble;
1315 return "These math expressions have invalid binary operators:\n" .
1316 join("\n", @trouble) .
1317 "\n\n";
1318 };
1319
1320
1321 ## do not allow GDS parameters to take the names of ifeffit's program
1322 ## variables. the $progvar_regex list are the pre-defined batch of
1323 ## program variables. The delta_* and correl_*_* program variables
1324 ## will be generated by feffit()ing or minimize()ing. The feff\d_\d_*
1325 ## variables are generated by get_path(). in fact the regex for that
1326 ## last one is incorrect -- it covers parts of the namespace that
1327 ## might not be used (feff087620_7652000_ei, for example), but it is a
1328 ## nice 'n' simple regex and an uncommon string for a GDS name. note
1329 ## also that "feff\d+_\d+" matches Artemis' convention for path group
1330 ## names.
1331 sub verify_ifeffit_program_variables {
1332 my $progvar_regex = # all of feffit's pre-defined program variables
1333 "c(hi_(reduced|square)|or(e_width|rel_min)|ursor_[xy])"
1334 . "|d([kr]|ata_(set|total)|k([12]|1_spl|2_spl)|r[12])"
1335 . "|e(0|dge_step|psilon_[kr]|tok)"
1336 . "|k(m(ax(|_s(pl|uggest))|in(|_spl))|w(eight(|_spl)|indow))"
1337 . "|n(_(idp|varys)|column_label|knots|orm([12]|_c[012]))"
1338 . "|p(ath_index|i|re([12]|_(offset|slope)))"
1339 . "|q(max_out|sp)"
1340 . "|r(_factor|bkg|m(ax(|_out)|in)|sp|w(eight|in(|dow)))"
1341 . "|toler";
1342 my $path_param_regex = "d(e(gen|lr)|phase)|e[0i]|fourth|reff|s(02|igma2)|third";
1343
1344 my @params = ();
1345 foreach my $p (@gds) {
1346 push @params, lc($p->name) unless ($p->type =~ /(sep|skip)/);
1347 };
1348 my $param_regex = lc(join("|", @params, '_^@_'));
1349 my @match = ();
1350 foreach my $p (@params) {
1351 push @match, $p if (lc($p) =~ /^($progvar_regex)$/);
1352 push @match, $p if (lc($p) =~ /^delta_($param_regex)$/);
1353 push @match, $p if (lc($p) =~ /^correl_($param_regex)_($param_regex)$/);
1354 push @match, $p if (lc($p) =~ /^feff\d+_\d+_($path_param_regex)$/);
1355 };
1356 return q{} unless @match;
1357 my $common = "One common example of this sort is a variable named \"dr1\", which\nshould be changed to something like \"dr_1\" or \"drone\".\n\n";
1358 if ($#match) {
1359 return "These parameters use names which have special meaning in Ifeffit:\n\t" .
1360 join("\n\t", @match) .
1361 "\nYou must change those parameter names before attempting to fit.\n" .
1362 $common;
1363 } else {
1364 return "This parameter uses a name which has special meaning in Ifeffit:\n\t" .
1365 join("\n\t", @match) .
1366 "\nYou must change this parameter name before attempting to fit.\n" .
1367 $common;
1368 }
1369 };
1370
1371 ## return a list of the number of merges and the index of the first
1372 ## merge in the list
1373 sub count_merge {
1374 my $total = 0;
1375 my $first = 0;
1376 foreach my $p (@gds) {
1377 ++$first unless $total;
1378 next unless ($p->type eq 'merge');
1379 ++$total;
1380 };
1381 return ($total, $first);
1382 };
1383
1384 sub check_idp {
1385 my ($nidp, $ndat, $nvar) = (0,0,0);
1386 foreach my $data (&all_data) {
1387 my $deltak = $paths{$data}->get('kmax') - $paths{$data}->get('kmin');
1388 my $deltar = $paths{$data}->get('rmax') - $paths{$data}->get('rmin');
1389 $nidp += int( 2 * $deltak * $deltar / PI );
1390 ++$ndat;
1391 };
1392 foreach my $p (@gds) {
1393 next if ($p->name =~ /^\s*$/);
1394 ++$nvar if ($p->type eq 'guess');
1395 };
1396 my $s = ($ndat >1) ? "s" : q{};
1397 return ($nidp < $nvar) ?
1398 "ERROR! You have used $nvar variables but only have $nidp independent\nmeasurements in $ndat data set$s.\n" :
1399 "";
1400 };
1401
1402
1403 sub gds2_import_text {
1404 my $path = $current_data_dir || cwd;
1405 my $types = [['Exported variables', '*.variables'], ['All files', '*']];
1406 my $file = $top -> getOpenFile(-filetypes=>$types,
1407 ##(not $is_windows) ?
1408 ## (-sortcmd=>sub{$Tk::FBox::a cmp $Tk::FBox::b}) : () ,
1409 -initialdir=>$path,
1410 -title => "Artemis: Import a list of variables");
1411 return unless ($file);
1412 my ($name, $feff_path, $suffix) = fileparse($file);
1413 $current_data_dir = $feff_path;
1414
1415 my $view = $#gds+2;
1416 open V, $file or die "could not open $file for reading variables\n";
1417 while (<V>) {
1418 next unless (/^\s*(after|def|guess|merge|restrain|s(et|ep|kip))\b/);
1419 chomp;
1420 my @line = split(/\s*[ \t=]\s*/, $_);
1421 my $type = shift @line;
1422 my $name = shift @line;
1423 my $val = join("", @line);
1424 $val =~ s/[!%#].*$//; # ease puts end-of-line comments on
1425 # guess lines
1426 my $which = -1;
1427 my $see = 0;
1428 foreach (@gds) {
1429 ++$see;
1430 $which = $_, last if ($_->name =~ /^$name$/i);
1431 };
1432 ## or for the end of the list
1433 if ($which == -1) {
1434 if ($type eq 'sep') {
1435 push @gds, Ifeffit::Parameter->new(type => "sep",);
1436 } else {
1437 push @gds, Ifeffit::Parameter->new(type => $type,
1438 name => $name,
1439 mathexp => $val,
1440 bestfit => 0,
1441 modified => 1,
1442 note => "$name: ",
1443 autonote => 1,
1444 );
1445 };
1446 $see = $#gds;
1447 $which = $gds[$see];
1448 ++$see;
1449 };
1450 };
1451 ($view = 1) if ($view > $#gds+1);
1452 repopulate_gds2();
1453 gds2_display($view);
1454 display_page("gsd");
1455 project_state(0);
1456 $parameters_changed = 1;
1457
1458 close V;
1459
1460 };
1461
1462
1463 sub gds2_export_text {
1464 my $path = $current_data_dir || cwd;
1465 my $types = [['All Files', '*'],['Text Files', '*.txt']];
1466 my $file = $top -> getSaveFile(-filetypes=>$types,
1467 ##(not $is_windows) ?
1468 ## (-sortcmd=>sub{$Tk::FBox::a cmp $Tk::FBox::b}) : () ,
1469 -initialfile=>'artemis.variables',
1470 -initialdir=>$path,
1471 -title => "Artemis: Export a list of variables");
1472 return unless ($file);
1473 my ($name, $feff_path, $suffix) = fileparse($file);
1474 $current_data_dir = $feff_path;
1475
1476 my $len = 0;
1477 foreach (@gds) {
1478 ($len = length($_->name)) if (length($_->name) > $len);
1479 };
1480 $len++;
1481
1482 open V, '>'.$file or die "could not open $file for writing variables\n";
1483 print V "# List of parameters from Artemis\n";
1484 print V "# ", $props{'Project title'}, $/, $/;
1485
1486 my $pattern = "%-9s %-" . $len . "s = %s\n";
1487 #print $len, " --- ", $pattern, $/;
1488 foreach (@gds) {
1489 printf V $pattern, $_->type, $_->name, $_->mathexp;
1490 };
1491 close V;
1492 };
1493
1494 ## END OF THE SECTION ON THE GDS PAGE
1495