source: trunk/liveplot @ 686

Last change on this file since 686 was 669, checked in by toby, 16 years ago

# on 2003/04/10 22:01:33, toby did:
change header
keep weights (for export)
use normalized data for BKGEDIT (fit is incorrect for TOF w/o)
allow export routines (for FOX)
allow 1,2,... keys to turn on phase tickmarks

  • Property rcs:author set to toby
  • Property rcs:date set to 2003/04/10 22:01:33
  • Property rcs:lines set to +29 -8
  • Property rcs:rev set to 1.31
  • Property rcs:state set to Exp
  • Property svn:keywords set to Author Date Revision Id
File size: 67.5 KB
Line 
1#!/bin/sh
2# the next line restarts this script using wish found in the path\
3exec wish "$0" "$@"
4# If this does not work, change the #!/usr/bin/wish line below
5# to reflect the actual wish location and delete all preceeding lines
6#
7# (delete here and above)
8#!/usr/bin/wish
9# $Id: liveplot 669 2009-12-04 23:10:02Z toby $
10set Revision {$Revision: 669 $ $Date: 2009-12-04 23:10:02 +0000 (Fri, 04 Dec 2009) $}
11
12bind all <Control-KeyPress-c> {destroy .}
13# process command line arguments
14set exitstat 0
15set expnam [lindex $argv 0]
16if {$expnam == ""} {puts "error -- no experiment name"; set exitstat 1}
17if $exitstat {
18    puts "usage: $argv0 expnam \[hist #\] \[legend\]"
19    destroy .
20}
21set program [file tail $argv0]
22#set program bkgedit
23
24if {[lindex $argv 1] == ""} {
25    set hst 1
26} else {
27    set hst [lindex $argv 1]
28}
29if {[lindex $argv 2] == ""} {
30    set graph(legend) 1
31} else {
32    set graph(legend) [lindex $argv 2]
33}
34
35set graph(backsub) 0
36
37if {$tcl_platform(platform) == "windows"} {
38    set graph(printout) 1
39    set expgui(tcldump) tcldump.exe
40} else {
41    set graph(printout) 0
42    set expgui(tcldump) tcldump
43}
44
45# default values
46set weightlist {}
47set graph(outname) out.ps
48set graph(outcmd) lpr
49set xunits {}
50set yunits {}
51set graph(chi2) 0
52set graph(xunits) 0
53set graph(yunits) 0
54set graph(autoraise) 1
55set graph(color_diff) blue
56set graph(color_chi2) magenta
57set graph(color_bkg) green
58set graph(color_obs) black
59set graph(color_input) magenta
60set graph(color_fit) blue
61set expgui(debug) 0
62catch {if $env(DEBUG) {set expgui(debug) 1}}
63#set expgui(debug) 1
64set expgui(font) 14
65set expgui(lblfontsize) 15
66set expgui(fadetime) 10
67set expgui(hklbox) 1
68set expgui(autotick) 0
69set expgui(pixelregion) 5
70# location for web pages, if not found locally
71set expgui(website) www.ncnr.nist.gov/xtal/software/expgui
72set peakinfo(obssym) scross
73if {$program == "bkgedit"}  {
74    set peakinfo(obssize) 0.15
75    set graph(color_calc) pink
76    set graph(yunits) 1
77} else {
78    set peakinfo(obssize) 1.0
79    set graph(color_calc) red
80}
81set peakinfo(inpsym) triangle
82set peakinfo(inpsize) 1.0
83# create a set of markers for each phase
84for {set i 1} {$i < 10} {incr i} {
85    set peakinfo(flag$i) 0
86    set peakinfo(max$i) Inf
87    set peakinfo(min$i) -Inf
88    set peakinfo(dashes$i) 1
89    set graph(label$i) Phase$i
90}
91set expgui(RadiiList) {}
92
93proc waitmsg {message} {
94    set w .wait
95    # kill any window/frame with this name
96    catch {destroy $w}
97    pack [frame $w]
98    frame $w.bot -relief raised -bd 1
99    pack $w.bot -side bottom -fill both
100    frame $w.top -relief raised -bd 1
101    pack $w.top -side top -fill both -expand 1
102    label $w.msg -justify left -text $message -wrap 3i
103    catch {$w.msg configure -font \
104                -Adobe-Times-Medium-R-Normal--*-180-*-*-*-*-*-*
105    }
106    pack $w.msg -in $w.top -side right -expand 1 -fill both -padx 3m -pady 3m
107    label $w.bitmap -bitmap info
108    pack $w.bitmap -in $w.top -side left -padx 3m -pady 3m
109    update
110}
111
112proc donewaitmsg {} {
113    catch {destroy .wait}
114    update
115}
116
117waitmsg "Loading histogram, Please wait"
118
119#--------------------------------------------------------------
120# define constants
121array set peakinfo {
122    color1 magenta
123    color2 cyan
124    color3 yellow
125    color4 sienna
126    color5 orange
127    color6 DarkViolet
128    color7 HotPink
129    color8 salmon
130    color9 LimeGreen
131}
132set cycle -1
133set modtime 0
134
135#----------------------------------------------------------------
136# where are we?
137set expgui(script) [info script]
138# translate links -- go six levels deep
139foreach i {1 2 3 4 5 6} {
140    if {[file type $expgui(script)] == "link"} {
141        set link [file readlink $expgui(script)]
142        if { [file  pathtype  $link] == "absolute" } {
143            set expgui(script) $link
144        } {
145            set expgui(script) [file dirname $expgui(script)]/$link
146        }
147    } else {
148        break
149    }
150}
151
152# fixup relative paths
153if {[file pathtype $expgui(script)] == "relative"} {
154    set expgui(script) [file join [pwd] $expgui(script)]
155}
156set expgui(scriptdir) [file dirname $expgui(script) ]
157set expgui(gsasdir) [file dirname $expgui(scriptdir)]
158set expgui(gsasexe) [file join $expgui(gsasdir) exe]
159set expgui(docdir) [file join $expgui(scriptdir) doc]
160
161source [file join $expgui(scriptdir) gsascmds.tcl]
162source [file join $expgui(scriptdir) readexp.tcl]
163source [file join $expgui(scriptdir) opts.tcl]
164
165if {$program == "bkgedit"}  {
166    lappend auto_path $expgui(scriptdir)
167    if {$tcl_version < 8.1} {
168        MyMessageBox -parent . -title "La Load Error" \
169                -message "$program requires Tcl/Tk version 8.1 or higher" \
170                -helplink "expgui.html La" \
171                -icon error -type Exit -default exit
172        exit
173    }
174    if [catch {package require La} errmsg] {
175        MyMessageBox -parent . -title "La Load Error" \
176                -message "Error -- Unable to load the La (Linear Algebra) package; cannot run $program" \
177                -helplink "expgui.html La" \
178                -icon error -type Exit -default exit
179        exit
180    }
181}
182
183if [catch {package require BLT} errmsg] {
184    MyMessageBox -parent . -title "BLT Error" \
185            -message "Error -- Unable to load the BLT package; cannot run $program" \
186            -helplink "expgui.html blt" \
187            -icon error -type Exit -default exit
188    exit
189}
190# handle Tcl/Tk v8+ where BLT is in a namespace
191#  use the command so that it is loaded
192catch {blt::graph}
193catch {
194    namespace import blt::graph
195    namespace import blt::vector
196}
197# old versions of blt don't report a version number
198if [catch {set blt_version}] {set blt_version 0}
199# option for coloring markers: note that GH keeps changing how to do this!
200# also element -mapped => -show
201if {$blt_version < 2.3 || $blt_version >= 8.0} {
202    # version 8.0 is ~same as 2.3
203    set graph(MarkerColorOpt) -fg
204    # mapped is needed in 8.0, both are OK in 2.3
205    set graph(ElementShowOption) "-mapped 1"
206    set graph(ElementHideOption) "-mapped 0"
207} elseif {$blt_version >= 2.4} {
208    set graph(MarkerColorOpt) -outline
209    set graph(ElementShowOption) "-hide 0"
210    set graph(ElementHideOption) "-hide 1"
211} else {
212    set graph(MarkerColorOpt) -color
213    set graph(ElementShowOption) "-mapped 1"
214    set graph(ElementHideOption) "-mapped 0"
215}
216
217# called by a trace on expgui(lblfontsize)
218proc setfontsize {a b c} {
219    global expgui graph
220    catch {
221        font config lblfont -size [expr -$expgui(lblfontsize)]
222        # this forces a redraw of the plot by changing the title to itself
223        .g configure -title [.g cget -title]
224    }
225}
226# define a font used for labels
227if {$tcl_version >= 8.0} {
228    font create lblfont -family Helvetica -size [expr -$expgui(lblfontsize)]
229    trace variable expgui(lblfontsize) w setfontsize
230}
231
232proc readdata {box} { 
233    global expgui modtime expnam
234    if [catch {
235        set modtime [file mtime $expnam.EXP]
236        set loadtime [time {
237            if {$expgui(tcldump) == ""} {
238                set p HSTDMP
239                readdata_hst $box
240            } else {
241                set p TCLDUMP
242                readdata_tcl $box
243            }
244        }]
245        if $expgui(debug) {
246            tk_dialog .time "Timing info" \
247                    "Histogram loading took $loadtime" "" 0 OK
248        }
249    } errmsg] {
250        if $expgui(debug) {
251            catch {console show}
252            error $errmsg
253        }
254        $box config -title "Read error"
255        MyMessageBox -parent . -title "$p Error" \
256                -message "There was an error running the $p program. The most common reason for this is that POWPREF & GENLES have not been run.\n\nError message: $errmsg" \
257                -icon error -type Continue -default continue \
258                -helplink "expguierr.html TCLDUMPError"
259        update
260    }
261    $box element show [lsort -decreasing [$box element show]]
262    global program
263    if {$program == "bkgedit"}  bkghstInit
264}
265   
266proc readdata_hst {box} {
267    global expgui expnam reflns
268    global lasthst
269    global hst peakinfo xunits weightlist
270    $box config -title "(Histogram update in progress)"
271    update
272    # parse the output of a file
273    set lasthst $hst
274###########################################################################
275#       set input [open histdump.inp w]
276#       puts $input "$hst"
277#       close $input
278#       set input [open "| $expgui(gsasexe)/hstdump $expnam  < histdump.inp" w+]
279###########################################################################
280    # use histdmp for histogram info
281    set input [open histdump$hst.inp w]
282    puts $input "$expnam"
283    puts $input "L"
284    puts $input "$hst"
285    puts $input "0"
286    close $input
287    # use hstdmp without an experiment name so that output
288    # is not sent to the .LST file
289    set input [open "| $expgui(gsasexe)/hstdmp < histdump$hst.inp" r]
290   
291    # initalize arrays
292    set num -1
293    set xlist {}
294    set obslist {}
295    set calclist {}
296    set bcklist {}
297    set xunits {}
298    set weightlist {}
299    # define a list of reflection positions for each phase
300    for {set i 1} {$i < 10} {incr i} {
301        set reflns($i) {}
302    }
303    set i 0
304    while {[gets $input line] >= 0} {
305        incr i
306        # run update every 50th line
307        if {$i > 50} {set i 0; update}
308        if [scan $line %d num] {
309            if {$num > 0} {
310                set Ispec 0
311                set X -999
312                scan [string range $line 8 end] %e%e%e%e%e%e \
313                        X Iobs Icalc Ispec fixB fitB
314                #puts $line
315                # eliminate excluded points
316                if {$Ispec > 0.0 && $X >= 0} {
317                    lappend xlist $X
318                    lappend obslist $Iobs
319                    lappend calclist $Icalc
320                    lappend bcklist [expr {$fixB + $fitB}]
321                }
322                # add peaks to peak lists
323                #    puts "[string range $line 6 6]"
324                # is this 6 or 7; 6 on win & 7 on SGI
325                if [regexp {[1-9]} [string range $line 6 7] ph] {
326                    lappend reflns($ph) $X
327                }
328            } 
329        } else {
330            regexp {Time|Theta|keV} $line xunits
331        }
332    }
333    if {$xunits == "Theta"} {set xunits "2-Theta"}
334    close $input
335    catch {file delete histdump$hst.inp}
336    xvec set $xlist
337    obsvec set $obslist
338    calcvec set $calclist
339    bckvec set $bcklist
340    diffvec set [obsvec - calcvec]
341    global obsvec calcvec diffvec
342    set maxdiff  [set diffvec(max)]
343    set cmin [set calcvec(min)]
344    set omin [set obsvec(min)]
345    set cmax [set calcvec(max)]
346    set omax [set obsvec(max)]
347    set expgui(min) [expr {$omin < $cmin ? $omin : $cmin}]
348    set expgui(max) [expr {$omax > $cmax ? $omax : $cmax}]
349    set ymin1 [expr {$cmin - 1.1*$maxdiff}]
350    set ymin2 [expr {$omin - 1.1*$maxdiff}]
351    if {$ymin1 < $ymin2} {
352        diffvec set [diffvec + $ymin1]
353    } {
354        diffvec set [diffvec + $ymin2]
355    }
356    plotdata
357}
358
359proc readdata_tcl {box} {
360    global expgui expnam reflns
361    global lasthst graph weightlist
362    global hst peakinfo xunits yunits
363    $box config -title "(Histogram update in progress)"
364    update
365    # parse the output of a file
366    set lasthst $hst
367    # use tcldump
368    set input [open histdump$hst.inp w]
369    puts $input "$hst"
370    # x units -- native
371    puts $input "$graph(xunits)" 
372    # y units  -- native
373    puts $input "$graph(yunits)" 
374    # format (if implemented someday)
375    puts $input "0" 
376    close $input
377    # initalize arrays
378    set X {}
379    set OBS {}
380    set CALC {}
381    set BKG {}
382    set WGT {}
383    global refhkllist refphaselist refpos
384    set refpos {}
385    set refhkllist {}
386    set refphaselist {}
387    for {set i 1} {$i < 10} {incr i} {
388        set reflns($i) {}
389    }
390    eval [exec $expgui(tcldump) $expnam < histdump$hst.inp]
391    catch {file delete histdump$hst.inp}
392    if {$X == ""} {
393        $box config -title "(Error reading Histogram $hst)"
394        foreach elem [$box element show] {
395           eval $box element config $elem $graph(ElementHideOption)
396        }
397        return
398    }
399    foreach elem [$box element names] {
400        eval $box element config $elem $graph(ElementShowOption)
401    }
402    xvec set $X
403    obsvec set $OBS
404    calcvec set $CALC
405    bckvec set $BKG
406    refposvec set $refpos
407    diffvec set [obsvec - calcvec]
408    set weightlist $WGT
409    if {$graph(chi2)} {
410        wifdvec set $WGT
411        wifdvec set [wifdvec * diffvec]
412        wifdvec set [wifdvec * diffvec]
413        # now do a running sum
414        set sum 0
415        set sumlist {}
416        foreach n [wifdvec range 0 end] {
417            set sum [expr {$sum + $n}]
418            lappend sumlist $sum
419        }
420        wifdvec set $sumlist
421        wifdvec set [wifdvec / [wifdvec length]]
422    }
423    if $graph(backsub) {
424        obsvec set [obsvec - bckvec]
425        calcvec set [calcvec - bckvec]
426    }
427    global obsvec calcvec diffvec
428    set maxdiff  [set diffvec(max)]
429    set cmin [set calcvec(min)]
430    set omin [set obsvec(min)]
431    set cmax [set calcvec(max)]
432    set omax [set obsvec(max)]
433    set expgui(min) [expr {$omin < $cmin ? $omin : $cmin}]
434    set expgui(max) [expr {$omax > $cmax ? $omax : $cmax}]
435    set ymin1 [expr {$cmin - 1.1*$maxdiff}]
436    set ymin2 [expr {$omin - 1.1*$maxdiff}]
437    if {$ymin1 < $ymin2} {
438        diffvec set [diffvec + $ymin1]
439    } {
440        diffvec set [diffvec + $ymin2]
441    }
442   
443    plotdata
444}
445
446proc lblhkl {plot x} {
447    global blt_version expgui tcl_platform tcl_version
448    global refhkllist refphaselist peakinfo refpos
449    # look for peaks within pixelregion pixels or the entire plot range
450    if {$x == "all"} {
451        foreach {xmin xmax} [$plot xaxis limits] {}
452    } else {
453        set xmin [$plot xaxis invtransform [expr {$x - $expgui(pixelregion)}]]
454        set xmax [$plot xaxis invtransform [expr {$x + $expgui(pixelregion)}]]
455    }
456    set peaknums [refposvec search $xmin $xmax]
457    set peaklist {}
458    # create a box, if needed
459    if {$expgui(hklbox)} {
460        catch {
461            toplevel .hkl
462            text .hkl.txt -width 30 -height 10 -wrap none \
463                    -yscrollcommand ".hkl.yscroll set" 
464            scrollbar .hkl.yscroll -command ".hkl.txt yview"
465            grid .hkl.txt -column 0 -row 1 -sticky nsew
466            grid .hkl.yscroll -column 1 -row 1 -sticky ns
467            grid columnconfigure .hkl 0 -weight 1
468            grid rowconfigure .hkl 1 -weight 1
469            wm title .hkl "Liveplot HKL Labels"
470            wm iconname .hkl HKL
471            .hkl.txt insert end "Phase\thkl\tPosition"
472        }
473    }
474    set xcen 0
475    set lbls 0
476    foreach peak $peaknums {
477        # put all hkls, all phases in the box
478        if {$expgui(hklbox)} {
479            catch {
480                .hkl.txt insert end "\n[lindex $refphaselist $peak]"
481                .hkl.txt insert end "\t[lindex $refhkllist $peak]"
482                .hkl.txt insert end "\t[lindex $refpos $peak]"
483                .hkl.txt see end
484            }
485        }
486        # label phases with tick marks
487        if [set peakinfo(flag[lindex $refphaselist $peak])] {
488            set pos [refposvec range $peak $peak]
489            if {$lbls <= 0} {
490                set xcen $pos
491                set peaklist [lindex $refhkllist $peak]
492                set lbls 1
493            } elseif {abs($xcen/$lbls-$pos) <= $expgui(pixelregion)} {
494                set xcen [expr {$xcen + $pos}]
495                lappend peaklist [lindex $refhkllist $peak]
496                incr lbls
497            } else {
498                puthkllbl $plot $peaklist $xcen $lbls 
499                set xcen $pos
500                set peaklist [lindex $refhkllist $peak]
501                set lbls 1
502            }
503        }
504    }
505    puthkllbl $plot $peaklist $xcen $lbls 
506}
507
508proc puthkllbl {plot peaklist xcen lbls} {
509    global blt_version tcl_platform tcl_version expgui
510    if {$peaklist == ""} return
511    set xcen [expr {$xcen / $lbls}]
512    # avoid bug in BLT 2.3 where Inf does not work for text markers
513    if {$blt_version == 2.3} {
514        set ycen [lindex [$plot yaxis limits] 1]
515    } else  {
516        set ycen Inf
517    }
518    # older BLT versions can't rotate text in windows
519    if {$tcl_platform(platform) == "windows" && \
520            ($blt_version <= 2.3 || $blt_version == 8.0)} {
521        regsub -all { } $peaklist "\n" peaklist
522        set mark [$plot marker create text -coords "$xcen $ycen" \
523                -text $peaklist -anchor n -bg "" -name hkl$xcen] 
524    } else {
525        set mark [$plot marker create text -coords "$xcen $ycen" \
526                -rotate 90 -text $peaklist -anchor n -bg "" -name hkl$xcen]
527    }
528    if {$tcl_version >= 8.0} {
529        $plot marker config hkl$xcen -font lblfont
530    }
531    if {$expgui(fadetime) > 0} {
532        catch {
533            after [expr {$expgui(fadetime) * 1000 }] \
534                    "catch \{ $plot marker delete $mark \}"
535        }
536    }
537}
538
539proc delallhkllbl {plot} {
540    catch {
541        eval $plot marker delete [$plot marker names hkl*]
542    }
543}
544
545proc plotdata {} {
546    global expnam hst peakinfo xunits yunits cycle reflns modtime
547    global lasthst graph expgui box
548
549    # is there a new histogram to load?
550    if {$hst != $lasthst} {
551        xvec set {}
552        xvec notify now
553        set cycle -1
554        set modtime 0
555        $box config -title "Please wait: loading histogram $hst"
556        update
557        return
558    }
559    $box config -title "$expnam cycle $cycle Hist $hst"
560    $box xaxis config -title $xunits
561    $box yaxis config -title $yunits
562    setlegend $box $graph(legend)
563    # reconfigure the data
564    $box element configure 3 \
565            -symbol $peakinfo(obssym) -color $graph(color_obs) \
566            -pixels [expr 0.125 * $peakinfo(obssize)]i
567    $box element config 0 -color $graph(color_chi2) 
568    $box element config 1 -color $graph(color_bkg)
569    $box element config 2 -color $graph(color_calc)
570    $box element config 4 -color $graph(color_diff)
571    global program
572    if {$program == "bkgedit"}  {
573        $box element config 12 -color $graph(color_input) \
574                -pixels [expr 0.125 * $peakinfo(inpsize)]i \
575                -symbol $peakinfo(inpsym)
576        $box element config 11 -color $graph(color_fit)
577    }
578    xvec notify now
579    obsvec notify now
580    calcvec notify now
581    bckvec notify now
582    diffvec notify now
583    wifdvec notify now
584    # now deal with peaks
585    for {set i 1} {$i < 10} {incr i} {
586        if {$expgui(autotick)} {
587            set div [expr {( $expgui(max) - $expgui(min) )/40.}]
588            set ymin [expr {$expgui(min) - ($i+1) * $div}]
589            set ymax [expr {$expgui(min) - $i * $div}]
590        } else {
591            set ymin $peakinfo(min$i)
592            set ymax $peakinfo(max$i)
593        }
594        set j 0
595        if [set peakinfo(flag$i)] {
596            foreach X $reflns($i) {
597                incr j
598                catch {
599                    $box marker create line -name peaks${i}_$j 
600                }
601                $box marker config peaks${i}_$j  -under 1 \
602                        -coords "$X $ymin $X $ymax" 
603                catch {
604                    $box marker config peaks${i}_$j \
605                            $graph(MarkerColorOpt) [list $peakinfo(color$i)]
606                    if $peakinfo(dashes$i) {
607                        $box marker config peaks${i}_$j -dashes "5 5"
608                    }
609                }
610            }
611            catch {$box element create phase$i}
612            catch {
613                $box element config phase$i -color $peakinfo(color$i) \
614                        -label $graph(label$i)
615            }
616        } else {
617            eval $box marker delete [$box marker names peaks${i}_*]
618            eval $box element delete [$box element names phase$i]
619        }
620    }
621    # force an update of the plot as BLT may not
622    $box config -title [$box cget -title]
623    update
624}
625
626proc setlegend {box legend} {
627    global blt_version
628    if {$blt_version >= 2.3 && $blt_version < 8.0} {
629        if $legend {
630            $box legend config -hide no
631        } else {
632            $box legend config -hide yes
633        }
634    } else {
635        if $legend {
636            $box legend config -mapped yes
637        } else {
638            $box legend config -mapped no
639        }
640    }
641}
642
643proc minioptionsbox {num} {
644    global blt_version tcl_platform peakinfo expgui
645    set bx .opt$num
646    catch {destroy $bx}
647    toplevel $bx
648    wm iconname $bx "Phase $num options"
649    wm title $bx "Phase $num options"
650
651    set i $num
652    pack [label $bx.0 -text "Phase $i reflns" ] -side top
653    pack [checkbutton $bx.1 -text "Show reflections" \
654            -variable peakinfo(flag$i)] -side top
655    # remove option that does not work
656    if {$blt_version != 8.0 || $tcl_platform(platform) != "windows"} {
657        pack [checkbutton $bx.2 -text "Use dashed line" \
658                -variable peakinfo(dashes$i)] -side top
659    }
660    if !$expgui(autotick) {
661        pack [frame $bx.p$i -bd 2 -relief groove] -side top
662        #       pack [checkbutton $bx.p$i.0 -text "Show phase $i reflns" \
663                #               -variable peakinfo(flag$i)] -side left -anchor w
664        pack [label $bx.p$i.1 -text "  Y min:"] -side left
665        pack [entry $bx.p$i.2 -textvariable peakinfo(min$i) -width 5] \
666                -side left
667        pack [label $bx.p$i.3 -text "  Y max:"] -side left
668        pack [entry $bx.p$i.4 -textvariable peakinfo(max$i) -width 5] \
669                -side left
670    }
671    pack [frame $bx.c$i -bd 2 -relief groove] -side top
672   
673    pack [label $bx.c$i.5 -text " color:"] -side left
674    pack [entry $bx.c$i.6 -textvariable peakinfo(color$i) -width 12] \
675            -side left
676    pack [button $bx.c$i.2 -bg $peakinfo(color$i) -state disabled] -side left
677    pack [button $bx.c$i.1 -text "Color\nmenu" \
678            -command "setcolor $i"] -side left
679
680    pack [frame $bx.l$i -bd 2 -relief groove] -side top
681   
682    pack [label $bx.l$i.1 -text " Phase label:"] -side left
683   
684    pack [entry $bx.l$i.2 -textvariable graph(label$i) -width 20] \
685            -side left
686
687    pack [frame $bx.b] -side top
688    pack [button $bx.b.4 -command "destroy $bx; plotdata" \
689            -text Close ] -side right
690}
691
692proc setcolor {num} {
693    global peakinfo
694    set color [tk_chooseColor -initialcolor $peakinfo(color$num) -title "Choose color"]
695    if {$color == ""} return
696    set peakinfo(color$num) $color
697}
698
699proc makepostscriptout {} {
700    global graph box
701    if !$graph(printout) {
702        set out [open "| $graph(outcmd) >& liveplot.msg" w]
703        catch {
704            puts $out [$box postscript output -landscape 1 \
705                -decorations no -height 7.i -width 9.5i]
706            close $out
707        } msg
708        catch {
709            set out [open liveplot.msg r]
710            if {$msg != ""} {append msg "\n"}
711            append msg [read $out]
712            close $out
713            catch {file delete liveplot.msg}
714        }
715        if {$msg != ""} {
716            tk_dialog .msg "file created" \
717                    "Postscript file processed with command \
718                    $graph(outcmd). Result: $msg" "" 0 OK
719        } else {
720            tk_dialog .msg "file created" \
721                    "Postscript file processed with command \
722                    $graph(outcmd)" "" 0 OK
723        }
724    } else {
725        $box postscript output $graph(outname) -landscape 1 \
726                -decorations no -height 7.i -width 9.5i   
727        tk_dialog .msg "file created" \
728                "Postscript file $graph(outname) created" "" 0 OK
729    }
730}
731
732proc setprintopt {page} {
733    global graph
734    if $graph(printout) { 
735        $page.4.1 config -fg black
736        $page.4.2 config -fg black -state normal
737        $page.6.1 config -fg #888
738        $page.6.2 config -fg #888 -state disabled
739    } else {
740        $page.4.1 config -fg #888
741        $page.4.2 config -fg #888 -state disabled
742        $page.6.1 config -fg black
743        $page.6.2 config -fg black -state normal
744    }
745}
746
747proc setpostscriptout {} {
748    global graph tcl_platform
749    set box .out
750    catch {destroy $box}
751    toplevel $box
752    focus $box
753    wm title $box "Set PS options"
754    pack [frame $box.4] -side top -anchor w -fill x
755    pack [checkbutton $box.4.a -text "Write PostScript files" \
756            -variable graph(printout) -offvalue 0 -onvalue 1 \
757            -command "setprintopt $box"] -side left -anchor w
758    pack [entry $box.4.2 -textvariable graph(outname)] -side right -anchor w
759    pack [label $box.4.1 -text "PostScript file name:"] -side right -anchor w
760    pack [frame $box.6] -side top -anchor w -fill x
761    pack [checkbutton $box.6.a -text "Print PostScript files" \
762            -variable graph(printout) -offvalue 1 -onvalue 0 \
763            -command "setprintopt $box" ] -side left -anchor w
764    pack [entry $box.6.2 -textvariable graph(outcmd)] -side right -anchor w
765    pack [label $box.6.1 -text "Command to print files:"] -side right -anchor w
766
767    pack [button $box.a -text "Close" -command "destroy $box"] -side top
768    if {$tcl_platform(platform) == "windows"} {
769        set graph(printout) 1
770        $box.4.a config -state disabled
771        $box.6.a config -fg #888 -state disabled
772    }
773    setprintopt $box
774}
775
776#-------------------------------------------------------------------------
777# export current plot to Grace
778#-------------------------------------------------------------------------
779if {$tcl_platform(platform) == "unix"} {
780    set graph(GraceFile) /tmp/grace_out.agr
781} else {
782    set graph(GraceFile) C:/graceout.agr
783}
784proc exportgrace {} {
785    global graph box
786    global tcl_platform graph
787    catch {toplevel .export}
788    raise .export
789    eval destroy [grid slaves .export]
790    set col 5
791    grid [label .export.1a -text Title:] -column 1 -row 1
792    set graph(title) [$box cget -title]
793    grid [entry .export.1b -width 60 -textvariable graph(title)] \
794            -column 2 -row 1 -columnspan 4
795    grid [label .export.2a -text Subtitle:] -column 1 -row 2
796    grid [entry .export.2b -width 60 -textvariable graph(subtitle)] \
797            -column 2 -row 2 -columnspan 4
798    grid [label .export.3a -text "File name:"] -column 1 -row 3
799    grid [entry .export.3b -width 60 -textvariable graph(GraceFile)] \
800            -column 2 -row 3 -columnspan 4
801    grid [button .export.help -text Help -bg yellow \
802            -command "MakeWWWHelp liveplot.html grace"] \
803            -column [incr col -1] -row 4
804    grid [button .export.c -text "Close" \
805            -command "set graph(export) 0; destroy .export"] \
806            -column [incr col -1] -row 4
807    if {$tcl_platform(platform) == "unix" && [auto_execok xmgrace] != ""} {
808        grid [button .export.d -text "Export & \nstart grace" \
809            -command "set graph(export) 1; destroy .export"] \
810                -column [incr col -1] -row 4
811    }
812    grid [button .export.e -text "Export" \
813            -command "set graph(export) 2; destroy .export"] \
814            -column [incr col -1] -row 4
815    tkwait window .export
816    if {$graph(export) == 0} return
817    if {[catch {
818        set fp [open $graph(GraceFile) w]
819        puts $fp [output_grace $box $graph(title) $graph(subtitle)]
820        close $fp
821    } errmsg]} {
822        MyMessageBox -parent . -title "Export Error" \
823                -message "An error occured during the export: $errmsg" \
824                -icon error -type Ignore -default ignore
825        return
826    }
827
828    if {$graph(export) == 1} {
829        set err [catch {exec xmgrace $graph(GraceFile) &} errmsg]
830        if $err {
831        MyMessageBox -parent . -title "Grace Error" \
832                -message "An error occured launching grace (xmgrace): $errmsg" \
833                -icon error -type Ignore -default ignore
834        }
835    } else {
836        MyMessageBox -parent . -title "OK" \
837                -message "File $graph(GraceFile) created" \
838                -type OK -default ok
839    }
840}
841#-------------------------------------------------------------------------
842# export current plot as .csv file
843#-------------------------------------------------------------------------
844proc makecsvfile {} {
845    global graph box expnam hst
846    global tcl_platform graph
847    set typelist {
848        {{Comma separated} {.csv}        }
849        {{Text File}       {.txt}        }
850    }
851    set file [tk_getSaveFile -filetypes $typelist \
852            -initialfile ${expnam}_$hst.csv]
853    if {$file == ""} return
854    foreach vec {xvec obsvec calcvec bckvec diffvec wifdvec} \
855            var {X    O      C       B      D       CC     } {
856        set $var {}
857        catch {set $var [$vec range 0 end]}
858    }
859    set fp [open $file w]
860    # get x and y axis limits
861    foreach v {x y} {
862        foreach "${v}min ${v}max" [$graph(blt) ${v}axis limits] {}
863        puts $fp "\"$v axis range [set ${v}min] to [set ${v}max]\""
864        global ${v}units
865        puts $fp "\"$v axis label [set ${v}units]\""
866    }
867    puts $fp {"Columns are X I(obs) I(calc) I(bkg) Obs-Calc cum-chi**2 refpos ref-phase ref-hkl"}
868    global refhkllist refphaselist refpos
869    foreach x $X o $O c $C b $B d $D cc $CC \
870            hkl $refhkllist rphase $refphaselist rp $refpos {
871        # replace commas with spaces
872        regsub -all "," $hkl " " hkl
873        puts $fp ", $x, $o, $c, $b, $d, $cc, $rp, $rphase, [list $hkl],"
874    }
875    close $fp
876}
877
878proc setlblopts {} {
879    global expgui tcl_platform tcl_version
880    set box .out
881    catch {destroy $box}
882    toplevel $box
883    focus $box
884    wm title $box "Set hkl options"
885    pack [frame $box.c] -side top  -anchor w
886    pack [label $box.c.l -text "HKL label\nerase time:"] -side left
887    pack [entry $box.c.e -textvariable expgui(fadetime) -width 8] \
888            -side left
889    pack [label $box.c.l1 -text seconds] -side left
890    pack [frame $box.d] -side top  -anchor w
891    pack [label $box.d.l -text "HKL label size:"] -side left
892    pack [entry $box.d.e -textvariable expgui(lblfontsize) -width 4] \
893            -side left
894    pack [label $box.d.l1 -text pixels] -side left
895    # old versions if tcl/tk don't support the font command
896    if {$tcl_version < 8.0} {
897        $box.d.l config -fg #888
898        $box.d.e config -fg #888 -state disabled
899        $box.d.l1 config -fg #888
900    }
901    pack [frame $box.f] -side top  -anchor w
902    pack [label $box.f.l -text "HKL search region:"] -side left
903    pack [entry $box.f.e -textvariable expgui(pixelregion) -width 3] \
904            -side left
905    pack [label $box.f.l1 -text pixels] -side left
906    pack [frame $box.e] -side top  -anchor w
907    pack [checkbutton $box.e.b -text "Separate window for HKL labels"\
908            -variable expgui(hklbox)] -side left
909    pack [button $box.a -text "Close" -command "destroy $box"] -side top
910}
911
912proc getsymopts {"sym obs"} {
913    global expgui peakinfo
914    set box .out
915    catch {destroy $box}
916    toplevel $box
917    focus $box
918    wm title .out "set $sym symbol"
919    pack [frame $box.d] -side left -anchor n
920    pack [label $box.d.t -text "Symbol type"] -side top
921    set expgui(sym) $peakinfo(${sym}sym) 
922    set expgui(size) $peakinfo(${sym}size) 
923    foreach symbol {square circle diamond triangle plus cross \
924            splus scross} \
925            symbol_name {square circle diamond triangle plus cross \
926            thin-plus thin-cross} {
927        pack [radiobutton $box.d.$symbol \
928                -text $symbol_name -variable expgui(sym) \
929                -value $symbol] -side top -anchor w
930    }
931    pack [frame $box.e] -side left -anchor n -fill y
932    pack [label $box.e.l -text "Symbol Size"] -side top
933    pack [scale $box.e.s -variable expgui(size) \
934            -from .1 -to 3 -resolution 0.05] -side top
935    pack [frame $box.a] -side bottom
936    pack [button $box.a.1 -text "Apply" -command "setsymopts $sym"] -side left
937    pack [button $box.a.2 -text "Close" -command "destroy $box"] -side left
938}
939proc setsymopts {sym} {
940    global peakinfo expgui
941    if {$peakinfo(${sym}sym) != $expgui(sym)} {set peakinfo(${sym}sym) $expgui(sym)}
942    if {$peakinfo(${sym}size) != $expgui(size)} {set peakinfo(${sym}size) $expgui(size)}
943}
944
945# save some of the global options in ~/.gsas_config
946proc SaveOptions {} {
947    global graph expgui peakinfo
948    set fp [open [file join ~ .gsas_config] a]
949    foreach v {printout legend outname outcmd autoraise chi2} {
950        puts $fp "set graph($v) [list $graph($v)]"
951    }
952    foreach v {diff chi2 bkg calc obs input fit} {
953        puts $fp "set graph(color_$v) [list $graph(color_$v)]"
954    }
955    foreach v {font lblfontsize fadetime hklbox pixelregion autotick} {
956        puts $fp "set expgui($v) [list $expgui($v)]"
957    }
958    foreach v {obssym obssize inpsym inpsize} {
959        puts $fp "set peakinfo($v) [list $peakinfo($v)]"
960    }
961    close $fp
962}
963
964proc aboutliveplot {} {
965    global Revision
966    tk_dialog .warn About "
967GSAS\n\
968A. C. Larson and\n R. B. Von Dreele,\n LANSCE, Los Alamos\n\n\
969LIVEPLOT\nB. Toby, NIST\nNot subject to copyright\n\n\
970$Revision\n\
971" {} 0 OK
972}
973
974proc getcycle {} {
975    global expnam
976    set cycle -1
977    catch {
978        set fp [open $expnam.EXP r]
979        set text [read $fp]
980        close $fp
981        regexp {GNLS  RUN.*Total cycles run *([0-9]*) } $text x cycle
982    }
983    return $cycle
984}
985
986proc updateifnew {} {
987    global cycle modtime expnam env tcl_platform graph
988    # has the .EXP file been changed?
989    set newmodtime $modtime
990    catch {set newmodtime [file mtime $expnam.EXP]}
991    if {$newmodtime != $modtime} {
992        # are we in windows and are "locked?" If not, OK to update
993        if {$tcl_platform(platform) == "windows" && [file exists expgui.lck]} {
994            .g config -title "(Experiment directory locked)"
995        } else { 
996            set modtime [file mtime $expnam.EXP]
997            set newcycle [getcycle]
998            if {$newcycle != $cycle} {
999                set cycle $newcycle
1000                readdata .g
1001            }
1002            if {$tcl_platform(platform) == "windows" && $graph(autoraise)} {
1003                # raise does not seem to be global in Windows,
1004                # but this works in Win-95
1005                # nothing seems to work in Win-NT
1006                wm withdraw .
1007                wm deiconify .
1008            } elseif {$graph(autoraise)} {
1009                raise .
1010            }
1011        }
1012    }
1013    # check again in a second
1014    after 1000 updateifnew
1015}
1016
1017proc plotdataupdate {array element action} {
1018    global box peakinfo reflns graph
1019    # parse the element
1020    regexp {([a-z]*)([0-9]*)} $element junk var num
1021    if {$var == "color"} {
1022        if {$peakinfo($element) == ""} return
1023        if [catch {
1024            .opt$num.c$num.2 config -bg $peakinfo($element)
1025        } ] return
1026        set i $num
1027        set j 0
1028        if [set peakinfo(flag$i)] {
1029            catch {
1030                $box element config phase$i -color $peakinfo(color$i) 
1031            } 
1032            foreach X $reflns($i) {
1033                incr j
1034                catch {
1035                    $box marker config peaks${i}_$j \
1036                            $graph(MarkerColorOpt) [list $peakinfo(color$i)]
1037                }
1038            }
1039        }
1040        return
1041    }
1042    waitmsg {Updating}
1043    plotdata
1044    donewaitmsg
1045}
1046proc ShowCumulativeChi2 {} {
1047    global graph box
1048    if $graph(chi2) {
1049        eval $box y2axis config $graph(ElementShowOption)
1050        eval $box element config 0 $graph(ElementShowOption) -label "Chi2"
1051        set cycle [getcycle]
1052        readdata .g
1053    } else {
1054        eval $box element config 0 $graph(ElementHideOption) 
1055        eval $box y2axis config $graph(ElementHideOption) 
1056        $box element config 0 -label ""
1057    }
1058}
1059# evaluate the Chebyshev polynomial with coefficients A at point x
1060# coordinates are rescaled from $xmin=-1 to $xmax=1
1061proc chebeval {A x xmin xmax} {
1062    set xs [expr {-1 + 2 * (1.*$x - $xmin) / (1.*$xmax - 1.*$xmin)}]
1063    set Tpp 0
1064    set Tp 0
1065    set total 0
1066    foreach a $A {
1067        if {$Tpp == $Tp && $Tp == 0} {
1068            set T 1
1069        } elseif {$Tpp == 0} {
1070            set T $xs
1071        } else {       
1072            set T [expr {2. * $xs * $Tp - $Tpp}]
1073        }
1074        set total [expr {$total + $a * $T}]
1075        set Tpp $Tp
1076        set Tp $T
1077    }
1078    return $total
1079}
1080
1081# change the binding of the mouse, based on the selected mode
1082proc bkgEditMode {b} {
1083    global zoomcommand box
1084    # get binding
1085    set bindtag $box
1086    catch {
1087        if {[bind bltZoomGraph] != ""} {
1088            set bindtag bltZoomGraph
1089        }
1090    }
1091    # save the zoom command
1092    if [catch {set zoomcommand}] {
1093        set zoomcommand [bind $bindtag <1>]
1094        .bkg.f.fit1 config -state disabled
1095        .bkg.f.terms config -state disabled
1096    }
1097    if {$b == ""} {
1098        foreach c {1 2 3} {
1099            if {[.bkg.l.b$c cget -relief] == "sunken"} {set b $c}
1100        }
1101    }
1102    foreach c {1 2 3} {
1103        if {$c == $b} {
1104            .bkg.l.b$c config -relief sunken
1105        } else {
1106            .bkg.l.b$c config -relief raised
1107        }
1108    }
1109    # reset previous mode; if in the middle
1110    if {[string trim [bind $box <Motion>]] != ""} {
1111        blt::ResetZoom $box
1112    }
1113    if {$b == 2} {
1114        bind $bindtag <1> "bkgAddPoint %x %y"
1115        .g config -cursor arrow
1116    } elseif {$b == 3} {
1117        bind $bindtag <1> "bkgDelPoint %x %y"
1118        .g config -cursor circle
1119    } else {
1120        bind $bindtag <1> $zoomcommand
1121        .g config -cursor crosshair
1122    }
1123}
1124
1125# plot the background points
1126proc bkgPointPlot {} {
1127    global bkglist termmenu expgui expnam hst tmin tmax
1128    set l {}
1129    set fp [open $expnam.bkg$hst w]
1130    puts $fp "y p h e $hst b ! fixed background points for use in BKGEDIT"
1131    foreach p $bkglist {
1132        puts $fp "i\t$p\t0.0"
1133        append l " $p"
1134    }
1135    if {[llength $bkglist] > 0} {
1136        puts $fp "i\t[expr $tmin*0.99] [lindex [lindex $bkglist 0] 1]\t0.0"
1137        puts $fp "i\t[expr $tmax*1.01] [lindex [lindex $bkglist end] 1]\t0.0"
1138    }
1139    close $fp
1140    .g element config 12 -data $l
1141    if {[set l [llength $bkglist]] > 3} {
1142        .bkg.f.fit1 config -state normal
1143        .bkg.f.terms config -state normal
1144        $termmenu delete 0 end
1145        set imax {}
1146        for {set i 2} {$i <= $l/1.5} {incr i 2} {
1147            $termmenu insert end radiobutton -label $i \
1148                    -variable expgui(FitOrder) -command "BkgFillTermBoxes nosave"
1149            set imax $i
1150        }
1151        if {$imax < $expgui(FitOrder)} {set expgui(FitOrder) $imax}
1152    } else {
1153        .bkg.f.fit1 config -state disabled
1154        .bkg.f.terms config -state disabled
1155        set expgui(FitOrder) 2
1156    }
1157}
1158
1159# add a bkg point at screen coordinates x,y
1160proc bkgAddPoint {x y} {
1161    global bkglist tmin tmax
1162    set xy [.g invtransform $x $y]
1163    set x [lindex $xy 0]
1164    if {$x < $tmin} {set x $tmin}
1165    if {$x > $tmax} {set x $tmax}
1166    lappend bkglist [list $x [lindex $xy 1]]
1167    set bkglist [lsort -real -index 0  $bkglist]
1168    bkgFillPoints
1169    bkgPointPlot
1170}
1171
1172# delete the bkg point closest to screen coordinates x,y
1173proc bkgDelPoint {x y} {
1174    global bkglist
1175    set closest {}
1176    set dist2 {}
1177    set i -1
1178    foreach p $bkglist {
1179        incr i
1180        set sxy [eval .g transform $p]
1181        if {$closest == ""} {
1182            set closest $i
1183            set dist2 0
1184            foreach v1 $sxy v2 "$x $y" {
1185                set dist2 [expr {$dist2 + ($v1 - $v2)*($v1 - $v2)}]
1186            }
1187        } else {
1188            set d2 0
1189            foreach v1 $sxy v2 "$x $y" {
1190                set d2 [expr {$d2 + ($v1 - $v2)*($v1 - $v2)}]
1191            }
1192            if {$d2 < $dist2} {
1193                set closest $i
1194                set dist2 $d2
1195            }           
1196        }
1197    }
1198    set bkglist [lreplace $bkglist $closest $closest]
1199    bkgPointPlot
1200    bkgFillPoints
1201}
1202
1203# initialize the background plot
1204proc bkghstInit {} {
1205    global bkglist tmin tmax hst expnam termlist expgui
1206    set tmin [histinfo $hst tmin]
1207    set tmax [histinfo $hst tmax]
1208    if {[catch {expr $tmin}] || [catch {expr $tmax}]} {
1209        tk_dialog .err "MIN/MAX Error" "Error -- Unable read tmin or tmax (has POWPREF been run?" \
1210                error 0 Quit
1211        destroy .
1212    }
1213
1214    set bkglist {}
1215    if [file exists $expnam.bkg$hst] {
1216        catch {
1217            set fp [open $expnam.bkg$hst r]
1218            gets $fp line
1219            while {[gets $fp line]>=0} {
1220                set x [lindex $line 1]
1221                set y [lindex $line 2]
1222                if {$x >= $tmin && $x <= $tmax} {
1223                    lappend bkglist [list $x $y]
1224                }
1225            }
1226        }
1227        close $fp
1228    }
1229
1230    bkgEditMode 1
1231    bkgPointPlot
1232    bkgFillPoints
1233    set termlist ""
1234    set expgui(FitOrder) 2
1235    BkgFillTermBoxes nosave
1236}
1237
1238proc bkgFit {button} {
1239    global bkglist termlist expgui
1240    # keep the button down while working
1241    $button config -relief sunken
1242    update
1243    # make a list of X & Y values
1244    foreach p $bkglist {
1245        lappend S 1.
1246        foreach v $p var {X Y} {
1247            lappend $var $v
1248        }
1249    }
1250
1251    # perform the Fit
1252    set termlist [FitBkgFunc $X $Y $expgui(FitOrder) $expgui(FitFunction) \
1253            $expgui(RadiiList)]
1254    # set the bkg terms in the edit boxes & update the plot
1255    BkgFillTermBoxes
1256    $button config -relief raised
1257}
1258
1259# put the Background coefficients into edit widgets
1260proc BkgFillTermBoxes {"save {}"} {
1261    global termlist expgui
1262    global bkgeditbox
1263    catch {destroy .bkg.canvas.fr}
1264    set top [frame .bkg.canvas.fr]
1265    .bkg.canvas create window 0 0 -anchor nw -window $top
1266    # delete trace on bkgeditbox
1267    foreach v [ trace vinfo bkgeditbox] {
1268        eval trace vdelete bkgeditbox $v
1269    }
1270
1271    .bkg.cw config -state normal
1272    set k 0
1273    if {$expgui(FitFunction) == 3} {
1274        # o is number of refinable terms
1275        set o [expr {2 + ($expgui(FitOrder) - 2)/2}]
1276        grid [label $top.lbl -text terms] -col $k -row 1
1277        if {$expgui(FitOrder) >= 4} {
1278            grid [label $top.rlbl -text radii] -col $k -row 2
1279        }
1280        incr k
1281        set width 7
1282    } else {
1283        set o $expgui(FitOrder)
1284        set width 10
1285    }
1286    for {set i 0} {$i < $o} {incr i} {
1287        if {$i >= [llength $termlist]} {lappend termlist 0.}
1288        set bkgeditbox($i) [lindex $termlist $i]
1289        grid [frame $top.$i -relief groove -bd 3] -col $k -row 1
1290        grid [label $top.$i.l -text "[expr 1+$i]"] -col 1 -row 1
1291        grid [entry $top.$i.e -textvariable bkgeditbox($i) -width $width] \
1292                -col 2 -row 1
1293        if {$expgui(FitFunction) == 3 && $i > 1} {
1294            set j [expr $i-2]
1295            if {$j >= [llength $expgui(RadiiList)]} {lappend expgui(RadiiList) 0.}
1296            set bkgeditbox(r$j) [lindex $expgui(RadiiList) $j]
1297            if {$bkgeditbox(r$j) == 0} {
1298                set bkgeditbox(r$j) ??
1299            }
1300            grid [frame $top.r$j -relief groove -bd 3] \
1301                    -col [expr $k-2] -row 2
1302            grid [label $top.r$j.l -text "[expr -1+$i]"] -col 1 -row 1
1303            grid [entry $top.r$j.e -textvariable bkgeditbox(r$j) -width $width] \
1304                    -col 2 -row 1       
1305        }
1306        incr k
1307    }
1308    trace variable bkgeditbox w "BkgRecalcPlot $top" 
1309    BkgRecalcPlot $top x x x
1310    update idletasks
1311    set sizes [grid bbox $top]
1312    .bkg.canvas config -scrollregion $sizes -height [lindex $sizes 3]
1313    # inhibit the save button, if requested
1314    if {$save == "nosave"} {
1315        .bkg.cw config -state disabled
1316        .g element configure 11 -xdata {} -ydata {}
1317        update
1318    }
1319}
1320
1321# respond to edits made to background terms
1322proc BkgRecalcPlot {top var i mode} {
1323    global bkgeditbox termlist expgui expgui(FitOrder)
1324
1325    set good 1
1326
1327    if {$expgui(FitFunction) == 3} {
1328        set expgui(RadiiList) {}
1329        for {set j 0} {$j < ($expgui(FitOrder) - 2)/2} {incr j} {
1330            lappend expgui(RadiiList) $bkgeditbox(r$j)
1331            if {[catch {expr $bkgeditbox(r$j)}]} {
1332                $top.r$j.e config -fg red
1333                set good 0
1334            } elseif {$bkgeditbox(r$j) == 0} {
1335                $top.r$j.e config -fg red
1336                set good 0
1337            } else {
1338                $top.r$j.e config -fg black
1339            }
1340        }
1341        set o [expr {2 + ($expgui(FitOrder) - 2)/2}]
1342    } else {
1343        set o $expgui(FitOrder)
1344    }
1345    set termlist {}
1346    for {set j 0} {$j < $o} {incr j} {
1347        lappend termlist $bkgeditbox($j)
1348        if {[catch {expr $bkgeditbox($j)}]} {
1349            $top.$j.e config -fg red
1350            set good 0
1351        } else {
1352            $top.$j.e config -fg black
1353        }
1354    }
1355
1356    # disable fit for invalid values
1357    if {$good} {
1358        .bkg.cw config -state normal
1359        .bkg.f.fit1 config -state normal
1360        # plot it
1361        set calcb [BkgEval $termlist $expgui(FitFunction) \
1362                [xvec range 0 end] $expgui(RadiiList)]
1363        .g element configure 11 -xdata xvec -ydata $calcb
1364        update
1365    } else {
1366        .bkg.cw config -state disabled
1367        .bkg.f.fit1 config -state disabled
1368        .g element configure 11 -xdata {} -ydata {}
1369        update
1370    }
1371}
1372
1373# put the bkg points into edit widgets
1374proc bkgFillPoints {} {
1375    global bkglist tmin tmax bkgedit
1376    # delete trace on bkgedit
1377    foreach v [ trace vinfo bkgedit] {
1378        eval trace vdelete bkgedit $v
1379    }
1380    catch {destroy .bkg.bc.fr}
1381    set top [frame .bkg.bc.fr]
1382    .bkg.bc create window 0 0 -anchor nw -window $top
1383    if {[llength $bkglist] == 0} {
1384        grid [label $top.0 -text "(no points defined)"] -col 1 -row 1
1385    } else {
1386        set i -1
1387        foreach p $bkglist {
1388            incr i
1389            grid [frame $top.$i -relief groove -bd 3] -col $i -row 1
1390            grid [label $top.$i.l -text "[expr 1+$i]"] -col 1 -rowspan 2 -row 1
1391            grid [entry $top.$i.ex -textvariable bkgedit(x$i) -width 13] \
1392                    -col 2 -row 1
1393            grid [entry $top.$i.ey -textvariable bkgedit(y$i) -width 13] \
1394                    -col 2 -row 2
1395            foreach val $p var {x y} {
1396                set bkgedit(${var}$i) $val
1397            }
1398        }
1399        trace variable bkgedit w "BkgRecalcBkg $top" 
1400    }
1401    update idletasks
1402    set sizes [grid bbox $top]
1403    .bkg.bc config -scrollregion $sizes -height [lindex $sizes 3]
1404}
1405
1406# respond to edits made to bkg points
1407proc BkgRecalcBkg {top var i mode} {
1408    global bkgedit bkglist tmin tmax
1409    regexp {(.)([0-9]*)} $i junk var num
1410    if [catch {expr {$bkgedit($i)}}] {
1411        $top.$num.e$var config -fg red
1412    } else {
1413        $top.$num.e$var config -fg black
1414        set p [lindex $bkglist $num]
1415        if {$var == "x"} {
1416            set x $bkgedit($i)
1417            if {$x < $tmin} {set x $tmin}
1418            if {$x > $tmax} {set x $tmax}
1419            set bkglist [lreplace $bkglist $num $num \
1420                    [list $x [lindex $p 1]]]
1421        } else {
1422            set bkglist [lreplace $bkglist $num $num \
1423                    [list [lindex $p 0] $bkgedit($i)]]
1424        }
1425    }
1426        bkgPointPlot
1427}
1428
1429# convert x values to Q
1430proc toQ {xlist hst} {
1431    global expmap
1432    if {[string range $expmap(htype_$hst) 2 2] == "T"} {
1433        return [toftoQ $xlist $hst]
1434    } elseif {[string range $expmap(htype_$hst) 2 2] == "C"} {
1435        return [tttoQ $xlist $hst]
1436    } elseif {[string range $expmap(htype_$hst) 2 2] == "E"} {
1437        return [engtoQ $xlist $hst]
1438    } else {
1439        return {}
1440    }
1441}
1442# convert tof to Q
1443proc toftoQ {toflist hst} {
1444    set difc [expr {[histinfo $hst difc]/1000.}]
1445    set difc2 [expr {$difc*$difc}]
1446    set difa [expr {[histinfo $hst difa]/1000.}]
1447    set zero [expr {[histinfo $hst zero]/1000.}]
1448    set 2pi [expr {4.*acos(0.)}]
1449    set ans {}
1450    foreach tof $toflist {
1451        if {$tof == 0.} {
1452            lappend ans 99999.
1453        } elseif {$tof == 1000.} {
1454            lappend ans 0.
1455        } else {
1456            set td [expr {$tof-$zero}]
1457            lappend ans [expr {$2pi * \
1458                    ($difc2*$difc+2.0*$difa*$td)/($td*($difc2+$difa*$td))}]
1459        }
1460    }
1461    return $ans
1462}
1463
1464# convert two-theta to Q
1465proc tttoQ {twotheta hst} {
1466    set lamo2 [expr {0.5 * [histinfo $hst lam1]}]
1467    set zero [expr [histinfo $hst zero]/100.]
1468    set ans {}
1469    set cnv [expr {acos(0.)/180.}]
1470    set 2pi [expr {4.*acos(0.)}]
1471    foreach tt $twotheta {
1472        if {$tt == 0.} {
1473            lappend ans 0.
1474        } elseif {$tt == 1000.} {
1475            lappend ans 1000.
1476        } else {
1477            lappend ans [expr {$2pi * sin($cnv*($tt-$zero)) / $lamo2}]
1478        }
1479    }
1480    return $ans
1481}
1482# convert energy (edx-ray) to Q
1483# (note that this ignores the zero correction)
1484proc engtoQ {eng hst} {
1485    set lam [histinfo $hst lam1]
1486    set zero [histinfo $hst zero]
1487    set ans {}
1488    set v [expr {12.398/(2.0*[sind[expr ($lam/2.0)]])}]
1489    set 2pi [expr {4.*acos(0.)}]
1490    foreach e $eng {
1491        if {$e == 0.} {
1492            lappend ans 0.
1493        } elseif {$e == 1000.} {
1494            lappend ans 1000.
1495        } else {
1496            lappend ans [expr {$2pi * $e / $v}]
1497        }
1498    }
1499    return $ans
1500}
1501
1502proc BkgEval {terms num tlist "rlist {}"} {
1503    global expmap hst
1504    if {$num == 1} {
1505        global tmin tmax
1506        foreach x $tlist {
1507            lappend blist [chebeval $terms $x $tmin $tmax]
1508        }
1509        return $blist
1510    } elseif {$num == 2} {
1511        set ts 1
1512        if {[string range $expmap(htype_$hst) 2 2] == "T"} {
1513            catch {
1514                set line [histinfo $hst ITYP]
1515                set ts [expr 180./ [lindex $line 2]]
1516            }
1517        }
1518        foreach tof $tlist {
1519            set tofm [expr {$tof * $ts}]
1520            set bkg 0
1521            set i -1
1522            foreach t $terms {
1523                incr i
1524                set bkg [expr {$bkg + $t * cos($i * $tofm * 3.14159/180.)}]
1525            }
1526            lappend blist $bkg
1527        }
1528        return $blist
1529    } elseif {$num == 3} {
1530        set Qlist [toQ $tlist $hst]
1531        foreach Q $Qlist tofm $tlist {
1532            set i 0
1533            set j -1
1534            foreach t $terms {
1535                incr i
1536                if {$i == 1} {
1537                    set bkg $t
1538                } elseif {$i == 2} {
1539                    set bkg [expr {$bkg + $tofm * $t}]
1540                } else {
1541                    incr j
1542                    set r [lindex $rlist $j]
1543                    set QR [expr {$Q * $r}]
1544                    set bkg [expr {$bkg + $t * sin($QR)/$QR}]
1545                }
1546            }
1547            lappend blist $bkg
1548        }
1549        return $blist
1550    } elseif {$num == 4} {
1551        set Qlist [toQ $tlist $hst]
1552        foreach Q $Qlist {
1553            set i -1
1554            set QT 1
1555            foreach t $terms {
1556                incr i
1557                if {$i == 0} {
1558                    set bkg $t
1559                } else {
1560                    set QT [expr {$QT * $Q * $Q / $i}]
1561                    set bkg [expr {$bkg + $t * $QT}]
1562                }
1563            }
1564            lappend blist $bkg
1565        }
1566        return $blist
1567    } elseif {$num == 5} {
1568        set Qlist [toQ $tlist $hst]
1569        foreach Q $Qlist {
1570            set i -1
1571            set QT 1
1572            foreach t $terms {
1573                incr i
1574                if {$i == 0} {
1575                    set bkg $t
1576                } else {
1577                    set QT [expr {$QT * $i /($Q * $Q)}]
1578                    set bkg [expr {$bkg + $t * $QT}]
1579                }
1580            }
1581            lappend blist $bkg
1582        }
1583        return $blist
1584    } elseif {$num == 6} {
1585        set Qlist [toQ $tlist $hst]
1586        foreach Q $Qlist {
1587            set i 0
1588            set QT 1
1589            foreach t $terms {
1590                incr i
1591                if {$i == 1} {
1592                    set bkg $t
1593                } elseif {$i % 2} {
1594                    # odd
1595                    set QT1 [expr {1./$QT}]
1596                    set bkg [expr {$bkg + $t * $QT1}]
1597                } else {
1598                    # even
1599                    set QT [expr {2*$QT*$Q*$Q/$i}]
1600                    set QT1 $QT
1601                    set bkg [expr {$bkg + $t * $QT1}]
1602                }
1603            }
1604            lappend blist $bkg     
1605        }
1606        return $blist
1607    }
1608}
1609
1610proc backderivcal {nterms num tof "rlist {}"} {
1611    global expmap hst
1612    if {$num == 1} {
1613        global tmin tmax
1614        # rescale x
1615        set xs [expr {-1 + 2 * (1.*$tof - $tmin) / (1.*$tmax - 1.*$tmin)}]
1616        # compute the Chebyschev term Tn(xs)
1617        set deriv {}
1618        set Tpp 0
1619        set Tp 0
1620        for {set i 0} {$i < $nterms} {incr i} {
1621            if {$Tpp == $Tp && $Tp == 0} {
1622                set T 1
1623            } elseif {$Tpp == 0} {
1624                set T $xs
1625            } else {
1626                set T [expr {2. * $xs * $Tp - $Tpp}]
1627            }
1628            lappend deriv $T
1629            set Tpp $Tp
1630            set Tp $T
1631        }
1632        return $deriv
1633    } elseif {$num == 2} {
1634        set ts 1
1635        if {[string range $expmap(htype_$hst) 2 2] == "T"} {
1636            catch {
1637                set line [histinfo $hst ITYP]
1638                set ts [expr 180./ [lindex $line 2]]
1639            }
1640            set tofm [expr {$tof * $ts}]
1641        } else {
1642            set tofm $tof
1643        }
1644        set deriv {}
1645        for {set i 0} {$i < $nterms} {incr i} {
1646            lappend deriv [expr {cos($i * $tofm * 3.14159/180.)}]
1647        }
1648        return $deriv
1649    } elseif {$num == 3} {
1650        set Q [toQ $tof $hst]
1651        set j -1
1652        #set n [expr {2 + ($nterms - 2)/2}]
1653        for {set i 1} {$i <= $nterms} {incr i} {
1654            if {$i == 1} {
1655                set deriv 1
1656            } elseif {$i == 2} {
1657                lappend deriv $tof
1658            } else {
1659                incr j
1660                set r [lindex $rlist $j]
1661                set QR [expr {$Q * $r}]
1662                lappend deriv [expr {sin($QR)/$QR}]
1663            }
1664        }
1665        return $deriv
1666    } elseif {$num == 4} {
1667        set Q [toQ $tof $hst]
1668        set QT 1
1669        for {set i 0} {$i < $nterms} {incr i} {
1670            if {$i == 0} {
1671                set deriv 1
1672            } else {
1673                lappend deriv [set QT [expr {$QT * $Q * $Q / $i}]]
1674            }
1675        }
1676        return $deriv
1677    } elseif {$num == 5} {
1678        set Q [toQ $tof $hst]
1679        set QT 1
1680        for {set i 0} {$i < $nterms} {incr i} {
1681            if {$i == 0} {
1682                set deriv 1
1683            } else {
1684                lappend deriv [set QT [expr {$QT * $i /($Q * $Q)}]]
1685            }
1686        }
1687        return $deriv
1688    } elseif {$num == 6} {
1689        set Q [toQ $tof $hst]
1690        set QT 1
1691        for {set i 1} {$i <= $nterms} {incr i} {
1692            if {$i == 1} {
1693                set deriv 1
1694            } elseif {$i % 2} {
1695                # odd
1696                lappend deriv [set QT1 [expr {1./$QT}]]
1697            } else {
1698                # even
1699                set QT [expr {2*$QT*$Q*$Q/$i}]
1700                lappend deriv [set QT1 $QT]
1701            }
1702        }
1703        return $deriv
1704    }
1705}
1706
1707# evaluate the best-fit background terms to fit GSAS background functions 1-6
1708# to a set of X and Y values.
1709# num is the function number,
1710# order is the # of terms
1711# rlist is used only for function type 3; there must be (order-2)/2 values
1712proc FitBkgFunc {X Y order num "rlist {}"} {
1713    if {$num == 3} {
1714        set o [expr {2 + ($order - 2)/2}]
1715    } else {
1716        set o $order
1717    }
1718    # zero the matrix and vector
1719    for {set j 0} {$j < $o} {incr j} {
1720        set sum($j) 0.
1721        for {set i 0} {$i <= $j} {incr i} {
1722            set sum(${i}_$j) 0.
1723        }
1724    }
1725#global octave
1726#set octave {}
1727#append octave {des = [}
1728    foreach y $Y x $X {
1729        # compute derivatives at point x
1730        set derivlist [backderivcal $o $num $x $rlist]
1731#append octave " $derivlist ;\n"
1732        # compute matrix elements
1733        for {set j 0} {$j < $o} {incr j} {
1734            set Tj [lindex $derivlist $j]
1735            # weighted
1736            # set sum($j) [expr {$sum($j) + $y * $Tj / ($sigma*$sigma)}]
1737            set sum($j) [expr {$sum($j) + $y * $Tj}]
1738            for {set i 0} {$i <= $j} {incr i} {
1739                set Ti [lindex $derivlist $i]
1740                # weighted
1741                # set sum(${i}_$j) [expr {$sum(${i}_$j) + $Ti * $Tj / ($sigma * $sigma)}]
1742                set sum(${i}_$j) [expr {$sum(${i}_$j) + $Ti * $Tj}]
1743            }
1744        }
1745    }
1746    # populate the matrix & vector in La format
1747    lappend V 2 $o 0
1748    lappend A 2 $o $o
1749    for {set i 0} {$i < $o} {incr i} {
1750        lappend V $sum($i)
1751        for {set j 0} {$j < $o} {incr j} {
1752            if {$j < $i} {
1753                lappend A $sum(${j}_$i)
1754            } else {
1755                lappend A $sum(${i}_$j)
1756            }
1757        }
1758    }
1759    set termlist {}
1760    if {[catch {
1761        set termlist [lrange [La::msolve $A $V] 3 end]
1762    }]} {
1763        tk_dialog .singlar "Singular Matrix" \
1764            "Unable to fit function: singular matrix. Too many terms or something else is wrong." ""\
1765            0 OK
1766    }
1767    return $termlist
1768}
1769
1770# save the Chebyshev terms in the .EXP file
1771proc bkgSave {} {
1772    global hst termlist expgui Revision expmap expnam
1773    histinfo $hst backtype set $expgui(FitFunction)
1774    # stick the r values into the list
1775    if {$expgui(FitFunction) == 3} {
1776        set t [lrange $termlist 0 1]
1777        foreach a [lrange $termlist 2 end] b $expgui(RadiiList) {lappend t $a $b}
1778    } else {
1779        set t $termlist
1780    }
1781    histinfo $hst backterms set [llength $t]
1782    set num 0
1783    foreach v $t {
1784        set var "bterm[incr num]"
1785        histinfo $hst $var set $v
1786    }
1787    histinfo $hst bref set 0
1788    # add a history record
1789    exphistory add " BKGEDIT [lindex $Revision 1] [lindex $expmap(Revision) 1] -- [clock format [clock seconds]]"
1790    # now save the file
1791    expwrite $expnam.EXP
1792}
1793
1794#-------------------------------------------------------------------------
1795# manual zoom option
1796proc BLTmanualZoom {} {
1797    global graph
1798    catch {toplevel .zoom}
1799    eval destroy [grid slaves .zoom]
1800    raise .zoom
1801    wm title .zoom {Manual Scaling}
1802    grid [label .zoom.l1 -text minimum] -row 1 -column 2 
1803    grid [label .zoom.l2 -text maximum] -row 1 -column 3 
1804    grid [label .zoom.l3 -text x] -row 2 -column 1 
1805    grid [label .zoom.l4 -text y] -row 3 -column 1 
1806    grid [entry .zoom.xmin -textvariable graph(xmin) -width 10] -row 2 -column 2 
1807    grid [entry .zoom.xmax -textvariable graph(xmax) -width 10] -row 2 -column 3 
1808    grid [entry .zoom.ymin -textvariable graph(ymin) -width 10] -row 3 -column 2 
1809    grid [entry .zoom.ymax -textvariable graph(ymax) -width 10] -row 3 -column 3 
1810    grid [frame .zoom.b] -row 4 -column 1 -columnspan 3
1811    grid [button .zoom.b.1 -text "Set Scaling" \
1812             -command "SetManualZoom set"]  -row 4 -column 1 -columnspan 2
1813    grid [button .zoom.b.2 -text Reset \
1814            -command "SetManualZoom clear"] -row 4 -column 3
1815    grid [button .zoom.b.3 -text Close -command "destroy .zoom"] -row 4 -column 4 
1816    grid rowconfigure .zoom 1 -weight 1 -pad 5
1817    grid rowconfigure .zoom 2 -weight 1 -pad 5
1818    grid rowconfigure .zoom 3 -weight 1 -pad 5
1819    grid rowconfigure .zoom 4 -weight 0 -pad 5
1820    grid columnconfigure .zoom 1 -weight 1 -pad 20
1821    grid columnconfigure .zoom 1 -weight 1 
1822    grid columnconfigure .zoom 3 -weight 1 -pad 10
1823    foreach item {min min max max} \
1824            format {3   2   3   2} \
1825            axis   {x   y   x   y} {
1826        set val [$graph(blt) ${axis}axis cget -${item}]
1827        set graph(${axis}${item}) {(auto)}
1828        catch {set graph(${axis}${item}) [format %.${format}f $val]}
1829    }
1830    bind .zoom <Return> "SetManualZoom set"
1831}
1832
1833proc SetManualZoom {mode} {
1834    global graph
1835    if {$mode == "clear"} {
1836        foreach item {xmin ymin xmax ymax} {
1837            set graph($item) {(auto)}
1838        }
1839    }
1840    foreach item {xmin ymin xmax ymax} {
1841        if {[catch {expr $graph($item)}]} {
1842            set $item ""
1843        } else {
1844            set $item $graph($item)
1845        }
1846    }
1847    # reset the zoomstack
1848    catch {Blt_ZoomStack $graph(blt)}
1849    catch {$graph(blt) xaxis config -min $xmin -max $xmax}
1850    catch {$graph(blt) yaxis config -min $ymin -max $ymax}
1851    global program
1852    if {$program == "bkgedit"} {bkgEditMode ""}
1853}
1854
1855# define a binding to show the cursor location
1856proc ToggleLiveCursor {} {
1857    global box graph
1858    if {[bind $box <Any-Motion>] == ""} {
1859        .a.options.menu entryconfig $graph(CursorLabel) -label "Hide Cursor Position"
1860        pack [frame .bot -bd 2 -relief sunken] -side bottom -fill x
1861        pack [label .bot.val1 -textvariable graph(position)] -side left
1862        pack [button .bot.close -command ToggleLiveCursor -text "Close cursor display"] -side right
1863        bind $box <Any-Motion> {FormatLiveCursor %x %y}
1864    } else {
1865        .a.options.menu entryconfig $graph(CursorLabel) -label "Show Cursor Position"
1866        destroy .bot
1867        bind $box <Any-Motion> {}
1868    }
1869}
1870proc FormatLiveCursor {x y} {
1871    global graph
1872    set graph(position) \
1873            "x=[format %.3f [$graph(blt) xaxis invtransform $x]] y=[format %.3f [$graph(blt) yaxis invtransform $y]]"
1874}
1875#-------------------------------------------------------------------------
1876
1877
1878# override options with locally defined values
1879if {[catch {
1880    foreach file [list \
1881                      [file join $expgui(scriptdir) localconfig] \
1882                      [file join ~ .gsas_config]] {
1883        if [file exists $file] {source $file}
1884    }
1885} errmsg]} {
1886    set msg "Error reading file $file (aka [file nativename $file]): $errmsg"
1887    MyMessageBox -parent . -title "Customize warning" \
1888        -message $msg -icon warning -type Ignore -default ignore \
1889        -helplink "expguierr.html Customizewarning"
1890}
1891SetTkDefaultOptions $expgui(font)
1892
1893if [file executable [file join $expgui(gsasexe) $expgui(tcldump)]] {
1894    set expgui(tcldump) [file join $expgui(gsasexe) $expgui(tcldump)]
1895} else {
1896    set expgui(tcldump) {}
1897}
1898
1899# vectors
1900if [catch {
1901    foreach vec {xvec obsvec calcvec bckvec diffvec refposvec wifdvec} {
1902        vector $vec
1903        $vec notify never
1904    }
1905} errmsg] {
1906    MyMessageBox -parent . -title "BLT Error" \
1907            -message "BLT Setup Error: could not define vectors \
1908(msg: $errmsg). \
1909$program cannot be run without vectors." \
1910            -helplink "expgui.html blt" \
1911            -icon error -type Skip -default skip
1912    exit
1913}
1914
1915# create the graph
1916if [catch {
1917    set box [graph .g -plotbackground white]
1918    set graph(blt) $box
1919} errmsg] {
1920    MyMessageBox -parent . -title "BLT Error" \
1921            -message "BLT Setup Error: could not create a graph \
1922(error msg: $errmsg). \
1923There is a problem with the setup of BLT on your system. \
1924See the expgui.html file for more info." \
1925            -helplink "expgui.html blt" \
1926            -icon warning -type Exit -default "exit" 
1927    exit
1928}
1929if [catch {
1930    Blt_ZoomStack $box
1931} errmsg] {
1932    MyMessageBox -parent . -title "BLT Error" \
1933            -message "BLT Setup Error: could not access a Blt_ routine \
1934(msg: $errmsg). \
1935The pkgIndex.tcl is probably not loading bltGraph.tcl.
1936See the expgui.html file for more info." \
1937        -helplink "expgui.html blt" \
1938        -icon warning -type {"Limp Ahead"} -default "limp Ahead" 
1939}
1940# modify zoom so that y2axis is not zoomed in for blt2.4u+
1941catch {
1942    regsub -all y2axis [info body blt::PushZoom] " " b1
1943    proc blt::PushZoom {graph} $b1
1944}
1945
1946$box element create 0 -xdata xvec -ydata wifdvec -color $graph(color_chi2) \
1947        -line 3 -symbol none -label "Chi2" -mapy y2
1948$box element create 1 -label bckgr -symbol none 
1949$box element config 1 -xdata xvec -ydata bckvec -color $graph(color_bkg)
1950$box element create 3 -color $graph(color_obs) -linewidth 0 -label Obs \
1951        -symbol $peakinfo(obssym) \
1952        -pixels [expr 0.125 * $peakinfo(obssize)]i
1953$box element create 2 -label Calc -color $graph(color_calc) -symbol none 
1954$box element create 4 -label diff -color $graph(color_diff) -symbol none 
1955
1956if {$program == "liveplot"} {
1957    $box y2axis config -title {Cumulative Chi Squared}
1958    catch {$box y2axis config -min 0}
1959} elseif {$program == "bkgedit"}  {
1960    eval $box element config 0 $graph(ElementHideOption) 
1961    eval $box y2axis config $graph(ElementHideOption) 
1962    $box element config 0 -label ""
1963    eval $box element config 1 $graph(ElementHideOption) 
1964    $box element config 1 -label ""
1965    eval $box element config 4 $graph(ElementHideOption) 
1966    $box element config 4 -label ""
1967    $box element create 11
1968    $box element create 12
1969    $box element configure 12  -color $graph(color_input) \
1970            -pixels [expr 0.125 * $peakinfo(inpsize)]i \
1971            -line 0 -symbol $peakinfo(inpsym) -label "bkg pts"
1972    $box element configure 11 -color $graph(color_fit) \
1973            -symbol none -label "bkg fit" -dashes 5 -line 2
1974    $box element show "3 2 11 12"
1975}
1976$box element config 3 -xdata xvec -ydata obsvec
1977$box element config 2 -xdata xvec -ydata calcvec
1978$box element config 4 -xdata xvec -ydata diffvec
1979
1980if {$expgui(tcldump) != ""} {
1981    bind . <Key-h> "lblhkl $box %x"
1982    bind . <Key-H> "lblhkl $box %x"
1983    bind . <Key-a> "lblhkl $box all"
1984    bind . <Key-A> "lblhkl $box all"
1985    bind . <Key-d> "delallhkllbl $box"
1986    bind . <Key-D> "delallhkllbl $box"
1987    if {[bind bltZoomGraph] != ""} {
1988        bind bltZoomGraph <Shift-Button-1> "lblhkl $box %x"
1989        bind bltZoomGraph <Shift-Button-3> "delallhkllbl %W"
1990    } else {
1991        bind $box <Shift-Button-1> "lblhkl $box %x"
1992        bind $box <Shift-Button-3> "delallhkllbl %W"
1993    }
1994} else {
1995    $box element config 1 -label ""
1996    eval $box element config 4 $graph(ElementHideOption) 
1997}
1998bind . <Key-z> {BLTmanualZoom}
1999bind . <Key-Z> {BLTmanualZoom}
2000
2001$box yaxis config -title {} 
2002setlegend $box $graph(legend)
2003
2004frame .a -bd 3 -relief groove
2005pack [menubutton .a.file -text File -underline 0 -menu .a.file.menu] -side left
2006menu .a.file.menu
2007.a.file.menu add cascade -label Tickmarks -menu .a.file.menu.tick
2008menu .a.file.menu.tick
2009.a.file.menu add cascade -label Histogram -menu .a.file.menu.hist -state disabled
2010.a.file.menu add command -label "Update Plot" \
2011        -command {set cycle [getcycle];readdata .g}
2012.a.file.menu add cascade -label "Export plot" -menu .a.file.menu.export
2013menu .a.file.menu.export
2014.a.file.menu.export add command -label "to PostScript" \
2015        -command makepostscriptout
2016if {$blt_version > 2.3 && $blt_version != 8.0} {
2017    source [file join $expgui(scriptdir) graceexport.tcl]
2018    .a.file.menu.export add command -label "to Grace" -command exportgrace
2019}
2020.a.file.menu add command -label Quit -command "destroy ."
2021.a.file.menu.export add command -label "as .csv file" \
2022        -command makecsvfile
2023# source additional export routines
2024set filelist [glob -nocomplain [file join $expgui(scriptdir) liveplot_*.tcl]]
2025foreach file $filelist {
2026    if [catch {
2027        source $file
2028        .a.file.menu.export add command -label $label -command $action
2029    } errmsg] {puts "error = $errmsg"}
2030}
2031pack [menubutton .a.options -text Options -underline 0 -menu .a.options.menu] \
2032        -side left   
2033menu .a.options.menu
2034.a.options.menu add cascade -label "Configure Tickmarks" -menu .a.options.menu.tick
2035menu .a.options.menu.tick
2036.a.options.menu.tick add radiobutton -label "Manual Placement" \
2037        -value 0 -variable expgui(autotick) -command plotdata
2038.a.options.menu.tick add radiobutton -label "Auto locate" \
2039        -value 1 -variable expgui(autotick) -command plotdata
2040.a.options.menu.tick add separator
2041.a.options.menu.tick add command -label "Label by name" \
2042        -command {
2043    foreach p $expmap(phaselist) {
2044        # 20 characters, max
2045        set graph(label$p) [string range [phaseinfo $p name] 0 19]
2046        plotdata
2047    }
2048}
2049.a.options.menu.tick add separator
2050
2051if {$program == "liveplot"} {
2052    .a.options.menu add command -label "Obs symbol" -command getsymopts
2053} else {
2054    .a.options.menu add cascade -label "Symbol Type" -menu .a.options.menu.sym
2055    menu .a.options.menu.sym
2056    foreach var {obs inp} lbl {Observed "Input bkg"} {
2057        .a.options.menu.sym add command -label $lbl -command "getsymopts $var"
2058    }
2059}
2060.a.options.menu add cascade -label "Symbol color" -menu .a.options.menu.color
2061menu .a.options.menu.color
2062set l1 {obs calc diff bkg chi2}
2063set l2 {Observed Calculated Obs-Calc Background Cumulative-Chi2}
2064if {$program != "liveplot"} {
2065    lappend l1 input fit
2066    lappend l2 "Input points" "bkg fit"
2067}
2068   
2069foreach var $l1 lbl $l2 {
2070    .a.options.menu.color add command -label $lbl \
2071        -command "set graph(color_$var) \[tk_chooseColor -initialcolor \$graph(color_$var) -title \"Choose \$lbl color\"]; plotdata"
2072}
2073if {$expgui(tcldump) != "" && $program == "liveplot"} {
2074    .a.options.menu add cascade -label "X units" -menu .a.options.menu.xunits
2075    menu .a.options.menu.xunits
2076    .a.options.menu.xunits add radiobutton -label "As collected" \
2077            -variable graph(xunits) -value 0 \
2078            -command {set cycle [getcycle];readdata .g}
2079    .a.options.menu.xunits add radiobutton -label "d-space" \
2080            -variable graph(xunits) -value 1 \
2081            -command {set cycle [getcycle];readdata .g}
2082    .a.options.menu.xunits add radiobutton -label "Q" \
2083            -variable graph(xunits) -value 2 \
2084            -command {set cycle [getcycle];readdata .g}
2085    .a.options.menu add cascade -label "Y units" -menu .a.options.menu.yunits
2086    menu .a.options.menu.yunits
2087    .a.options.menu.yunits add radiobutton -label "As collected" \
2088            -variable graph(yunits) -value 0 \
2089            -command {set cycle [getcycle];readdata .g}
2090    .a.options.menu.yunits add radiobutton -label "Normalized" \
2091            -variable graph(yunits) -value 1 \
2092            -command {set cycle [getcycle];readdata .g}
2093    .a.options.menu add command -label "HKL labeling" -command setlblopts
2094    .a.options.menu add checkbutton -label "Subtract background" \
2095            -variable graph(backsub) \
2096            -command {set cycle [getcycle];readdata .g}
2097} else {
2098    set graph(xunits) 0
2099}
2100   
2101.a.options.menu add checkbutton -label "Include legend" \
2102        -variable graph(legend) \
2103        -command {setlegend $box $graph(legend)}
2104.a.options.menu add command -label "Show Cursor Position" \
2105        -command ToggleLiveCursor
2106set graph(CursorLabel) [.a.options.menu index "Show Cursor Position"]
2107.a.options.menu add command -label "Set PS output" -command setpostscriptout
2108.a.options.menu add cascade -menu  .a.options.menu.font \
2109        -label "Screen font"
2110menu .a.options.menu.font
2111foreach f {10 11 12 13 14 16 18 20 22} {
2112    .a.options.menu.font add radiobutton \
2113            -command {SetTkDefaultOptions $expgui(font); ResizeFont .} \
2114        -label $f -value $f -variable expgui(font) -font "Helvetica -$f"
2115}
2116if {$program == "liveplot"} {
2117    .a.options.menu add checkbutton -label "Raise on update" \
2118            -variable graph(autoraise)
2119    .a.options.menu add checkbutton -label "Cumulative Chi2" \
2120            -variable graph(chi2) -command ShowCumulativeChi2
2121    .a.options.menu add command -label "Save Options" -underline 1 \
2122            -command "SaveOptions"
2123    ShowCumulativeChi2
2124} elseif {$program == "bkgedit"}  {
2125    catch {pack [frame .bkg -bd 3 -relief sunken] -side bottom -fill both}
2126#    grid [label .bkg.top -text "Background Point Editing"] \
2127#           -col 0 -row 0 -columnspan 4
2128#    grid [button .bkg.help -text Help -bg yellow \
2129#           -command "MakeWWWHelp liveplot.html bkgedit"] \
2130#           -column 5 -row 0 -rowspan 2 -sticky n
2131   
2132    grid [frame .bkg.l -bd 3 -relief groove] \
2133            -col 0 -row 1 -columnspan 2 -sticky nse
2134    grid [label .bkg.l.1 -text "Mouse click\naction"] -col 0 -row 0
2135    foreach c {1 2 3} l {zoom add delete} {
2136        grid [button .bkg.l.b$c -text $l -command "bkgEditMode $c"] \
2137                -col $c -row 0
2138    }
2139    # leave a small blank space
2140    grid columnconfigure .bkg 2 -pad 0 -min 10
2141    grid [frame .bkg.f -bd 3 -relief groove] \
2142            -col 3 -row 1 -columnspan 2 -sticky nsw
2143    grid [button .bkg.f.fit1 -text "Fit" -command {bkgFit .bkg.f.fit1}] \
2144            -col 1 -row 1
2145    grid [label .bkg.f.tl -text "with"] -col 3 -row 1
2146    set termmenu [tk_optionMenu .bkg.f.terms expgui(FitOrder) 0]
2147    grid .bkg.f.terms -col 4 -row 1
2148    grid [label .bkg.f.tl1 -text "terms"] -col 5 -row 1
2149
2150    grid [frame .bkg.c1 -bd 3 -relief groove] \
2151            -col 0 -row 5 -rowspan 2 -sticky nsew
2152    grid [label .bkg.c1.0 -text "Background\nfunction #"] -col 0 -row 0
2153    set bkgmenu [tk_optionMenu .bkg.c1.1 expgui(FitFunction) stuff]
2154    grid .bkg.c1.1 -col 0 -row 1
2155    $bkgmenu delete 0 end
2156    foreach item {
2157        "1 - Shifted Chebyschev polynomial"
2158        "2 - Cosine Fourier series"
2159        "3 - Radial distribution peaks"
2160        "4 - Power series in Q**2n/n!"
2161        "5 - Power series in n!/Q**2n"
2162        "6 - Power series in Q**2n/n! and n!/Q**2n"
2163    } {
2164        set val [lindex $item 0]
2165        $bkgmenu insert end radiobutton -variable expgui(FitFunction) \
2166                -label $item -value $val \
2167                -command "set termlist {};BkgFillTermBoxes nosave"
2168    }
2169    set expgui(FitFunction) 1
2170
2171    grid [canvas .bkg.canvas \
2172            -scrollregion {0 0 5000 500} -width 0 -height 0 \
2173            -xscrollcommand ".bkg.scroll set"] \
2174            -column 1 -row 5 -columnspan 3 -sticky nsew
2175    grid [scrollbar .bkg.scroll -command ".bkg.canvas xview" \
2176            -orient horizontal] -column 1 -row 6 -columnspan 3 -sticky nsew
2177    grid [button .bkg.cw -text "Save in\nEXP file\n& Exit" \
2178            -command "bkgSave;exit"] \
2179            -col 4 -columnspan 2 -row 5 -rowspan 2 -sticky ns
2180
2181    grid [frame .bkg.bl -bd 3 -relief groove] \
2182            -col 0 -row 3 -rowspan 2 -sticky nsew
2183    grid [label .bkg.bl.1 -text "Background\npoints"] -col 0 -row 0
2184    grid [canvas .bkg.bc \
2185            -scrollregion {0 0 5000 500} -width 0 -height 0 \
2186            -xscrollcommand ".bkg.bs set"] \
2187            -column 1 -row 3 -columnspan 5 -sticky nsew
2188    grid [scrollbar .bkg.bs -command ".bkg.bc xview" -orient horizontal] \
2189            -column 1 -row 4 -columnspan 5 -sticky nsew
2190
2191    grid columnconfigure .bkg 1 -weight 1
2192    grid columnconfigure .bkg 2 -weight 1
2193    grid columnconfigure .bkg 3 -weight 1
2194    grid rowconfigure .bkg 3 -weight 1
2195    grid rowconfigure .bkg 5 -weight 1
2196    .g config -title ""
2197}
2198
2199pack [menubutton .a.help -text Help -underline 0 -menu .a.help.menu] -side right
2200menu .a.help.menu -tearoff 0
2201if {$program == "bkgedit"}  {
2202    .a.help.menu add command -command "MakeWWWHelp liveplot.html bkgedit" \
2203            -label "Web page"
2204} else {
2205    .a.help.menu add command -command "MakeWWWHelp liveplot.html" \
2206            -label "Web page"
2207}
2208.a.help.menu add command -command aboutliveplot -label About
2209
2210pack .a -side top -fill both
2211pack $box -fill both -expand yes
2212
2213# add the extra options
2214set fl [file join $expgui(scriptdir) icddcmd.tcl]
2215if [file exists $fl] {source $fl}
2216set fl [file join $expgui(scriptdir) cellgen.tcl]
2217if [file exists $fl] {source $fl}
2218
2219expload $expnam.EXP
2220mapexp
2221
2222# fill the histogram menu
2223if {[llength $expmap(powderlist)] > 15} {
2224    set expgui(plotlist) {}
2225    .a.file.menu entryconfigure Histogram -state normal
2226    menu .a.file.menu.hist
2227    set i 0
2228    foreach num [lsort -integer $expmap(powderlist)] {
2229        incr i
2230        # for now include, but disable histograms
2231        set state disabled
2232        if {[string range $expmap(htype_$num) 3 3] != "*"} {
2233            set state normal
2234            lappend expgui(plotlist) $num
2235        }
2236        if {$i == 1} {
2237            set num1 $num
2238            menu .a.file.menu.hist.$num1
2239        }
2240        .a.file.menu.hist.$num1 add radiobutton -label $num -value $num \
2241                -variable hst -state $state \
2242                -command {set cycle [getcycle];readdata .g}
2243        if {$i >= 10} {
2244            set i 0
2245            .a.file.menu.hist add cascade -label "$num1-$num" \
2246                    -menu .a.file.menu.hist.$num1
2247        }
2248    }
2249    if {$i != 0} {
2250        .a.file.menu.hist add cascade -label "$num1-$num" \
2251                -menu .a.file.menu.hist.$num1
2252    }
2253} elseif {[llength $expmap(powderlist)] > 1} {
2254    set expgui(plotlist) {}
2255    .a.file.menu entryconfigure Histogram -state normal
2256    menu .a.file.menu.hist
2257    foreach num [lsort -integer $expmap(powderlist)] {
2258        # for now include, but disable unprocessed histograms
2259        set state disabled
2260        if {[string range $expmap(htype_$num) 3 3] != "*"} {
2261            set state normal
2262            lappend expgui(plotlist) $num
2263        }
2264        .a.file.menu.hist add radiobutton -label $num -value $num \
2265                -variable hst -state $state \
2266                -command {set cycle [getcycle];readdata .g}
2267    }
2268} else {
2269    set expgui(plotlist) [lindex $expmap(powderlist) 0]
2270}
2271
2272foreach num $expmap(phaselist) {
2273    .a.file.menu.tick add checkbutton -label "Phase $num" \
2274            -variable  peakinfo(flag$num) \
2275            -command plotdata
2276    if {$program != "bkgedit"}  {
2277        bind . <Key-$num> ".a.file.menu.tick invoke $num"
2278    }
2279    .a.options.menu.tick add command -label "Phase $num opts" \
2280            -command "minioptionsbox $num"
2281}
2282
2283# N = load next histogram
2284bind . <Key-n> {
2285    set i [lsearch $expgui(plotlist) $hst]
2286    incr i
2287    if {$i >= [llength $expgui(plotlist)]} {set i 0}
2288    set hst [lindex $expgui(plotlist) $i]
2289    set cycle [getcycle];readdata .g
2290}
2291bind . <Key-N> {
2292    set i [lsearch $expgui(plotlist) $hst]
2293    incr i
2294    if {$i >= [llength $expgui(plotlist)]} {set i 0}
2295    set hst [lindex $expgui(plotlist) $i]
2296    set cycle [getcycle];readdata .g
2297}
2298bind . <Key-l> {ToggleLiveCursor}
2299bind . <Key-L> {ToggleLiveCursor}
2300updateifnew
2301donewaitmsg
2302trace variable peakinfo w plotdataupdate
Note: See TracBrowser for help on using the repository browser.