source: trunk/addcmds.tcl @ 721

Last change on this file since 721 was 721, checked in by toby, 14 years ago

# on 2003/08/11 19:19:37, toby did:
add support for adding multiple histograms
code cleanup -col -> -column

  • Property rcs:author set to toby
  • Property rcs:date set to 2003/08/11 19:19:37
  • Property rcs:lines set to +195 -16
  • Property rcs:rev set to 1.32
  • Property rcs:state set to Exp
  • Property svn:keywords set to Author Date Revision Id
File size: 70.0 KB
Line 
1# $Id: addcmds.tcl 721 2009-12-04 23:10:54Z toby $
2
3#----------- Add Phase routines ----------------------------------------
4
5proc MakeAddPhaseBox {} {
6    global expmap expgui
7
8    set expgui(coordList) {}
9    set nextphase ""
10    foreach p {1 2 3 4 5 6 7 8 9} {
11        if {[lsearch $expmap(phaselist) $p] == -1} {
12            set nextphase $p
13            break
14        }
15    }
16
17    # no more room
18    if {$nextphase == ""} {
19        MyMessageBox -parent . -title "Add Phase Error" \
20                -message "There are already 9 phases. You cannot add more." \
21                -icon error
22        return
23    }
24
25    set np .newphase
26    catch {destroy $np}
27    toplevel $np
28    bind $np <Key-F1> "MakeWWWHelp expgui2.html addphase"
29
30    grid [label $np.l1 -text "Adding phase #$nextphase"] \
31            -column 0 -row 0 -sticky w
32    grid [label $np.l2 -text "Phase title:"] -column 0 -row 1 
33    grid [entry $np.t1 -width 68] -column 1 -row 1 -columnspan 8
34    grid [label $np.l3 -text "Space Group:"] -column 0 -row 2 
35    grid [entry $np.t2 -width 12] -column 1 -row 2 
36    grid [frame $np.f -bd 4 -relief groove] -column 3 -row 2 -columnspan 8
37    set col -1
38    foreach i {a b c} {
39        grid [label $np.f.l1$i -text " $i "] -column [incr col] -row 1
40        grid [entry $np.f.e1$i -width 12] -column [incr col]  -row 1
41    }
42    set col -1
43    foreach i {a b g} {
44        grid [label $np.f.l2$i -text $i] -column [incr col] -row 2
45        set font [$np.f.l2$i cget -font]
46        $np.f.l2$i config -font "Symbol [lrange $font 1 end]"
47        grid [entry $np.f.e2$i -width 12] -column [incr col]  -row 2
48        $np.f.e2$i insert 0 90.
49    }   
50   
51    grid [frame $np.bf] -row 3 -column 0 -columnspan 10 -sticky ew
52    grid [button $np.bf.b1 -text Add \
53            -command "addphase $np"] -column 2 -row 3
54    bind $np <Return> "addphase $np"
55    grid [button $np.bf.b2 -text Cancel \
56            -command "destroy $np"] -column 3 -row 3
57    grid columnconfig $np.bf 4 -weight 1
58    grid [button $np.bf.help -text Help -bg yellow \
59            -command "MakeWWWHelp expgui2.html addphase"] \
60            -column 4 -row 3
61
62    # get the input formats if not already defined
63    GetImportFormats
64    if {[llength $expgui(importFormatList)] > 0} {
65        grid [frame $np.bf.fr -bd 4 -relief groove] -column 5 -row 3
66        grid [button $np.bf.fr.b3 -text "Import phase from: " \
67                -command "ImportPhase \$expgui(importFormat) $np"] \
68                -column 0 -row 0 -sticky e
69        set menu [eval tk_optionMenu $np.bf.fr.b4 expgui(importFormat) \
70                $expgui(importFormatList)]
71        for {set i 0} {$i <= [$menu index end]} {incr i} {
72            $menu entryconfig $i -command "ImportPhase \$expgui(importFormat) $np"
73        }
74        grid $np.bf.fr.b4 -column 1 -row 0 -sticky w
75        grid rowconfig $np.bf.fr 0 -pad 10
76        grid columnconfig $np.bf.fr 0 -pad 10
77        grid columnconfig $np.bf.fr 1 -pad 10
78    }
79    wm title $np "add new phase"
80
81    # set grab, etc.
82    putontop $np
83   
84    tkwait window $np
85   
86    # fix grab...
87    afterputontop
88}
89
90proc addphase {np} {
91    global expgui expmap
92    # validate the input
93    set err {}
94    set title [$np.t1 get]
95    if {[string trim $title] == ""} {
96        append err "  Title cannot be blank\n"
97    }
98    set spg [$np.t2 get]
99    if {[string trim $spg] == ""} {
100        append err "  Space group cannot be blank\n"
101    }
102    foreach i {a b c} {
103        set cell($i) [$np.f.e1$i get]
104        if {[string trim $cell($i)] == ""} {
105            append err "  $i cannot be blank\n"
106        } elseif {[catch {expr $cell($i)}]} {
107            append err "  $i is not valid\n"
108        }
109    }
110
111    foreach i {a b g} lbl {alpha beta gamma} {
112        set cell($lbl) [$np.f.e2$i get]
113        if {[string trim $cell($lbl)] == ""} {
114            append err "  $lbl cannot be blank\n"
115        } elseif {[catch {expr $cell($lbl)}]} {
116            append err "  $lbl is not valid\n"
117        }
118    }
119
120    if {$err != ""} {
121        MyMessageBox -parent . -title "Add Phase Error" \
122                -message "The following error(s) were found in your input:\n$err" \
123                -icon error
124        set expgui(oldphaselist) -1
125        return
126    }
127
128    # check the space group
129    set fp [open spg.in w]
130    puts $fp "N"
131    puts $fp "N"
132    puts $fp $spg
133    puts $fp "Q"
134    close $fp
135    global tcl_platform
136    catch {
137        if {$tcl_platform(platform) == "windows"} {
138            exec [file join $expgui(gsasexe) spcgroup.exe] < spg.in >& spg.out
139        } else {
140            exec [file join $expgui(gsasexe) spcgroup] < spg.in >& spg.out
141        }
142    }
143    set fp [open spg.out r]
144    set out [read $fp]
145    close $fp
146    # attempt to parse out the output (fix up if parse did not work)
147    if {[regexp "space group symbol.*>(.*)Enter a new space group symbol" \
148            $out a b ] != 1} {set b $out}
149    if {[string first Error $b] != -1} {
150        # got an error, show it
151        ShowBigMessage \
152                 $np.error \
153                 "Error processing space group\nReview error message below" \
154                 $b OK "" 1
155        set expgui(oldphaselist) -1
156        return
157    } else {
158        # show the result and confirm
159        set opt [ShowBigMessage \
160                $np.check \
161                "Check the symmetry operators in the output below" \
162                $b \
163                {Continue Redo} ]
164        if {$opt > 1} {
165            set expgui(oldphaselist) -1
166            return
167        }
168    }
169    file delete spg.in spg.out
170   
171    # ok do it!
172    set fp [open exptool.in w]
173    puts $fp "P"
174    puts $fp $title
175    puts $fp $spg
176    puts $fp "$cell(a) $cell(b) $cell(c) $cell(alpha) $cell(beta) $cell(gamma)"
177    puts $fp "/"
178    close $fp
179    global tcl_platform
180    # Save the current exp file
181    savearchiveexp
182    # disable the file changed monitor
183    set expgui(expModifiedLast) 0
184    set expnam [file root [file tail $expgui(expfile)]]
185    # save the previous phase list
186    set expgui(oldphaselist) $expmap(phaselist)
187    catch {
188        if {$tcl_platform(platform) == "windows"} {
189            exec [file join $expgui(gsasexe) exptool.exe] $expnam \
190                    < exptool.in >& exptool.out
191        } else {
192            exec [file join $expgui(gsasexe) exptool] $expnam \
193                    < exptool.in >& exptool.out
194        }
195    } errmsg
196    # load the revised exp file
197    set oldphaselist $expmap(phaselist)
198    loadexp $expgui(expfile)
199    set fp [open exptool.out r]
200    set out [read $fp]
201    close $fp
202    destroy $np
203    set err 0
204    if {[llength $oldphaselist] == [llength $expmap(phaselist)]} {set err 1}
205    if {$errmsg != ""} {
206        set err 1
207        append errmsg "\n" $out
208    } else {
209        set errmsg $out
210    }
211    if {$expgui(showexptool) || $err} {
212        set msg "Please review the result from adding the phase" 
213        if {$err} {append msg "\nIt appears an error occurred!"}
214        ShowBigMessage $np $msg $errmsg OK "" $err
215    }
216    file delete exptool.in exptool.out
217    # set the powpref warning (2 = required)
218    set expgui(needpowpref) 2
219    set msg "A phase was added" 
220    if {[string first $msg $expgui(needpowpref_why)] == -1} {
221        append expgui(needpowpref_why) "\t$msg\n"
222    }
223    # now select the new phase
224    SelectOnePhase [lindex $expmap(phaselist) end]   
225}
226
227#----------- Add Histogram routines --------------------------------------
228proc LabelInstParm {args} {
229    global newhist
230    switch $newhist(insttype) {
231        TOF {
232            set newhist(instfiletext) "Neutron Time of Flight"
233            catch {
234                set b $newhist(setnum)
235                append newhist(instfiletext) ", 2theta = $newhist(inst${b}Angle)"
236            }
237        }
238        ED {set newhist(instfiletext) "X-ray Energy Dispersive"}
239        "CW X" {set newhist(instfiletext) "CW X-ray"}
240        "CW N" {set newhist(instfiletext) "CW Neutron"}
241    }
242}
243trace variable newhist(setnum) w LabelInstParm
244proc MakeAddHistBox {} {
245    global expmap newhist
246
247    # --> should check here if room for another histogram, but only texture
248    # folks will ever need that
249
250    set np .newhist
251    catch {destroy $np}
252    toplevel $np
253    bind $np <Key-F1> "MakeWWWHelp expgui3.html AddHist"
254
255    grid [label $np.l0 -text "Adding a new histogram"] \
256            -column 0 -row 0 -sticky ew -columnspan 7
257    grid [checkbutton $np.d0 -text "Dummy Histogram" -variable newhist(dummy) \
258            -command "PostDummyOpts $np" \
259            ] -column 2 -row 0 -columnspan 99 -sticky e
260    grid [label $np.l1 -text "Data file:"] -column 0 -row 2
261    grid [label $np.t1 -textvariable newhist(rawfile) -bd 2 -relief ridge] \
262            -column 1 -row 2 -columnspan 3 -sticky ew
263    grid [button $np.b1 -text "Select File" \
264            -command "getrawfile $np" \
265            ] -column 4 -row 2
266
267    grid [label $np.lbank -text "Select bank" -anchor w] -column 1 -row 3 -sticky w
268    grid [frame $np.bank]  -column 2 -row 3 -columnspan 7 -sticky ew
269
270    grid [label $np.l2 -text "Instrument\nParameter file:"] -column 0 -row 5
271    grid [label $np.t2 -textvariable newhist(instfile) -bd 2 -relief ridge] \
272            -column 1 -row 5 -columnspan 3 -sticky ew
273    grid [button $np.b2 -text "Select File" \
274            -command "getinstfile $np" \
275            ] -column 4 -row 5
276    grid [button $np.edit -text "Edit file" \
277            -command {EditInstFile $newhist(instfile)}] \
278            -column 5 -row 5
279
280    grid [label $np.lset -text "Select set" -anchor w] -column 1 -row 6 -sticky w
281    grid [frame $np.set]  -column 2 -row 6 -columnspan 7 -sticky ew
282    grid [label $np.t2a -textvariable newhist(instfiletext) \
283            -justify center -anchor center -fg blue] \
284            -column 0 -row 8 -columnspan 99 -sticky ew
285
286    grid [button $np.f6a -text "Run\nRAWPLOT" -command "RunRawplot $np"] \
287            -column 4 -row 18 -rowspan 2
288    grid [label $np.l3 -text "Usable data limit:"] -column 0 -row 18 -rowspan 3 
289    grid [entry $np.e3 -width 12 -textvariable newhist(2tLimit) \
290            ] -column 1 -row 18 -rowspan 3
291    grid [radiobutton $np.cb3 -text "D-min" -variable newhist(LimitMode) \
292            -value 0] -column 2 -row 18 -sticky w
293    grid [radiobutton $np.cb4 -textvariable newhist(limitLbl)  \
294            -variable newhist(LimitMode) -anchor w -justify l \
295            -value 1] -column 2 -row 20 -sticky w
296    grid [radiobutton $np.cb5 -text "Q-max" -variable newhist(LimitMode) \
297            -value 2] -column 2 -row 19 -sticky w
298    set newhist(limitLbl) "TOF-min\n2-Theta Max"
299    # spacers
300    grid [frame $np.sp0 -bg white] \
301            -columnspan 20 -column 0 -row 1 -sticky nsew -ipady 2
302    grid [frame $np.sp1 -bg white] \
303            -columnspan 20 -column 0 -row 4 -sticky nsew -ipady 2
304    grid [frame $np.sp2 -bg white] \
305            -columnspan 20 -column 0 -row 17 -sticky nsew -ipady 2
306    grid [frame $np.sp3 -bg white] \
307            -columnspan 20 -column 0 -row 98 -sticky nsew -ipady 2
308    grid [frame $np.f6] -column 0 -row 99 -columnspan 5 -sticky ew
309    grid [button $np.f6.b6a -text Add \
310            -command "addhist $np"] -column 0 -row 0
311    bind $np <Return> "addhist $np"
312    grid [button $np.f6.b6b -text Cancel \
313            -command "destroy $np"] -column 1 -row 0
314    grid [button $np.f6.b6c -text "Add multiple banks" \
315            -command "addMultiplehist $np" -state disabled] -column 2 -row 0
316    grid [button $np.f6.help -text Help -bg yellow \
317            -command "MakeWWWHelp expgui3.html AddHist"] \
318            -column 2 -row 0 -sticky e
319    grid columnconfigure $np.f6 2 -weight 1
320    grid columnconfigure $np 3 -weight 1
321
322    # dummy histogram stuff
323    frame $np.d1
324    grid [label $np.d1.l1 -text min] -column 1 -row 1
325    grid [label $np.d1.l2 -text max] -column 2 -row 1
326    grid [label $np.d1.l3 -text step] -column 3 -row 1
327    grid [label $np.d1.lu -text ""] -column 4 -row 1 -rowspan 2
328    grid [entry $np.d1.e1 -width 10 -textvariable newhist(tmin)] -column 1 -row 2
329    grid [entry $np.d1.e2 -width 10 -textvariable newhist(tmax)] -column 2 -row 2
330    grid [entry $np.d1.e3 -width 10 -textvariable newhist(tstep)] -column 3 -row 2
331    grid [label $np.d1.m1 -anchor w] -column 1 -row 3 -sticky ew
332    grid [label $np.d1.m2 -anchor w] -column 2 -row 3 -sticky ew
333    label $np.dl1 -text "Data range:"
334    label $np.dl2 -text "Allowed"
335    label $np.dl3 -text "\n" -justify left -fg blue
336    wm title $np "add new histogram"
337
338    set newhist(banknum) {}
339    set newhist(setnum) {}
340    if {[string trim $newhist(rawfile)] != {}} {
341        validaterawfile $np $newhist(rawfile)
342    }
343    if {[string trim $newhist(instfile)] != {}} {
344        validateinstfile $np $newhist(instfile)
345    }
346
347    PostDummyOpts $np
348    # set grab, etc.
349    putontop $np
350
351    tkwait window $np
352
353    # fix grab...
354    afterputontop
355}
356
357# convert a file to Win-95 direct access
358proc WinCvt {file win} {
359    global expgui
360    if ![file exists $file] {
361        MyMessageBox -parent $win -title "Convert Error" \
362                -message "File $file does not exist" -icon error
363        return
364    }
365
366    set tmpname "[file join [file dirname $file] tempfile.xxx]"
367    set oldname "[file rootname $file].org"
368    if [file exists $oldname] {
369        set ans [MyMessageBox -parent $win -title "OK to overwrite?" \
370                -message "File [file tail $oldname] exists in [file dirname $oldname]. OK to overwrite?" \
371                -icon question -type yesno -default yes]
372        if {$ans == "no"} return
373        catch {file delete $oldname}
374    }
375
376    if [catch {
377        set in [open $file r]
378        # needed to test under UNIX
379        set out [open $tmpname w]
380        fconfigure $out -translation crlf
381        set len [gets $in line]
382        if {$len > 160} {
383            # this is an old-style UNIX file. Hope there are no control characters
384            set i 0
385            set j 79
386            while {$j < $len} {
387                puts $out [string range $line $i $j]
388                incr i 80
389                incr j 80
390            }
391        } else {
392            while {$len >= 0} {
393                append line "                                        "
394                append line "                                        "
395                set line [string range $line 0 79]
396                puts $out $line
397                set len [gets $in line]
398            }
399        }
400        close $in
401        close $out
402        file rename $file $oldname
403        file rename $tmpname $file
404    } errmsg] {
405        MyMessageBox -parent $win -title Notify \
406                -message "Error in conversion:\n$errmsg" -icon warning
407    }
408    return $file
409}
410
411proc getrawfile {np} {
412    global newhist tcl_platform
413    if {$tcl_platform(platform) == "windows"} {
414        set inp [
415        tk_getOpenFile -parent $np -initialfile $newhist(rawfile) -filetypes {
416            {"Data files" .GSAS} {"Data files" .GSA} 
417            {"Data files" .RAW}  {"All files" *}
418        }
419        ]
420    } else {
421        set inp [
422        tk_getOpenFile -parent $np -initialfile $newhist(rawfile) -filetypes {
423            {"Data files" .GSA*} {"Data files" .RAW} 
424            {"Data files" .gsa*} {"Data files" .raw} 
425            {"All files" *}
426        } 
427        ]
428    }
429    validaterawfile $np $inp
430}
431
432proc validaterawfile {np inp} {
433    global expgui newhist
434    if {$inp == ""} return
435    if [catch {set in [open $inp r]}] {
436        MyMessageBox -parent $np -title "Open error" \
437                -message "Unable to open file $inp" -icon error
438        return 
439    }
440    set newhist(banklist) {}
441    foreach child [winfo children $np.bank] {destroy $child}
442    # is this a properly formatted file?
443    # -- are lines the correct length & terminated with a CR-LF?   
444    fconfigure $in -translation lf
445    set i 0
446    while {[set len [gets $in line]] > 0} {
447        incr i
448        if {$len != 81 || [string range $line end end] != "\r"} {
449            set ans [MyMessageBox -parent $np -title "Convert?" \
450                    -message "File $inp is not in the correct format for GSAS.\nOK to convert?" \
451                    -icon warning -type {OK Quit} -default OK]
452            if {$ans == "ok"} {
453                # convert and reopen the file
454                close $in
455                WinCvt $inp $np
456                set i 0
457                set in [open $inp r]
458                fconfigure $in -translation lf
459                set line {}
460            } else {
461                return
462            }
463        }
464        # scan for BANK lines
465        if {[string first BANK $line] == 0} {
466            scan $line "BANK%d" num
467            lappend newhist(banklist) $num
468            # compute last point
469            set tmin 0
470            set tmax 0
471            catch {
472                scan $line "BANK%d%d%d%s%f%f" num nchan nrec rest start step
473                set tmin [expr $start/100.]
474                set tmax [expr ($start + $step*($nchan-1))/100.]
475            }
476            set newhist(tmin$num) $tmin
477            set newhist(tmax$num) $tmax
478        }
479        # check for "Instrument parameter file" line
480        if {$i == 2 && [string first "Instrument parameter" $line] == 0} {
481            validateinstfile $np \
482                    [file join [file dirname $inp] \
483                    [string trim [string range $line 26 end]]]
484        }
485    }
486    # were banks found?
487    if {$newhist(banklist) == ""} {
488        MyMessageBox -parent $np -title "Read error" \
489                -message "File $inp has no BANK lines.\nThis is not a valid GSAS data file." \
490                -icon warning
491        return
492    }
493    # don't use a full path unless needed
494    if {[pwd] == [file dirname $inp]} {
495        set newhist(rawfile) [file tail $inp]
496    } else {
497        set newhist(rawfile) $inp
498    }
499    set row 0
500    set col -1
501    foreach i $newhist(banklist) {
502        if {$col > 8} {
503            set col -1
504            incr row
505        }
506        grid [radiobutton $np.bank.$i -text $i -command SetTmax \
507                -variable newhist(banknum) -value $i] \
508                -column [incr col] -row $row -sticky w
509        # only 1 choice, so set it
510        if {[llength $newhist(banklist)] == 1} {
511            set newhist(banknum) $i
512            SetTmax
513        } else {
514            set newhist(2tLimit) {}
515            set newhist(LimitMode) {}
516        }
517    }
518    SetMultipleAdd $np
519}
520
521proc SetTmax {} {
522    global newhist
523    set num $newhist(banknum)
524    if {$newhist(insttype) == "TOF"} {
525        set newhist(2tLimit) [expr {$newhist(tmin$num) / 10.}]
526        if {[llength $newhist(banklist)] == $newhist(instbanks)} {
527            set newhist(setnum) $newhist(banknum)
528        }
529    } else {
530        set newhist(2tLimit) $newhist(tmax$num)
531    }
532    set newhist(LimitMode) 1
533
534}
535
536proc getinstfile {np} {
537    global newhist tcl_platform
538    if {$tcl_platform(platform) == "windows"} {
539        set inp [
540        tk_getOpenFile -parent $np -initialfile $newhist(instfile) -filetypes {
541            {"Inst files" .INST} {"Inst files" .INS} 
542            {"Inst files" .PRM} {"All files" *}
543        }
544        ]
545    } else {
546        set inp [
547        tk_getOpenFile -parent $np -initialfile $newhist(instfile) -filetypes {
548            {"Inst files" .INS*} {"Inst files" .ins*} 
549            {"Inst files" .PRM}  {"Inst files" .prm} 
550            {"All files" *}
551        }
552        ]
553    }
554    set newhist(setnum) {}
555    validateinstfile $np $inp
556}
557
558proc validateinstfile {np inp} {
559    global expgui newhist
560    if {$inp == ""} return
561    if [catch {set in [open $inp r]}] {
562        MyMessageBox -parent $np -title "Open error" \
563                -message "Unable to open file $inp" -icon error
564        return 
565    }
566    set newhist(instbanks) {}
567    foreach child [winfo children $np.set] {destroy $child}
568    # is this a properly formatted file?
569    # -- are lines the correct length & terminated with a CR-LF?   
570    fconfigure $in -translation lf
571    while {[set len [gets $in line]] > 0} {
572        if {$len != 81 || [string range $line end end] != "\r"} {
573            set ans [MyMessageBox -parent $np -title "Convert?" \
574                    -message "File $inp is not in the correct format for GSAS.\nOK to convert?" \
575                    -icon warning -type {OK Quit} -default OK]
576            if {$ans == "ok"} {
577                # convert and reopen the file
578                close $in
579                WinCvt $inp $np
580                set in [open $inp r]
581                fconfigure $in -translation lf
582                set line {}
583            } else {
584                return
585            }
586        }
587        # scan for the INS   BANK line
588        if {[string first "INS   BANK" $line] == 0} {
589            set newhist(instbanks) \
590                    [string trim [string range $line 12 end]]
591        }
592        # scan for the INS   HTYPE line
593        if {[string first "INS   HTYPE" $line] == 0} {
594            if {[string index [lindex $line 2] 2] == "T"} {
595                set newhist(insttype) TOF
596            } elseif {[string index [lindex $line 2] 2] == "E"} {
597                set newhist(insttype) ED
598            } elseif {[string index [lindex $line 2] 1] == "X"} {
599                set newhist(insttype) "CW X"
600            } else {
601                set newhist(insttype) "CW N"
602            }
603        }
604        # scan for the instrument constants
605        if {[regexp {INS ([ 1-9][0-9]) ICONS(.*)} $line a b c]} {
606            set b [string trim $b]
607            set newhist(inst${b}ICONS) [string trim $c]
608        }
609        if {[regexp {INS ([ 1-9][0-9])I ITYP(.*)} $line a b c]} {
610            set b [string trim $b]
611            set newhist(inst${b}ITYP) [string trim $c]
612        }
613        if {[regexp {INS ([ 1-9][0-9])BNKPAR(.*)} $line a b c]} {
614            set b [string trim $b]
615            set newhist(inst${b}Angle) [string trim [lindex $c 1]]
616        }
617    }
618    # were banks found?
619    if {$newhist(instbanks) == ""} {
620        MyMessageBox -parent $np -title "Read error" -message \
621                "File $inp has no \"INS   BANK\" line.\nThis is not a valid GSAS Instrument Parameter file." \
622                -icon warning
623        return
624    }
625    # don't use a full path unless needed
626    if {[pwd] == [file dirname $inp]} {
627        set newhist(instfile) [file tail $inp]
628    } else {
629        set newhist(instfile) $inp
630    }
631    set col -1
632    set row 0
633    for {set i 1} {$i <= $newhist(instbanks)} {incr i} {
634        if {$col > 8} {
635            set col -1
636            incr row
637        }
638        grid [radiobutton $np.set.$i -text $i \
639                -command "PostDummyOpts $np; ValidateDummyHist $np" \
640                -variable newhist(setnum) -value $i] \
641                -column [incr col] -row $row -sticky w
642        if {$newhist(instbanks) == 1} {set newhist(setnum) $i}
643    }
644    if {$newhist(dummy)} {PostDummyOpts $np; ValidateDummyHist $np}
645    LabelInstParm
646    SetMultipleAdd $np
647}
648
649proc addhist {np} {
650    global expgui newhist tcl_platform expmap
651    if {$newhist(dummy)} {
652        AddDummyHist $np
653        return
654    }
655    # validate the input
656    set err {}
657    if {[string trim $newhist(rawfile)] == ""} {
658        append err "  No data file specified\n"
659    }
660    if {[string trim $newhist(instfile)] == ""} {
661        append err "  No instrument parameter file specified\n"
662    }
663    if {[string trim $newhist(banknum)] == ""} {
664            append err "  Bank number must be specified\n"
665    } elseif {[catch {expr $newhist(banknum)}]} {
666            append err "  Bank number is not valid\n"
667    }
668    if {[string trim $newhist(setnum)] == ""} {
669        append err "  Parameter set number must be specified\n"
670    } elseif {[catch {expr $newhist(setnum)}]} {
671        append err "  Parameter set number is not valid\n"
672    }
673    if {[string trim $newhist(2tLimit)] == ""} {
674        append err "  2Theta/d-space limit must be specified\n"
675    } elseif {[catch {expr $newhist(2tLimit)}]} {
676        append err "  The 2Theta/d-space limit is not valid\n"
677    } elseif {$newhist(2tLimit) <= 0} {
678        append err "  The 2Theta/d-space limit is not valid\n"
679    }
680    if {[string trim $newhist(LimitMode)] == ""} {
681        append err "  Please choose between either a 2Theta, Q or d-space limit\n"
682    }
683
684    if {$err != ""} {
685        MyMessageBox -parent $np -title  "Add Histogram Error" \
686                -message "The following error(s) were found in your input:\n$err" \
687                -icon error -type ok -default ok \
688                -helplink "expgui3.html AddHistErr"
689        return
690    }
691
692    # ok do it!
693    set fp [open exptool.in w]
694    puts $fp "H"
695    if {$tcl_platform(platform) == "windows"} {
696        puts $fp [file attributes $newhist(rawfile) -shortname]
697        puts $fp [file attributes $newhist(instfile) -shortname]
698    } else {
699        puts $fp $newhist(rawfile)
700        puts $fp $newhist(instfile)
701    }
702    puts $fp $newhist(banknum)
703    puts $fp $newhist(setnum)
704    if {$newhist(LimitMode) == 1} {
705        puts $fp "T"
706        puts $fp "$newhist(2tLimit)"
707    } elseif {$newhist(LimitMode) == 2} {
708        puts $fp "D"
709        set Q 100
710        catch {set Q [expr {4*acos(0)/$newhist(2tLimit)}]}
711        puts $fp "$Q"
712    } else {
713        puts $fp "D"
714        puts $fp "$newhist(2tLimit)"
715    }
716    puts $fp "/"
717    puts $fp "X"
718    puts $fp "X"
719    close $fp
720    global tcl_platform
721    # Save the current exp file
722    savearchiveexp
723    # disable the file changed monitor
724    set expgui(expModifiedLast) 0
725    set expnam [file root [file tail $expgui(expfile)]]
726    catch {
727        if {$tcl_platform(platform) == "windows"} {
728            exec [file join $expgui(gsasexe) exptool.exe] $expnam \
729                    < exptool.in >& exptool.out
730        } else {
731            exec [file join $expgui(gsasexe) exptool] $expnam \
732                    < exptool.in >& exptool.out
733        }
734    } errmsg
735    # load the revised exp file
736    set oldpowderlist $expmap(powderlist)
737    loadexp $expgui(expfile)
738    set fp [open exptool.out r]
739    set out [read $fp]
740    close $fp
741    destroy $np
742    set err 0
743    if {[llength $oldpowderlist] == [llength $expmap(powderlist)]} {set err 1}
744    if {$errmsg != ""} {
745        append errmsg "\n" $out
746        set err 1
747    } else {
748        set errmsg $out
749    }
750    if {$expgui(showexptool) || $err} {
751        set msg "Please review the result from adding the histogram" 
752        if {$err} {append msg "\nIt appears an error occurred!"}
753        ShowBigMessage $np $msg $errmsg OK "" $err
754    }
755    file delete exptool.in exptool.out
756    # set the powpref warning (2 = required)
757    set expgui(needpowpref) 2
758    set msg "A histogram was added" 
759    if {[string first $msg $expgui(needpowpref_why)] == -1} {
760        append expgui(needpowpref_why) "\t$msg\n"
761    }
762    # select the most recently added histogram
763    if {!$err} {
764        set i [llength $expmap(histlistboxcontents)]
765        if {$i > 0} {
766            incr i -1
767            set expgui(curhist) $i
768            sethistlist
769        }
770    }
771}
772
773proc RunRawplot {parent} {
774    global newhist tcl_platform
775    set f1 $newhist(rawfile)
776    set f2 $newhist(instfile)
777    # for Windows put a message on top, in case file names must be shortened
778    if {$tcl_platform(platform) == "windows"} {
779        catch {set f1 [file nativename \
780                    [file attributes $newhist(rawfile) -shortname]]}
781        catch {set f2 [file nativename \
782                [file attributes $newhist(instfile) -shortname]]}
783    }
784    if {$f1 != "" || $f2 != ""} {
785        #set msg "Note: input to RAWPLOT\n"
786        #if {$f1 != ""} {append msg "data file: $f1\n"}
787        #if {$f2 != ""} {append msg "instrument file: $f2"}
788        catch {toplevel $parent.msg}
789        catch {eval destroy [winfo children $parent.msg]}
790        wm title $parent.msg "File names"
791        grid [label $parent.msg.1 \
792                -text "File names to be input to RAWPLOT" \
793                -justify center -anchor center] \
794                -column 0 -row 0 -columnspan 2
795        if {$f1 != ""} {
796            grid [label $parent.msg.2a \
797                    -text "Raw histogram: $f1" \
798                    -justify center -anchor e] \
799                    -column 0 -row 1
800            grid [button $parent.msg.2b \
801                    -command "clipboard clear; clipboard append $f1" \
802                    -text "put name\nin clipboard"] \
803                    -column 1 -row 1
804        }           
805        if {$f2 != ""} {
806            grid [label $parent.msg.3a \
807                    -text "Raw histogram: $f2" \
808                    -justify center -anchor e] \
809                    -column 0 -row 2
810            grid [button $parent.msg.3b \
811                    -command "clipboard clear; clipboard append $f2" \
812                    -text "put name\nin clipboard"] \
813                    -column 1 -row 2
814        }           
815        grid [button $parent.msg.4 \
816                -command "destroy $parent.msg" \
817                -text "Close"] \
818                -column 0 -columnspan 2 -row 9
819    }
820    # start RAWPLOT
821    runGSASprog rawplot 1
822    if {[winfo exists $parent.msg]} {raise $parent.msg}
823    update
824}
825#--- Dummy histogram stuff
826proc PostDummyOpts {np} {
827    global newhist
828    if {$newhist(dummy)} {
829        trace variable newhist(tmin) w "ValidateDummyHist $np"
830        trace variable newhist(tmax) w "ValidateDummyHist $np"
831        trace variable newhist(tstep) w "ValidateDummyHist $np"
832        foreach w {l1 t1 lbank} {
833            $np.$w config -fg grey
834        }
835        $np.d1.m1 config -text {}
836        $np.d1.m2 config -text {}
837        $np.b1 config -state disabled
838        grid forget $np.l3 $np.e3 $np.cb3 $np.cb4 $np.cb5 $np.bank $np.f6a
839        grid $np.dl1 -column 0 -row 18
840        grid $np.d1 -column 1 -row 18 -rowspan 2 -columnspan 4 -sticky e
841        grid $np.dl3 -column 0 -columnspan 99 -row 20 -sticky ew
842        if {$newhist(insttype) == "TOF"} {
843            $np.dl1 config -text "Data range:\n(TOF)"
844            $np.d1.lu config -text millisec
845            grid $np.dl2 -column 0 -row 19
846            catch {
847                set s $newhist(setnum)
848                foreach {x tmin tmax x} $newhist(inst${s}ITYP) {}
849                $np.d1.m1 config -text $tmin
850                $np.d1.m2 config -text $tmax
851            }
852        } elseif {[lindex $newhist(insttype) 0] == "CW"} {
853            $np.dl1 config -text "Data range:\n(2Theta)"
854            $np.d1.lu config -text degrees
855            #grid forget $np.dl2
856            $np.d1.m1 config -text >0.
857            $np.d1.m2 config -text <180.
858        } elseif {$newhist(insttype) == "ED"} {
859            $np.dl1 config -text "Data range:\n(Energy)"
860            $np.d1.lu config -text KeV
861            $np.d1.m1 config -text 1.
862            $np.d1.m2 config -text 200.
863            grid $np.dl2 -column 0 -row 19
864        } else {
865            $np.dl1 config -text "No file\nselected"
866            $np.d1.lu config -text {}
867        }
868    } else {
869        foreach var {tmin tmax tstep} {
870            foreach v [ trace vinfo newhist($var)] {
871                eval trace vdelete newhist($var) $v
872            }
873        }
874        grid forget $np.dl1 $np.d1 $np.dl2 $np.dl3
875        foreach w {l1 t1 lbank} {
876            $np.$w config -fg black
877        }
878        $np.b1 config -state normal
879        grid $np.bank -column 2 -row 3 -columnspan 7 -sticky ew
880        grid $np.f6a -column 4 -row 18 -rowspan 3
881        grid $np.l3 -column 0 -row 18 -rowspan 3
882        grid $np.e3 -column 1 -row 18 -rowspan 3 
883        grid $np.cb3 -column 2 -row 18 -sticky w
884        grid $np.cb4 -column 2 -row 20 -sticky w
885        grid $np.cb5 -column 2 -row 19 -sticky w
886     }
887}
888
889proc ValidateDummyHist {np args} {
890    # validate input
891    global newhist
892    set msg {}
893    $np.dl3 config -text "\n"
894    foreach e {e1 e2 e3} v {tmin tmax tstep} {
895        if [catch {expr $newhist($v)}] {
896            $np.d1.$e config -fg red
897            append msg "Value of $newhist($v) is invalid for $v\n"
898        } else {
899            $np.d1.$e config -fg black
900        }
901    }
902    if {[catch {expr $newhist(setnum)}]} {
903        append msg "An instrument file bank number must be selected\n"
904    } elseif {$newhist(setnum) <= 0 || \
905            $newhist(setnum) > $newhist(instbanks)} {
906        append msg "An invalid instrument file bank has been selected\n"
907    }
908
909    if {$msg != ""} {return $msg}
910
911    if {$newhist(tmax) <= $newhist(tmin)} {
912        $np.d1.e1 config -fg red
913        $np.d1.e2 config -fg red
914        return "Tmax <= Tmin\n"
915    }
916
917
918    set dmin -1
919    set dmax -1
920    if {$newhist(insttype) == "TOF"} {
921        catch {
922            set s $newhist(setnum)
923            foreach {x tmin tmax x} $newhist(inst${s}ITYP) {}
924            if {$newhist(tmin) <$tmin } {
925                $np.d1.e1 config -fg red
926                append msg "Min value of $newhist(tmin) msec is invalid.\n"
927            }
928            if {$newhist(tmax) >$tmax } {
929                $np.d1.e2 config -fg red
930                append msg "Max value of $newhist(tmax) msec is invalid.\n"
931            }
932            set s $newhist(setnum)
933            set dmin [expr {1000. * $newhist(tmin) / \
934                    [lindex $newhist(inst${s}ICONS) 0]}]
935            set dmax [expr {1000. * $newhist(tmax) / \
936                    [lindex $newhist(inst${s}ICONS) 0]}]
937        }
938    } elseif {[lindex $newhist(insttype) 0] == "CW"} {
939        if {$newhist(tmin) <= 0 } {
940            $np.d1.e1 config -fg red
941            append msg "Min value of $newhist(tmin) degrees is invalid.\n"
942        }
943        if {$newhist(tmax) >=180 } {
944            $np.d1.e2 config -fg red
945            append msg "Max value of $newhist(tmax) degrees is invalid.\n"
946        }
947        catch {
948            set s $newhist(setnum)
949            set dmin [expr {[lindex $newhist(inst${s}ICONS) 0]\
950                    * 0.5 / sin(acos(0.)*$newhist(tmax)/180.)}]
951            set dmax [expr {[lindex $newhist(inst${s}ICONS) 0]\
952                    * 0.5 / sin(acos(0.)*$newhist(tmin)/180.)}]
953        }
954    } else {
955        if {$newhist(tmin) <1 } {
956            $np.d1.e1 config -fg red
957            append msg "Min value of $newhist(tmin) KeV is invalid.\n"
958        }
959        if {$newhist(tmax) >200 } {
960            $np.d1.e2 config -fg red
961            append msg "Max value of $newhist(tmax) KeV is invalid.\n"
962        }
963        catch {
964            set s $newhist(setnum)
965            set ang [lindex $newhist(inst${s}ICONS) 0]
966            set dmin [expr {12.398/ (2.0*sin($ang*acos(0.)/180) * \
967                    $newhist(tmax))}]
968            set dmax [expr {12.398/ (2.0*sin($ang*acos(0.)/180) * \
969                    $newhist(tmin))}]
970        }
971    }
972    if {$msg != ""} {return $msg}
973    set pnts -1
974    catch {
975        set pnts [expr {1+int(($newhist(tmax) - $newhist(tmin))/$newhist(tstep))}]
976        set qmin [expr {4.*acos(0)/$dmax}]
977        set qmax [expr {4.*acos(0)/$dmin}]
978    }
979    if {$pnts <= 0} {
980        $np.d1.e3 config -fg red
981        append msg "Step value of $newhist(tstep) is invalid.\n"
982    }
983    if {$pnts >20000} {
984        $np.d1.e3 config -fg red
985        append msg "Step value of $newhist(tstep) is too small (>20000 points).\n"
986    }
987    if {$msg != ""} {return $msg}
988    if {$dmin > 0 && $dmax > 0} {
989        catch {
990            set msg [format \
991                    {  %d points.%s  D-space range: %.2f-%.2f A,  Q: %.2f-%.2f/A} \
992                    $pnts "\n" $dmin $dmax $qmin $qmax]
993            $np.dl3 config -text $msg
994        }
995    }
996    if {$msg != ""} {return ""}
997    $np.dl3 config -text [format {  %d points.%s  Range: ?} $pnts "\n"]
998    return "Invalid data range -- something is wrong!"
999}
1000
1001proc AddDummyHist {np} {
1002    global newhist expgui expmap
1003    global tcl_platform
1004    set msg [ValidateDummyHist $np]
1005    if {$msg != ""} {
1006        MyMessageBox -parent $np -title  "Add Histogram Error" \
1007                -message "The following error(s) were found in your input:\n$msg" \
1008                -icon error -type ok -default ok \
1009                -helplink "expgui3.html AddHistErr"
1010        return
1011    }
1012    set fp [open exptool.in w]
1013    puts $fp "D"
1014    puts $fp $newhist(instfile)
1015    puts $fp $newhist(setnum)
1016    if {$newhist(insttype) == "TOF"} {
1017        puts $fp "C"
1018    }
1019    puts $fp $newhist(tmin)
1020    puts $fp $newhist(tmax)
1021    puts $fp $newhist(tstep)
1022    puts $fp "X"
1023    puts $fp "0"
1024    close $fp
1025    # Save the current exp file
1026    savearchiveexp
1027    # disable the file changed monitor
1028    set expgui(expModifiedLast) 0
1029    set expnam [file root [file tail $expgui(expfile)]]
1030    set err [catch {
1031        if {$tcl_platform(platform) == "windows"} {
1032            exec [file join $expgui(gsasexe) exptool.exe] $expnam \
1033                    < exptool.in >& exptool.out
1034        } else {
1035            exec [file join $expgui(gsasexe) exptool] $expnam \
1036                    < exptool.in >& exptool.out
1037        }
1038    } errmsg ]
1039    # load the revised exp file
1040    set oldpowderlist $expmap(powderlist)
1041    loadexp $expgui(expfile)
1042    set fp [open exptool.out r]
1043    set out [read $fp]
1044    close $fp
1045    if {[llength $oldpowderlist] == [llength $expmap(powderlist)]} {set err 1}
1046    if {$errmsg != ""} {
1047        append errmsg "\n" $out
1048    } else {
1049        set errmsg $out
1050    }
1051    if {[regexp {\(P,H,A\)} $out]} {
1052        set msg {You must upgrade the EXPTOOL program.}
1053        append msg { This version cannot add dummy histograms.}
1054        MyMessageBox -icon error -title "Old EXPTOOL program" \
1055                -message $msg -parent $np \
1056                -helplink "expguierr.html OldEXPTOOL"
1057        # update the documentation & link
1058        destroy $np
1059    } elseif {$expgui(showexptool) || $err} {
1060        set msg "Please review the result from adding the dummy histogram" 
1061        if {$err} {append msg "\nIt appears an error occurred!"}
1062        ShowBigMessage $np $msg $errmsg OK "" $err
1063    } else {
1064        destroy $np
1065    }
1066    file delete exptool.in exptool.out
1067    # set the powpref warning (2 = required)
1068    set expgui(needpowpref) 2
1069    set msg "A histogram was added" 
1070    if {[string first $msg $expgui(needpowpref_why)] == -1} {
1071        append expgui(needpowpref_why) "\t$msg\n"
1072    }
1073}
1074
1075#--- multiple histogram stuff
1076proc SetMultipleAdd {np} {
1077    global newhist
1078    $np.f6.b6c configure -state disabled
1079    catch {
1080        if {$newhist(instbanks) == [llength $newhist(banklist)] \
1081                && $newhist(instbanks) > 1} {
1082            $np.f6.b6c configure -state normal
1083        }
1084    }
1085}
1086
1087proc addMultiplehist {np} {
1088    global newhist
1089    # should not happen, but just in case
1090    if {$newhist(instbanks) != [llength $newhist(banklist)]} {
1091        $np.f6.b6c configure -state disable
1092        return
1093    }
1094    catch {destroy [set top $np.addMult]}
1095    toplevel $top
1096    grid [canvas $top.canvas \
1097            -scrollregion {0 0 5000 500} -width 0 -height 250 \
1098            -yscrollcommand "$top.scroll set"] \
1099            -column 0 -columnspan 2 -row 1 -sticky nsew
1100    grid columnconfigure $top 0 -weight 1
1101    grid rowconfigure $top 1 -weight 1
1102    scrollbar $top.scroll \
1103            -command "$top.canvas yview"
1104    frame [set cfr $top.canvas.fr]
1105    $top.canvas create window 0 0 -anchor nw -window $cfr
1106    grid [label $top.top -text "Select banks to add" -bg beige] \
1107            -column 0 -columnspan 3 -row 0 -sticky ew
1108    grid [button $top.add -text Add -command "destroy $np"] -column 0 -row 2
1109    grid [button $top.cancel -text Cancel -command "destroy $top"] \
1110            -column 1 -row 2 -columnspan 2
1111
1112    set row 1
1113    grid [label $cfr.t1 -text "Bank\n#"] -column 0 -row 0
1114    switch $newhist(insttype) {
1115        TOF {set txt "T-min\n(ms)"}
1116        ED  {set txt "E-max\n(KeV)"}
1117        default {set txt "2theta\nmax"}
1118    }
1119    grid [label $cfr.t2 -text $txt] -column 1 -row 0
1120    foreach i $newhist(banklist) {
1121        grid [checkbutton $cfr.c$i -text $i \
1122                -variable newhist(usebank$i)] \
1123                -column 0 -row [incr row] -sticky w
1124        set newhist(usebank$i) 1
1125        grid [entry $cfr.e$i -width 8 \
1126                -textvariable newhist(tmin$i)] \
1127                -column 1 -row $row -sticky w
1128    }
1129    # resize the list
1130    update
1131    set sizes [grid bbox $top.canvas.fr]
1132    $top.canvas config -scrollregion $sizes -width [lindex $sizes 2]
1133    # use the scroll for BIG lists
1134    if {[lindex $sizes 3] > [winfo height $top.canvas]} {
1135        grid $top.scroll -sticky ns -column 3 -row 1
1136    } else {
1137        grid forget $top.scroll 
1138    }
1139    update
1140    putontop $top
1141    tkwait window $top
1142    if {[winfo exists $np]} return
1143
1144    # validate the input
1145    set err {}
1146    if {[string trim $newhist(rawfile)] == ""} {
1147        append err "  No data file specified\n"
1148    }
1149    if {[string trim $newhist(instfile)] == ""} {
1150        append err "  No instrument parameter file specified\n"
1151    }
1152    foreach i $newhist(banklist) {
1153        if {$newhist(usebank$i)} {
1154            if {[catch {expr $newhist(tmin$i)}]} {
1155                append err "  The Max/Min limit is not valid for bank $i\n"
1156            } elseif {$newhist(tmin$i) <= 0} {
1157                append err "  The Max/Min limit is not valid for bank $i\n"
1158            }
1159        }
1160    }
1161    if {$err != ""} {
1162        MyMessageBox -parent $np -title  "Add Histogram Error" \
1163                -message "The following error(s) were found in your input:\n$err" \
1164                -icon error -type ok -default ok \
1165                -helplink "expgui3.html AddHistErr"
1166        return
1167    }
1168
1169    # ok do it!
1170    global tcl_platform expmap expgui
1171    # Save the current exp file
1172    savearchiveexp
1173    set oldpowderlist $expmap(powderlist)
1174    # disable the file changed monitor
1175    set expgui(expModifiedLast) 0
1176    set expnam [file root [file tail $expgui(expfile)]]
1177    if {$tcl_platform(platform) == "windows"} {
1178        set rfile [file attributes $newhist(rawfile) -shortname]
1179        set ifile [file attributes $newhist(instfile) -shortname]
1180        set exe [file join $expgui(gsasexe) exptool.exe]
1181    } else {
1182        set rfile $newhist(rawfile)
1183        set ifile $newhist(instfile)
1184        set exe [file join $expgui(gsasexe) exptool]
1185    }
1186    set k 0
1187    set added 0
1188    set outlog {}
1189    set err 0
1190    pleasewait "adding histograms" expgui(temp)
1191    foreach i $newhist(banklist) {
1192        incr k
1193        if {$newhist(usebank$i)} {
1194            incr added
1195            set expgui(temp) "adding bank $i"
1196            update
1197            set fp [open exptool.in w]
1198            puts $fp "H"
1199            puts $fp $rfile
1200            puts $fp $ifile
1201            puts $fp $i
1202            puts $fp $k
1203            puts $fp "T"
1204            puts $fp "$newhist(tmin$i)"
1205            puts $fp "/"
1206            puts $fp "X"
1207            puts $fp "X"
1208            close $fp
1209            catch {
1210                exec $exe $expnam < exptool.in >& exptool.out
1211            } errmsg
1212            set fp [open exptool.out r]
1213            set out [read $fp]
1214            close $fp
1215            if {$errmsg != ""} {
1216                append outlog "\n\n\nNOTE ERROR:\n" $errmsg $out
1217                set err 1
1218            } else {
1219                append outlog $out
1220            }
1221        }
1222    }
1223    # load the revised exp file
1224    loadexp $expgui(expfile)
1225    if {[llength $oldpowderlist]+$added != [llength $expmap(powderlist)]} {
1226        set err 1
1227    }
1228    # set the powpref warning (2 = required)
1229    set expgui(needpowpref) 2
1230    set msg "A histogram was added" 
1231    if {[string first $msg $expgui(needpowpref_why)] == -1} {
1232        append expgui(needpowpref_why) "\t$msg\n"
1233    }
1234    file delete exptool.in exptool.out
1235    donewait 
1236    if {$expgui(showexptool) || $err} {
1237        set msg "Please review the result from adding the histogram" 
1238        if {$err} {append msg "\nIt appears an error occurred!"}
1239        ShowBigMessage $np $msg $outlog OK "" $err
1240    }
1241    # select the most recently added histogram
1242    if {!$err} {
1243        set i [llength $expmap(histlistboxcontents)]
1244        if {$i > 0} {
1245            incr i -1
1246            set expgui(curhist) $i
1247            sethistlist
1248        }
1249    }
1250}
1251
1252#----------- Add Atoms routines ----------------------------------------
1253proc MakeAddAtomsBox {phase "atomlist {}"} {
1254    global expmap expgui
1255
1256    # is there room for more atoms? Well, we will check this someday
1257    if {$phase == ""} return
1258    if {[llength $phase] != 1} return
1259
1260    set top .newatoms
1261    catch {destroy $top}
1262    toplevel $top
1263    bind $top <Key-F1> "MakeWWWHelp expgui2.html addatoms"
1264
1265    grid [label $top.l1 -relief groove -bd 4 -anchor center\
1266            -text "Adding atoms to phase #$phase"] \
1267            -column 0 -row 0 \
1268            -sticky we -columnspan 10
1269   
1270    grid [canvas $top.canvas \
1271            -scrollregion {0 0 5000 500} -width 0 -height 250 \
1272            -yscrollcommand "$top.scroll set"] \
1273            -column 0 -row 2 -columnspan 4 -sticky nsew
1274    grid columnconfigure $top 3 -weight 1
1275    grid rowconfigure $top 2 -weight 1
1276    grid rowconfigure $top 1 -pad 5
1277    scrollbar $top.scroll \
1278            -command "$top.canvas yview"
1279    frame $top.canvas.fr
1280    $top.canvas create window 0 0 -anchor nw -window $top.canvas.fr
1281
1282    set np $top.canvas.fr
1283    set row 0
1284    set col 0
1285    grid [label $np.l_${row}0 -text "  #  "] -column $col -row $row
1286    foreach i {Atom\ntype Name x y z Occ Uiso} \
1287            var {type name x y z occ uiso} {
1288        grid [button $np.l_${row}$i -text $i -padx 0 -pady 0 \
1289                -command "sortAddAtoms $phase $top $var"] \
1290                -column [incr col] -row $row -sticky nsew
1291    }
1292    grid [label $np.l_${row}Use -text Use\nFlag] -column [incr col] -row $row
1293
1294    set expgui(SetAddAtomsScroll) 0
1295    set i [llength $atomlist]
1296    if {$i == 0} {incr i}
1297    for {set j 0} {$j < $i} {incr j} {
1298        MakeAddAtomsRow $top
1299    }
1300    set row 0
1301    foreach item $atomlist {
1302        incr row
1303        foreach val $item w {n x y z t o u} {
1304            if {$val != ""} {
1305                $np.e${row}$w delete 0 end
1306                $np.e${row}$w insert end $val
1307            }
1308        }
1309    }
1310    bind $top <Configure> "SetAddAtomsScroll $top"
1311    grid rowconfigure $top 3 -min 10
1312    grid [button $top.b1 -text "Add Atoms"\
1313            -command "addatom $phase $top"] -column 0 -row 5 -sticky w
1314    bind $top <Return> "addatom $phase $top"
1315    grid [button $top.b2 -text Cancel \
1316            -command "destroy $top"] -column 1 -row 5 -sticky w
1317    grid [button $top.help -text Help -bg yellow \
1318            -command "MakeWWWHelp expgui2.html addatoms"] \
1319            -column 0 -columnspan 2 -row 4
1320
1321    # get the input formats if not already defined
1322    GetImportFormats
1323    if {[llength $expgui(importFormatList)] > 0} {
1324        grid [frame $top.fr -bd 4 -relief groove] \
1325                -column 3 -row 5 -columnspan 2 -sticky e
1326        grid [button $top.fr.b3 -text "Import atoms from: " \
1327                -command "ImportAtoms \$expgui(importFormat) $top $phase"] \
1328                -column 0 -row 0 -sticky e
1329        set menu [eval tk_optionMenu $top.fr.b4 expgui(importFormat) \
1330                $expgui(importFormatList)]
1331        for {set i 0} {$i <= [$menu index end]} {incr i} {
1332            $menu entryconfig $i -command "ImportAtoms \$expgui(importFormat) $top $phase"
1333        }
1334        grid $top.fr.b4 -column 1 -row 0 -sticky w
1335        grid rowconfig $top.fr 0 -pad 10
1336        grid columnconfig $top.fr 0 -pad 10
1337        grid columnconfig $top.fr 1 -pad 10
1338    }
1339
1340    grid [button $top.b3 -text  "More atom boxes" \
1341            -command "MakeAddAtomsRow $top"] -column 3 \
1342            -columnspan 2 -row 4 -sticky e
1343   
1344    wm title $top "add new atom"
1345
1346    # set grab, etc.
1347    putontop $top
1348
1349    tkwait window $top
1350
1351    # fix grab...
1352    afterputontop
1353}
1354
1355proc MakeAddAtomsRow {top} {
1356    set np $top.canvas.fr
1357    set col -1
1358    set row 1
1359    # find an empty row
1360    while {![catch {grid info $np.e${row}t}]} {incr row}
1361    grid [label $np.e${row}num -text $row] -column [incr col]  -row $row
1362    grid [entry $np.e${row}t -width 5] -column [incr col]  -row $row
1363    grid [entry $np.e${row}n -width 8] -column [incr col]  -row $row
1364    foreach i {x y z o u} {
1365        grid [entry $np.e${row}$i -width 9] -column [incr col] -row $row
1366    }
1367    grid [checkbutton $np.e${row}use -variable expgui(UseAtom$row)] \
1368            -column [incr col] -row $row
1369    # default occupancy
1370    $np.e${row}o delete 0 end
1371    $np.e${row}o insert end 1.0
1372    # default Uiso
1373    $np.e${row}u delete 0 end
1374    $np.e${row}u insert end 0.025
1375    # default label
1376    $np.e${row}n delete 0 end
1377    $np.e${row}n insert end (default)
1378    # use by default
1379    $np.e${row}use select
1380
1381    SetAddAtomsScroll $top
1382    return $row
1383}
1384
1385proc SetAddAtomsScroll {top} {
1386    global expgui
1387    if $expgui(SetAddAtomsScroll) return
1388    # prevent reentrance
1389    set expgui(SetAddAtomsScroll) 1
1390    update
1391    set sizes [grid bbox $top.canvas.fr]
1392    $top.canvas config -scrollregion $sizes -width [lindex $sizes 2]
1393    # use the scroll for BIG atom lists
1394    if {[lindex $sizes 3] > [winfo height $top.canvas]} {
1395        grid $top.scroll -sticky ns -column 4 -row 2
1396    } else {
1397        grid forget $top.scroll 
1398    }
1399    update
1400    set expgui(SetAddAtomsScroll) 0
1401}
1402
1403# Validate the atoms in the atoms add/phase replace box
1404# returns a null string on error or a list of atoms
1405proc ValidateAtomsBox {top np} {
1406    global expgui
1407    set row 0
1408    # loop over the defined rows
1409    set err {}
1410    set atomlist {}
1411    set validatmtypes {
1412        H H-1 H_1 H_2 D H_3 HE HE_3 HE_4 LI LI+1 LI_6 LI_7 BE BE+2 B B_10
1413        B_11 C CV C_12 C_13 N N_14 N_15 O O-1 O_16 O_17 O_18 F F-1 F_19 NE
1414        NE_20 NE_21 NE_22 NA NA+1 NA_23 MG MG+2 MG_24 MG_25 MG_26 AL AL+3
1415        AL_27 SI SI+4 SIV SI_28 SI_29 SI_30 P P_31 S S_32 S_33 S_34 CL CL-1
1416        CL_35 CL_37 AR AR_36 AR_40 K K+1 K_39 K_41 CA CA+2 CA_40 CA_44 SC SC+3
1417        SC_45 TI TI+2 TI+3 TI+4 TI_46 TI_47 TI_48 TI_49 TI_50 V V+2 V+3 V+5
1418        V_51 CR CR+2 CR+3 CR_50 CR_52 CR_53 CR_54 MN MN+2 MN+3 MN+4 MN_55 FE
1419        FE+2 FE+3 FE_54 FE_56 FE_57 FE_58 CO CO+2 CO+3 CO_59 NI NI+2 NI+3
1420        NI_58 NI_60 NI_61 NI_62 NI_64 CU CU+1 CU+2 CU_63 CU_65 ZN ZN+2 ZN_64
1421        ZN_66 ZN_67 ZN_68 GA GA+3 GE GE+4 AS AS_75 SE BR BR-1 BR_79 BR_81 KR
1422        RB RB+1 SR SR+2 Y Y+3 Y_89 ZR ZR+4 NB NB+3 NB+5 NB_93 MO MO+3 MO+5
1423        MO+6 TC TC_98 RU RU+3 RU+4 RH RH+3 RH+4 RH_103 PD PD+2 PD+4 AG AG+1
1424        AG+2 CD CD+2 CD_112 CD_113 CD_114 CD_116 IN IN+3 IN_113 IN_115 SN SN+2
1425        SN+4 SB SB+3 SB+5 TE I I-1 I_127 XE CS CS+1 CS_133 BA BA+2 LA LA+3 CE
1426        CE+3 CE+4 PR PR+3 PR+4 PR_141 ND ND+3 PM PM+3 PM_147 SM SM+3 SM_152
1427        SM_154 EU EU+2 EU+3 EU_153 GD GD+3 GD_160 TB TB+3 TB_159 DY DY+3 HO
1428        HO+3 HO_165 ER ER+3 TM TM+3 TM_169 YB YB+2 YB+3 LU LU+3 HF HF+4 TA
1429        TA+5 TA_181 W W+6 RE OS OS+4 IR IR+3 IR+4 PT PT+2 PT+4 AU AU+1 AU+3
1430        AU_197 HG HG+1 HG+2 TL TL+1 TL+3 PB PB+2 PB+4 BI BI+3 BI+5 BI_209 PO
1431        PO_210 AT AT_210 RN RN_222 FR FR_223 RA RA+2 RA_226 AC AC+3 AC_227 TH
1432        TH+4 TH_232 PA PA_231 U U+3 U+4 U+6 U_235 U_238 NP NP+3 NP+4 NP+6
1433        NP_237 PU PU+3 PU+4 PU+6 PU_239 PU_240 PU_242 AM AM_243 CM CM_244 BK
1434        BK_247 CF CF_249
1435    }
1436    # loop over the defined rows
1437    while {![catch {grid info $np.e[incr row]t}]} {
1438        if !{$expgui(UseAtom$row)} continue
1439        # ignore blank entries
1440        set line {}
1441        foreach i {t x y z} {
1442            append line [string trim [$np.e${row}$i get]]
1443        }
1444        if {$line == ""} continue
1445
1446        # validate the input
1447        if {[set type [string trim [$np.e${row}t get]]] == ""} {
1448            append err "  line $row: No atom type specified\n"
1449        }
1450        if {[lsearch $validatmtypes [string toupper $type]] == -1} {
1451            append err "  line $row: Atom type $type is invalid for GSAS\n"
1452        }
1453        set name [string trim [$np.e${row}n get]]
1454        if {$name == "(default)"} {set name "/"}
1455        if {$name == ""} {set name "/"}
1456        foreach i {x y z o u} n {x y z Occ Uiso} {
1457            if {[set $i [string trim [$np.e${row}$i get]]] == ""} {
1458                append err "  line $row: No value specified for $n\n"
1459            } elseif {[catch {expr [set $i]}]} {
1460                append err "  line $row: The value for $n is invalid\n"
1461            }
1462        }
1463        lappend atomlist "$type $x $y $z $o $name I $u"
1464    }
1465    if {$err != ""} {
1466        MyMessageBox -icon warning -message "Note Errors:\n$err" -parent $top
1467        return {}
1468    }
1469    if {[llength $atomlist] == 0} {
1470        MyMessageBox -icon warning -message "No atoms to load!" -parent $top
1471        return {}
1472    }
1473    return $atomlist
1474}
1475
1476proc addatom {phase top} {
1477    global expgui env expmap
1478    set np $top.canvas.fr
1479    # validate the atoms info
1480    set atomlist [ValidateAtomsBox $top $np]
1481    if {$atomlist == ""} return
1482
1483    # ok add the atoms!
1484    set fp [open exptool.in w]
1485    puts $fp "A"
1486    puts $fp $phase
1487    # number of atoms
1488    puts $fp [llength $atomlist]
1489    foreach atomline $atomlist {
1490        puts $fp $atomline
1491    }
1492    close $fp
1493    # needed in UNIX
1494    set env(ATOMDATA) [file join $expgui(gsasdir) data atmdata.dat]
1495    set env(gsas) [file nativename $expgui(gsasdir)]
1496    # needed in Windows
1497    set env(GSAS) [file nativename $expgui(gsasdir)]
1498
1499    global tcl_platform
1500    # Save the current exp file
1501    savearchiveexp
1502    # disable the file changed monitor
1503    set expgui(expModifiedLast) 0
1504    set expnam [file root [file tail $expgui(expfile)]]
1505    catch {
1506        if {$tcl_platform(platform) == "windows"} {
1507            exec [file join $expgui(gsasexe) exptool.exe] $expnam \
1508                    < exptool.in >& exptool.out
1509        } else {
1510            exec [file join $expgui(gsasexe) exptool] $expnam \
1511                    < exptool.in >& exptool.out
1512        }
1513    } errmsg
1514    # load the revised exp file
1515    set oldatomlist $expmap(atomlist_$phase)
1516    loadexp $expgui(expfile)
1517    set fp [open exptool.out r]
1518    set out [read $fp]
1519    close $fp
1520    destroy $top
1521    set err 0
1522    if {[llength $oldatomlist] == [llength $expmap(atomlist_$phase))]} {
1523        set err 1
1524    }
1525    if {$errmsg != ""} {
1526        append errmsg "\n" $out
1527        set err 1
1528    } else {
1529        set errmsg $out
1530    }
1531    if {$expgui(showexptool) || $err} {
1532        set msg "Please review the result from adding the atom(s)" 
1533        if {$err} {append msg "\nIt appears an error occurred!"}
1534        ShowBigMessage $top $msg $errmsg OK "" $err
1535    }
1536    file delete exptool.in exptool.out
1537}
1538
1539#---------------------------------------------------------------------------
1540# commands to modify a group of selected atoms
1541#---------------------------------------------------------------------------
1542
1543# make the dialog to choose an action
1544proc MakeXformAtomsBox {phase} {
1545    global expgui expmap
1546    set numberList {}
1547    set p $expgui(curPhase)
1548    foreach AtomIndex $expgui(selectedatomlist) {
1549        # get atom number & phase
1550        set tuple [lindex $expmap(atomlistboxcontents) $AtomIndex]
1551        lappend numberList [lindex $tuple 0]
1552    }
1553    if {$numberList == ""} return
1554    if {[llength $numberList] > 1} {
1555        set suffix s
1556        set suffixy "ies"
1557    } else {
1558        set suffix ""
1559        set suffixy "y"
1560    }
1561    set w .global
1562    catch {destroy $w}
1563    toplevel $w
1564    wm title $w "Edit Atomic Parameter -- phase #$phase"
1565    bind $w <Key-F1> "MakeWWWHelp expgui2.html xform"
1566    # this needs to track by phase
1567    grid [label $w.0 \
1568            -text "Modifying atom${suffix} [CompressList $numberList] Phase $phase" \
1569            -bg yellow -anchor center] -row 0 -column 0 -columnspan 10 \
1570            -sticky nsew
1571    grid rowconfigure $w 0 -pad 5
1572    grid rowconfigure $w 1 -minsize 2
1573
1574    grid [TitleFrame $w.1 -bd 6 -relief groove -text "Modify coordinates"] \
1575            -row 2 -column 0 -columnspan 10 -sticky news
1576    set w1 [$w.1 getframe]
1577    set row 0
1578    foreach v {x y z} {
1579        incr row
1580        set col -1
1581        grid [label $w1.l$v -text "new $v   =   "] -column [incr col] -row $row
1582        foreach o {x y z} {
1583            grid [entry $w1.e${v}${o} -width 6] -column [incr col] -row $row
1584            $w1.e${v}${o} delete 0 end
1585            if {$v == $o} {
1586                $w1.e${v}${o} insert end "1.0"
1587            } else {
1588                $w1.e${v}${o} insert end "0."
1589            }
1590            grid [label $w1.p${v}${o} -text " $o  +  "] \
1591                    -column [incr col] -row $row
1592        }
1593        grid [entry $w1.e${v} -width 6] -column [incr col] -row $row
1594        $w1.e${v} delete 0 end
1595        $w1.e${v} insert end "0."
1596    }
1597    grid [button $w1.do -text "Transform Coordinates" \
1598            -command "XformAtomsCoord $phase [list $numberList] $w1" \
1599            ] -row [incr row] -column 0 -columnspan 10
1600
1601    grid rowconfigure $w 3 -minsize 5
1602    grid [TitleFrame $w.4 -bd 6 -relief groove -text "Modify occupanc${suffixy}"] \
1603            -row 4 -column 0 -columnspan 10 -sticky news
1604    set w2 [$w.4 getframe]
1605    grid [label $w2.1 -text "Occupancy: "] -row 1 -column 0
1606    grid [entry $w2.e -width 10] -column 1 -row 1
1607    $w2.e delete 0 end
1608    $w2.e insert end 1.0
1609    grid columnconfigure $w2 2 -weight 1
1610    grid [button $w2.do -text "Set Occupanc${suffixy}" \
1611            -command "XformAtomsOcc $phase [list $numberList] $w2" \
1612            ] -row 2 -column 0 -columnspan 10
1613
1614    grid rowconfigure $w 5 -minsize 5
1615    grid [TitleFrame $w.6 -bd 6 -relief groove \
1616            -text "Modify Displacement Parameter$suffix"] \
1617            -row 6 -column 0 -columnspan 10 -sticky news
1618    set w2 [$w.6 getframe]
1619    grid [entry $w2.e -width 10] -column 1 -row 1
1620    $w2.e delete 0 end
1621    $w2.e insert end 0.025
1622    grid columnconfigure $w2 2 -weight 1
1623    grid [button $w2.do -text "Set U" \
1624            -command "XformAtomsU $phase [list $numberList] $w2" \
1625            ] -row 2 -column 0 -columnspan 10
1626    grid [frame $w2.f] -row 3 -column 0 -columnspan 10
1627
1628    if {[lindex $expmap(phasetype) [expr {$p - 1}]] != 4} {
1629        grid [label $w2.1 -text "Uiso or Uequiv: "] -row 1 -column 0
1630        grid [button $w2.f.iso -text "Set Isotropic" \
1631                -command "XformAtomsU $phase [list $numberList] iso" \
1632                ] -row 0 -column 0
1633        grid [button $w2.f.aniso -text "Set Anisotropic" \
1634                -command "XformAtomsU $phase [list $numberList] aniso" \
1635                ] -row 0 -column 1
1636    } else {
1637        grid [label $w2.1 -text "Uiso: "] -row 1 -column 0
1638    }
1639
1640    grid rowconfigure $w 5 -minsize 5
1641    if {[lindex $expmap(phasetype) [expr {$p - 1}]] != 4} {
1642        grid [TitleFrame $w.8 -bd 6 -relief groove \
1643                -text "Erase Atom$suffix"] \
1644                -row 8 -column 0 -columnspan 10 -sticky news
1645        set w2 [$w.8 getframe]
1646        grid [button $w2.do -text "Erase Atom${suffix}" \
1647                -command "EraseAtoms $phase [list $numberList] $w" \
1648                ] -row 2 -column 0 -columnspan 10
1649    }
1650
1651    grid rowconfigure $w 9 -minsize 5
1652    grid [frame $w.b] -row 10 -column 0 -columnspan 10 -sticky ew
1653    pack [button $w.b.3 -text Close -command "destroy $w"] -side left \
1654            -padx 5 -pady 5
1655    pack [button $w.b.help -text Help -bg yellow \
1656            -command "MakeWWWHelp expgui2.html xform"] -side right \
1657            -padx 5 -pady 5
1658    bind $w <Return> "destroy $w"
1659
1660    # force the window to stay on top
1661    putontop $w
1662    focus $w.b.3
1663    tkwait window $w
1664    afterputontop
1665    # if there are selected atoms, reset their display
1666    if {[llength $expgui(selectedatomlist)] != 0} editRecord
1667}
1668
1669# transform the coordinates
1670proc XformAtomsCoord {phase numberList w1} {
1671    global expgui expmap
1672    if {[lindex $expmap(phasetype) [expr {$phase - 1}]] == 4} {
1673        set cmd mmatominfo
1674    } else {
1675        set cmd atominfo
1676    }
1677    # get the matrix
1678    foreach v {x y z} {
1679        foreach o {x y z} {
1680            set matrix(${v}${o}) [$w1.e${v}${o} get]
1681        }
1682        set matrix(${v}) [$w1.e${v} get]
1683    }
1684    foreach atom $numberList {
1685        foreach v {x y z} {
1686            set $v [$cmd $phase $atom $v]
1687        }
1688        foreach v {x y z} {
1689            set new$v $matrix(${v})
1690            foreach o {x y z} {
1691                set new$v [expr [set new$v] + $matrix(${v}${o})*[set $o]]
1692            }
1693            $cmd $phase $atom $v set [set new$v]
1694        }
1695        incr expgui(changed)
1696    }
1697    UpdateAtomLine $numberList $phase
1698}
1699
1700# set the occupancies to a single value
1701proc XformAtomsOcc {phase numberList w2} {
1702    global expgui expmap
1703    if {[lindex $expmap(phasetype) [expr {$phase - 1}]] == 4} {
1704        set cmd mmatominfo
1705    } else {
1706        set cmd atominfo
1707    }
1708    # get the value
1709    set val [$w2.e get]
1710    foreach atom $numberList {
1711        $cmd $phase $atom frac set $val
1712        incr expgui(changed)
1713    }
1714    UpdateAtomLine $numberList $phase
1715}
1716
1717# transform Uiso or Uij; if anisotropic set Uequiv to Uij
1718proc XformAtomsU {phase numberList w2} {
1719    global expgui
1720    if {$w2 == "iso"} {
1721        foreach atom $numberList {
1722            if {[atominfo $phase $atom temptype] != "I"} {
1723                atominfo $phase $atom temptype set I
1724                incr expgui(changed)
1725            }
1726        }
1727    } elseif {$w2 == "aniso"} {
1728        foreach atom $numberList {
1729            if {[atominfo $phase $atom temptype] == "I"} {
1730                atominfo $phase $atom temptype set A
1731                incr expgui(changed)
1732            }
1733        }
1734    } else {
1735        # get the value
1736        set val [$w2.e get]
1737        foreach atom $numberList {
1738            global expmap
1739            if {[lindex $expmap(phasetype) [expr {$phase - 1}]] == 4} {
1740                mmatominfo $phase $atom Uiso set $val
1741            } elseif {[atominfo $phase $atom temptype] == "I"} {
1742                atominfo $phase $atom Uiso set $val
1743            } else {
1744                atominfo $phase $atom U11 set $val
1745                atominfo $phase $atom U22 set $val
1746                atominfo $phase $atom U33 set $val
1747                atominfo $phase $atom U12 set 0.0
1748                atominfo $phase $atom U13 set 0.0
1749                atominfo $phase $atom U23 set 0.0
1750            }
1751            incr expgui(changed)
1752        }
1753    }
1754    UpdateAtomLine $numberList $phase
1755}
1756
1757# confirm and erase atoms
1758proc EraseAtoms {phase numberList w2} {
1759    global expgui
1760    if {[llength $numberList] <= 0} return
1761    # make a list of atoms
1762    foreach atom $numberList {
1763        append atomlist "\n\t$atom  [atominfo $phase $atom label]"
1764    }
1765    set msg "OK to remove the following [llength $numberList] atoms from phase $phase:$atomlist"
1766    set val [MyMessageBox -parent $w2 -type okcancel -icon warning \
1767            -default cancel -title "Confirm Erase" -message $msg]
1768    if {$val == "ok"} {
1769        foreach atom $numberList {
1770            EraseAtom $atom $phase
1771            incr expgui(changed)
1772        }
1773        mapexp
1774        DisplayAllAtoms $phase
1775        destroy $w2
1776    }
1777}
1778
1779#----------- more Add Phase routines (import) -------------------------------
1780proc ImportPhase {format np} {
1781    global expgui
1782    foreach item $expgui(extensions_$format) {
1783        lappend typelist [list $format $item]
1784    }
1785    lappend typelist [list "All files" *]
1786    set file [tk_getOpenFile -parent $np -filetypes $typelist]
1787    if {![file exists $file]} return
1788    # read in the file
1789    set input [$expgui(proc_$format) $file]
1790    catch {
1791        $np.bf.b1 config -text "Continue" -command "addphase $np; AddAtomsList"
1792        bind $np <Return> "addphase $np; AddAtomsList"
1793    }
1794    catch {
1795        $np.t1 delete 0 end
1796        $np.t1 insert end "from $file"
1797    }
1798    $np.t2 delete 0 end
1799    $np.t2 insert end [lindex $input 0]
1800    foreach i {.e1a .e1b .e1c .e2a .e2b .e2g} val [lindex $input 1] {
1801        $np.f$i delete 0 end
1802        $np.f$i insert end $val
1803    }
1804    set expgui(coordList) [lindex $input 2]
1805    set msg [lindex $input 3]
1806    if {$msg != ""} {
1807        catch {destroy $np.msg}
1808        grid [label $np.msg -text $msg -fg red -anchor center -bd 4 -relief raised] \
1809                -column 0 -columnspan 99 -row 20 -sticky ew
1810    }
1811}
1812
1813proc ImportAtoms {format top phase} {
1814    global expgui
1815    foreach item $expgui(extensions_$format) {
1816        lappend typelist [list $format $item]
1817    }
1818    lappend typelist [list "All files" *]
1819    set file [tk_getOpenFile -parent $top -filetypes $typelist]
1820    if {![file exists $file]} return
1821    # disable during read
1822    catch {
1823        foreach b "$top.b1 $top.b2 $top.fr.b3" {
1824            $b config -state disabled
1825        }
1826    }
1827    # read in the file
1828    set input [$expgui(proc_$format) $file]
1829    # add atoms to table
1830    foreach item [lindex $input 2] {
1831        set row [MakeAddAtomsRow $top]
1832        set np $top.canvas.fr
1833        foreach val $item w {n x y z t o u} {
1834            if {$val != ""} {
1835                $np.e${row}$w delete 0 end
1836                $np.e${row}$w insert end $val
1837            }
1838        }
1839    }
1840    # sort the atoms by number, so that empty entries are at the bottom
1841    sortAddAtoms $phase $top number
1842    # reenable
1843    catch {
1844        foreach b "$top.b1 $top.b2 $top.fr.b3" {
1845            $b config -state normal
1846        }
1847    }
1848}
1849
1850proc AddAtomsList {} {
1851    global expgui expmap
1852    # skip if we aborted out of addphase
1853    if {$expgui(oldphaselist) == -1} return
1854    # find the new phase
1855    set phase {}
1856    foreach p $expmap(phaselist) {
1857        if {[lsearch $expgui(oldphaselist) $p] == -1} {
1858            set phase $p
1859            break
1860        }
1861    }
1862    if {$phase == ""} return
1863    MakeAddAtomsBox $phase $expgui(coordList)
1864}
1865
1866# get the input formats by sourcing files named import_*.tcl
1867proc GetImportFormats {} {
1868    global expgui tcl_platform
1869    # only needs to be done once
1870    if [catch {set expgui(importFormatList)}] {
1871        set filelist [glob -nocomplain [file join $expgui(scriptdir) import_*.tcl]]
1872        foreach file $filelist {
1873            set description ""
1874            source $file
1875            if {$description != ""} {
1876                lappend expgui(importFormatList) $description
1877                if {$tcl_platform(platform) == "unix"} {
1878                    set extensions "[string tolower $extensions] [string toupper $extensions]"
1879                }
1880                set expgui(extensions_$description) $extensions
1881                set expgui(proc_$description) $procname
1882            }
1883        }
1884    }
1885}
1886
1887proc MakeReplacePhaseBox {} {
1888    global expmap expgui tcl_platform
1889
1890    set expgui(coordList) {}
1891    # ignore the command if no phase is selected
1892    foreach p {1 2 3 4 5 6 7 8 9} {
1893        if {[lsearch $expmap(phaselist) $expgui(curPhase)] == -1} {
1894            return
1895        }
1896    }
1897
1898    set top .newphase
1899    catch {destroy $top}
1900    toplevel $top
1901    bind $top <Key-F1> "MakeWWWHelp expgui2.html replacephase"
1902
1903    grid [label $top.l1 -text "Replacing phase #$expgui(curPhase)" \
1904            -bg yellow -anchor center] -column 0 -columnspan 8 -row 0 -sticky ew
1905    grid [label $top.l3a -text "Current Space Group: "] \
1906            -column 0 -row 2 -columnspan 2 -sticky e
1907    grid [label $top.l3b -text [phaseinfo $expgui(curPhase) spacegroup]\
1908            -bd 4 -relief groove] \
1909            -column 2 -row 2  -sticky ew
1910    grid [label $top.l4 -text "New Space Group: "] \
1911            -column 0 -row 3 -columnspan 2 -sticky e
1912    grid [entry $top.t2 -width 12] -column 2 -row 3 -sticky w
1913    grid [radiobutton $top.r1 -text "Reenter current atoms"\
1914            -variable expgui(DeleteAllAtoms) -value 0] \
1915            -column 1 -row 4 -columnspan 8 -sticky w
1916    grid [radiobutton $top.r2 -text "Delete current atoms" \
1917            -variable expgui(DeleteAllAtoms) -value 1] \
1918            -column 1 -row 5 -columnspan 8 -sticky w
1919   
1920    grid [frame $top.f -bd 4 -relief groove] \
1921            -column 3 -row 2 -columnspan 3 -rowspan 4
1922    set col -1
1923    foreach i {a b c} {
1924        grid [label $top.f.l1$i -text " $i "] -column [incr col] -row 1
1925        grid [entry $top.f.e1$i -width 12] -column [incr col]  -row 1
1926        $top.f.e1$i delete 0 end
1927        $top.f.e1$i insert 0 [phaseinfo $expgui(curPhase) $i]
1928    }
1929    set col -1
1930    foreach i {a b g} var {alpha beta gamma} {
1931        grid [label $top.f.l2$i -text $i] -column [incr col] -row 2
1932        set font [$top.f.l2$i cget -font]
1933        $top.f.l2$i config -font "Symbol [lrange $font 1 end]"
1934        grid [entry $top.f.e2$i -width 12] -column [incr col]  -row 2
1935        $top.f.e2$i delete 0 end
1936        $top.f.e2$i insert 0 [phaseinfo $expgui(curPhase) $var]
1937    } 
1938
1939    grid [button $top.b1 -text Continue \
1940            -command "replacephase1 $top $expgui(curPhase)"] \
1941            -column 0 -row 6 -sticky w
1942    bind $top <Return> "replacephase1 $top $expgui(curPhase)"
1943    grid [button $top.b2 -text Cancel \
1944            -command "destroy $top"] -column 1 -row 6 -sticky w
1945    grid [button $top.help -text Help -bg yellow \
1946            -command "MakeWWWHelp expgui2.html replacephase"] \
1947            -column 2 -row 6
1948
1949    # get the input formats if not already defined
1950    GetImportFormats
1951    if {[llength $expgui(importFormatList)] > 0} {
1952        grid [frame $top.fr -bd 4 -relief groove] \
1953                -column 2 -row 6 -columnspan 8 -sticky e
1954        grid [button $top.fr.b3 -text "Import phase from: " \
1955                -command "ImportPhase \$expgui(importFormat) $top"] \
1956                -column 0 -row 0 -sticky e
1957        set menu [eval tk_optionMenu $top.fr.b4 expgui(importFormat) \
1958                $expgui(importFormatList)]
1959        for {set i 0} {$i <= [$menu index end]} {incr i} {
1960            $menu entryconfig $i -command "ImportPhase \$expgui(importFormat) $np"
1961        }
1962        grid $top.fr.b4 -column 1 -row 0 -sticky w
1963        grid rowconfig $top.fr 0 -pad 10
1964        grid columnconfig $top.fr 0 -pad 10
1965        grid columnconfig $top.fr 1 -pad 10
1966#       grid columnconfig $top 4 -weight 1
1967        grid columnconfig $top 2 -weight 1
1968    }
1969   
1970    wm title $top "Replace phase $expgui(curPhase)"
1971
1972    # set grab, etc.
1973    putontop $top
1974
1975    tkwait window $top
1976
1977    # fix grab...
1978    afterputontop
1979}
1980
1981proc replacephase1 {top phase} {
1982    # validate cell & space group & save to pass
1983    global expgui expmap
1984    set expgui(SetAddAtomsScroll) 0
1985    # validate the input
1986    set err {}
1987    set spg [$top.t2 get]
1988    if {[string trim $spg] == ""} {
1989        append err "  Space group cannot be blank\n"
1990    }
1991    set cell {}
1992    foreach i {a b c a b g} lbl {a b c alpha beta gamma} n {1 1 1 2 2 2} {
1993        set $lbl [$top.f.e${n}$i get]
1994        if {[string trim [set $lbl]] == ""} {
1995            append err "  $lbl cannot be blank\n"
1996        } elseif {[catch {expr [set $lbl]}]} {
1997            append err "  [set $lbl] is not valid for $lbl\n"
1998        }
1999        lappend cell [set $lbl]
2000    }
2001
2002    if {$err != ""} {
2003        MyMessageBox -parent $top -title "Replace Phase Error" -icon warning \
2004                -message "The following error(s) were found in your input:\n$err" 
2005        return
2006    }
2007
2008    # check the space group
2009    set fp [open spg.in w]
2010    puts $fp "N"
2011    puts $fp "N"
2012    puts $fp $spg
2013    puts $fp "Q"
2014    close $fp
2015    global tcl_platform
2016    catch {
2017        if {$tcl_platform(platform) == "windows"} {
2018            exec [file join $expgui(gsasexe) spcgroup.exe] < spg.in >& spg.out
2019        } else {
2020            exec [file join $expgui(gsasexe) spcgroup] < spg.in >& spg.out
2021        }
2022    }
2023    set fp [open spg.out r]
2024    set out [read $fp]
2025    close $fp
2026    # attempt to parse out the output (fix up if parse did not work)
2027    if {[regexp "space group symbol.*>(.*)Enter a new space group symbol" \
2028            $out a b ] != 1} {set b $out}
2029    if {[string first Error $b] != -1} {
2030        # got an error, show it
2031        ShowBigMessage \
2032                 $top.error \
2033                 "Error processing space group\nReview error message below" \
2034                 $b OK "" 1
2035        return
2036    } else {
2037        # show the result and confirm
2038        set opt [ShowBigMessage \
2039                $top.check \
2040                "Check the symmetry operators in the output below" \
2041                $b \
2042                {Continue Redo} ]
2043        if {$opt > 1} return
2044    }
2045    file delete spg.in spg.out
2046    # draw coordinates box
2047    eval destroy [winfo children $top]
2048    grid [label $top.l1 -relief groove -bd 4 -anchor center\
2049            -text "Atom list for phase #$phase"] \
2050            -column 0 -row 0 \
2051            -sticky we -columnspan 10
2052    grid [canvas $top.canvas \
2053            -scrollregion {0 0 5000 500} -width 0 -height 250 \
2054            -yscrollcommand "$top.scroll set"] \
2055            -column 0 -row 2 -columnspan 4 -sticky nsew
2056    grid columnconfigure $top 3 -weight 1
2057    grid rowconfigure $top 2 -weight 1
2058    grid rowconfigure $top 1 -pad 5
2059    scrollbar $top.scroll \
2060            -command "$top.canvas yview"
2061    frame $top.canvas.fr
2062    $top.canvas create window 0 0 -anchor nw -window $top.canvas.fr
2063
2064    set np $top.canvas.fr
2065    set row 0
2066    set col 0
2067    grid [label $np.l_${row}0 -text "  #  "] -column $col -row $row
2068    foreach i {Atom\ntype Name x y z Occ Uiso} \
2069            var {type name x y z occ uiso} {
2070        grid [button $np.l_${row}$i -text $i -padx 0 -pady 0 \
2071                -command "sortAddAtoms $phase $top $var"] \
2072                -column [incr col] -row $row -sticky nsew
2073    }
2074    grid [label $np.l_${row}Use -text Use\nFlag] -column [incr col] -row $row
2075
2076    # add the old atoms, if appropriate
2077    if {!$expgui(DeleteAllAtoms)} {
2078        # loop over all atoms
2079        foreach atom $expmap(atomlist_$phase) {
2080            set row [MakeAddAtomsRow $top]
2081            # add all atoms in the current phase to the list
2082            foreach w {n x y z t o} var {label x y z type frac} {
2083                $np.e${row}$w delete 0 end
2084                $np.e${row}$w insert end [atominfo $phase $atom $var]
2085            }
2086            $np.e${row}u delete 0 end
2087            if {[atominfo $phase $atom temptype] == "I"} {
2088                $np.e${row}u insert end [atominfo $phase $atom Uiso]
2089            } else {
2090                $np.e${row}u insert end [expr ( \
2091                        [atominfo $phase $atom U11] + \
2092                        [atominfo $phase $atom U22] + \
2093                        [atominfo $phase $atom U33]) / 3.]
2094            }
2095        }
2096    }
2097
2098    # add coordinates that have been read in, if any
2099    foreach item $expgui(coordList) {
2100        set row [MakeAddAtomsRow $top]
2101        foreach val $item w {n x y z t o u} {
2102            if {$val != ""} {
2103                $np.e${row}$w delete 0 end
2104                $np.e${row}$w insert end $val
2105            }
2106        }
2107    }
2108    # a blank spot in the table
2109    MakeAddAtomsRow $top
2110
2111    bind $top <Configure> "SetAddAtomsScroll $top"
2112    grid rowconfigure $top 3 -min 10
2113    grid [button $top.b1 -text "Continue"\
2114            -command "replacephase2 $phase $top [list $spg] [list $cell]"] \
2115            -column 0 -row 5 -sticky w
2116    bind $top <Return> "replacephase2 $phase $top [list $spg] [list $cell]"
2117    grid [button $top.b2 -text Cancel \
2118            -command "destroy $top"] -column 1 -row 5 -sticky w
2119    if {[llength $expgui(importFormatList)] > 0} {
2120        grid [frame $top.fr -bd 4 -relief groove] \
2121                -column 3 -row 5 -columnspan 2 -sticky e
2122        grid [button $top.fr.b3 -text "Import atoms from: " \
2123                -command "ImportAtoms \$expgui(importFormat) $top $phase"] \
2124                -column 0 -row 0 -sticky e
2125        set menu [eval tk_optionMenu $top.fr.b4 expgui(importFormat) \
2126                $expgui(importFormatList)]
2127        for {set i 0} {$i <= [$menu index end]} {incr i} {
2128            $menu entryconfig $i -command "ImportAtoms \$expgui(importFormat) $top $phase"
2129        }
2130        grid $top.fr.b4 -column 1 -row 0 -sticky w
2131        grid rowconfig $top.fr 0 -pad 10
2132        grid columnconfig $top.fr 0 -pad 10
2133        grid columnconfig $top.fr 1 -pad 10
2134    }
2135
2136    grid [button $top.b3 -text  "More atom boxes" \
2137            -command "MakeAddAtomsRow $top"] -column 3 \
2138            -columnspan 2 -row 4 -sticky e
2139   
2140    wm title $top "Replacing phase: Enter atoms"
2141    SetAddAtomsScroll $top
2142
2143    # fix grab for old window
2144    afterputontop
2145    # set grab, etc.
2146    putontop $top
2147}
2148
2149proc replacephase2 {phase top spg cell} {
2150    global expgui expmap env
2151    # validate coordinates
2152    set np $top.canvas.fr
2153    # validate the atoms info
2154    set atomlist [ValidateAtomsBox $top $np]
2155    if {$atomlist == ""} return
2156
2157    pleasewait "updating phase"
2158    # replace spacegroup and cell
2159    phaseinfo $phase spacegroup set $spg
2160    foreach val $cell var {a b c alpha beta gamma} {
2161        phaseinfo $phase $var set $val
2162    }
2163    incr expgui(changed) 
2164    # delete all atoms
2165    foreach i $expmap(atomlist_$phase) {
2166        EraseAtom $i $phase
2167        incr expgui(changed) 
2168    }
2169    # write new atoms from table as input to exptool
2170    set fp [open exptool.in w]
2171    puts $fp "A"
2172    puts $fp $phase
2173    # number of atoms
2174    puts $fp [llength $atomlist]
2175    foreach atomline $atomlist {
2176        puts $fp $atomline
2177        incr expgui(changed) 
2178    }
2179    close $fp
2180    # needed in UNIX
2181    set env(ATOMDATA) [file join $expgui(gsasdir) data atmdata.dat]
2182    set env(gsas) [file nativename $expgui(gsasdir)]
2183    # needed in Windows
2184    set env(GSAS) [file nativename $expgui(gsasdir)]
2185
2186    global tcl_platform
2187    # Save the current exp file
2188    savearchiveexp
2189    # disable the file changed monitor
2190    set expgui(expModifiedLast) 0
2191    set expnam [file root [file tail $expgui(expfile)]]
2192    catch {
2193        if {$tcl_platform(platform) == "windows"} {
2194            exec [file join $expgui(gsasexe) exptool.exe] $expnam \
2195                    < exptool.in >& exptool.out
2196        } else {
2197            exec [file join $expgui(gsasexe) exptool] $expnam \
2198                    < exptool.in >& exptool.out
2199        }
2200    } errmsg
2201    # load the revised exp file
2202    loadexp $expgui(expfile)
2203    set fp [open exptool.out r]
2204    set out [read $fp]
2205    close $fp
2206    set err 0
2207    if {[llength $atomlist] != [llength $expmap(atomlist_$phase))]} {
2208        set err 1
2209    }
2210    if {$errmsg != ""} {
2211        append errmsg "\n" $out
2212        set err 1
2213    } else {
2214        set errmsg $out
2215    }
2216    donewait 
2217    if {$expgui(showexptool) || $err} {
2218        set msg "Please review the result from adding the atom(s)" 
2219        if {$err} {append msg "\nIt appears an error occurred!"}
2220        ShowBigMessage $top $msg $errmsg OK "" $err
2221    }
2222    file delete exptool.in exptool.out
2223    # set the powpref warning (2 = required)
2224    set expgui(needpowpref) 2
2225    set msg "A phase was replaced"
2226    if {[string first $msg $expgui(needpowpref_why)] == -1} {
2227        append expgui(needpowpref_why) "\t$msg\n"
2228    }
2229    destroy $top
2230}
2231
2232proc sortAddAtoms {phase top sortvar} {
2233    global expgui
2234    set np $top.canvas.fr
2235    set validlist {}
2236    set invalidlist {}
2237    set row 0
2238    while {![catch {grid info $np.e[incr row]t}]} {
2239        set valid 1
2240        set line $row
2241        if !{$expgui(UseAtom$row)} {set valid 0}
2242        lappend line $expgui(UseAtom$row)
2243        if {[set type [string trim [$np.e${row}t get]]] == ""} {set valid 0}
2244        lappend line [string trim [$np.e${row}t get]]
2245        lappend line [string trim [$np.e${row}n get]]
2246        foreach i {x y z o u} {
2247            set tmp [string trim [$np.e${row}$i get]]
2248            lappend line $tmp
2249            if {$tmp == "" || [catch {expr $tmp}]} {set valid 0}
2250        }
2251        if {$valid} {
2252            lappend validlist $line
2253        } else {
2254            lappend invalidlist $line
2255        }
2256    }
2257    switch $sortvar {
2258        type {set sortlist [lsort -index 2 -dictionary $validlist]}
2259        name {set sortlist [lsort -index 3 -dictionary $validlist]}
2260        x {set sortlist [lsort -index 4 -real $validlist]}
2261        y {set sortlist [lsort -index 5 -real $validlist]}
2262        z {set sortlist [lsort -index 6 -real $validlist]}
2263        occ {set sortlist [lsort -index 7 -real $validlist]}
2264        uiso  {set sortlist [lsort -index 8 -real $validlist]}
2265        default {set sortlist $validlist}
2266    }
2267
2268    if {[llength $invalidlist] > 0} {append sortlist " $invalidlist"}
2269    set row 0
2270    foreach line $sortlist {
2271        incr row
2272        set expgui(UseAtom$row) [lindex $line 1]
2273        foreach item [lrange $line 2 end] \
2274                var {t n x y z o u} {
2275            $np.e${row}$var delete 0 end
2276            $np.e${row}$var insert end $item
2277        }
2278    }
2279}
2280
2281proc EditInstFile {"filename {}"} {
2282    global expgui
2283    # on the first call, load the commands
2284    if {[catch {
2285        if {[info procs instMakeWindow] == ""} {
2286            source [file join $expgui(scriptdir) instedit.tcl]
2287        }
2288    } errmsg]} {
2289        MyMessageBox -parent . -title "Load error" \
2290                -message "Unexpected error while sourcing file instedit.tcl: $errmsg" \
2291                -icon error
2292    }
2293    instMakeWindow $filename
2294}
2295
2296# default
2297set newhist(insttype) {}
2298set newhist(dummy) 0
2299set newhist(instfiletext) {}
Note: See TracBrowser for help on using the repository browser.