source: branches/blt4/gui/scripts/analyzer.tcl @ 1799

Last change on this file since 1799 was 1795, checked in by gah, 14 years ago
File size: 45.2 KB
Line 
1# ----------------------------------------------------------------------
2#  COMPONENT: analyzer - output area for Rappture
3#
4#  This widget acts as the output side of a Rappture application.
5#  When the input has changed, it displays a Simulate button that
6#  launches the simulation.  When a simulation is running, this
7#  area shows status.  When it is finished, the results appear
8#  in place of the button, according to the specs in the <analyze>
9#  XML data.
10# ======================================================================
11#  AUTHOR:  Michael McLennan, Purdue University
12#  Copyright (c) 2004-2005  Purdue Research Foundation
13#
14#  See the file "license.terms" for information on usage and
15#  redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
16# ======================================================================
17package require Itk
18
19option add *Analyzer.width 3.5i widgetDefault
20option add *Analyzer.height 4i widgetDefault
21option add *Analyzer.simControl "auto" widgetDefault
22option add *Analyzer.simControlBackground "" widgetDefault
23option add *Analyzer.simControlOutline gray widgetDefault
24option add *Analyzer.simControlActiveBackground #ffffcc widgetDefault
25option add *Analyzer.simControlActiveOutline black widgetDefault
26option add *Analyzer.notebookpage "about" widgetDefault
27
28option add *Analyzer.font \
29    -*-helvetica-medium-r-normal-*-12-* widgetDefault
30option add *Analyzer.codeFont \
31    -*-courier-medium-r-normal-*-12-* widgetDefault
32option add *Analyzer.textFont \
33    -*-helvetica-medium-r-normal-*-12-* widgetDefault
34option add *Analyzer.boldTextFont \
35    -*-helvetica-bold-r-normal-*-12-* widgetDefault
36
37itk::usual Scrollset {
38}
39
40itcl::class Rappture::Analyzer {
41    inherit itk::Widget
42
43    itk_option define -codefont codeFont Font ""
44    itk_option define -textfont textFont Font ""
45    itk_option define -boldtextfont boldTextFont Font ""
46    itk_option define -simcontrol simControl SimControl ""
47    itk_option define -simcontroloutline simControlOutline Background ""
48    itk_option define -simcontrolbackground simControlBackground Background ""
49    itk_option define -simcontrolactiveoutline simControlActiveOutline Background ""
50    itk_option define -simcontrolactivebackground simControlActiveBackground Background ""
51    itk_option define -holdwindow holdWindow HoldWindow ""
52    itk_option define -notebookpage notebookPage NotebookPage ""
53
54    constructor {tool args} { # defined below }
55    destructor { # defined below }
56
57    public method simulate {args}
58    public method reset {{when -eventually}}
59    public method load {xmlobj}
60    public method clear {}
61    public method download {option args}
62
63    protected method _plot {args}
64    protected method _reorder {comps}
65    protected method _autoLabel {xmlobj path title cntVar}
66    protected method _fixResult {}
67    protected method _fixSize {}
68    protected method _fixSimControl {}
69    protected method _fixNotebook {}
70    protected method _simState {state args}
71    protected method _simOutput {message}
72    protected method _resultTooltip {}
73    protected method _isPdbTrajectory {data}
74    protected method _isLammpsTrajectory {data}
75    protected method _pdbToSequence {xmlobj path id child data}
76    protected method _lammpsToSequence {xmlobj path id child data}
77    protected method _trajToSequence {xmlobj {path ""}}
78
79    private variable _tool ""          ;# belongs to this tool
80    private variable _appName ""       ;# Name of application
81    private variable _control "manual" ;# start mode
82    private variable _runs ""          ;# list of XML objects with results
83    private variable _pages 0          ;# number of pages for result sets
84    private variable _label2page       ;# maps output label => result set
85    private variable _label2desc       ;# maps output label => description
86    private variable _lastlabel ""     ;# label of last example loaded
87    private variable _plotlist ""      ;# items currently being plotted
88
89    private common job                 ;# array var used for blt::bgexec jobs
90}
91
92itk::usual Scrollset {
93}
94itk::usual Analyzer {
95    keep -background -cursor foreground -font
96}
97
98# ----------------------------------------------------------------------
99# CONSTRUCTOR
100# ----------------------------------------------------------------------
101itcl::body Rappture::Analyzer::constructor {tool args} {
102    set _tool $tool
103
104    itk_option add hull.width hull.height
105    pack propagate $itk_component(hull) no
106
107    frame $itk_interior.simol -borderwidth 1 -relief flat
108    pack $itk_interior.simol -fill x
109
110    itk_component add simbg {
111        frame $itk_interior.simol.simbg -borderwidth 0
112    } {
113        usual
114        rename -background -simcontrolcolor simControlColor Color
115    }
116    pack $itk_component(simbg) -expand yes -fill both
117
118    set simtxt [$tool xml get tool.action.label]
119    if {"" == $simtxt} {
120        set simtxt "Simulate"
121    }
122    itk_component add simulate {
123        button $itk_component(simbg).simulate -text $simtxt \
124            -command [itcl::code $this simulate]
125    } {
126        usual
127        rename -highlightbackground -simcontrolcolor simControlColor Color
128    }
129    pack $itk_component(simulate) -side left -padx 4 -pady 4
130
131    # if there's a hub url, then add "About" and "Questions" links
132    set _appName [$_tool xml get tool.id]
133    set url [Rappture::Tool::resources -huburl]
134    if {"" != $url && "" != $_appName} {
135        itk_component add hubcntls {
136            frame $itk_component(simbg).hubcntls
137        } {
138            usual
139            rename -background -simcontrolcolor simControlColor Color
140        }
141        pack $itk_component(hubcntls) -side right -padx 4
142
143        itk_component add icon {
144            label $itk_component(hubcntls).icon -image [Rappture::icon ask] \
145                -highlightthickness 0
146        } {
147            usual
148            ignore -highlightthickness
149            rename -background -simcontrolcolor simControlColor Color
150        }
151        pack $itk_component(icon) -side left
152
153        itk_component add about {
154            button $itk_component(hubcntls).about -text "About this tool" \
155                -command [list Rappture::filexfer::webpage \
156                              "$url/tools/$_appName"]
157        } {
158            usual
159            ignore -font
160            rename -background -simcontrolcolor simControlColor Color
161            rename -highlightbackground -simcontrolcolor simControlColor Color
162        }
163        pack $itk_component(about) -side top -anchor w
164
165        itk_component add questions {
166            button $itk_component(hubcntls).questions -text Questions? \
167                -command [list Rappture::filexfer::webpage \
168                              "$url/resources/$_appName/questions"]
169        } {
170            usual
171            ignore -font
172            rename -background -simcontrolcolor simControlColor Color
173            rename -highlightbackground -simcontrolcolor simControlColor Color
174        }
175        pack $itk_component(questions) -side top -anchor w
176    }
177
178    itk_component add simstatus {
179        text $itk_component(simbg).simstatus -borderwidth 0 \
180            -highlightthickness 0 -height 1 -width 1 -wrap none \
181            -state disabled
182    } {
183        usual
184        ignore -highlightthickness
185        rename -background -simcontrolcolor simControlColor Color
186        rename -font -textfont textFont Font
187    }
188    pack $itk_component(simstatus) -side left -expand yes -fill x
189
190    $itk_component(simstatus) tag configure popup \
191        -underline 1 -foreground blue
192
193    $itk_component(simstatus) tag bind popup \
194        <Enter> {%W configure -cursor center_ptr}
195    $itk_component(simstatus) tag bind popup \
196        <Leave> {%W configure -cursor ""}
197    $itk_component(simstatus) tag bind popup \
198        <ButtonPress> {after idle {Rappture::Tooltip::tooltip show %W}}
199
200
201    itk_component add notebook {
202        Rappture::Notebook $itk_interior.nb
203    }
204    pack $itk_interior.nb -expand yes -fill both
205
206    # ------------------------------------------------------------------
207    # ABOUT PAGE
208    # ------------------------------------------------------------------
209    set w [$itk_component(notebook) insert end about]
210
211    blt::scrollset $w.info -yscrollbar $w.info.ys -window $w.info.text
212    blt::tk::scrollbar $w.info.ys
213    pack $w.info -expand yes -fill both -padx 4 -pady 20
214    itk_component add toolinfo {
215        text $w.info.text -width 1 -height 1 -wrap word \
216            -borderwidth 0 -highlightthickness 0
217    } {
218        usual
219        ignore -borderwidth -relief
220        rename -font -textfont textFont Font
221    }
222
223    # ------------------------------------------------------------------
224    # SIMULATION PAGE
225    # ------------------------------------------------------------------
226    set w [$itk_component(notebook) insert end simulate]
227    frame $w.cntls
228    pack $w.cntls -side bottom -fill x -pady 12
229    frame $w.cntls.sep -background black -height 1
230    pack $w.cntls.sep -side top -fill x
231
232    itk_component add abort {
233        button $w.cntls.abort -text "Abort" \
234            -command [itcl::code $_tool abort]
235    }
236    pack $itk_component(abort) -side left -expand yes -padx 4 -pady 4
237
238    blt::scrollset $w.info -xscrollbar $w.info.xs -yscrollbar $w.info.ys \
239        -window $w.info.text
240    blt::tk::scrollbar $w.info.xs
241    blt::tk::scrollbar $w.info.ys
242
243    pack $w.info -expand yes -fill both -padx 4 -pady 4
244    itk_component add runinfo {
245        text $w.info.text -width 1 -height 1 -wrap none \
246            -borderwidth 0 -highlightthickness 0 \
247            -state disabled
248    } {
249        usual
250        ignore -borderwidth -relief
251        rename -font -codefont codeFont Font
252    }
253    itk_component add progress {
254        Rappture::Progress $w.progress
255    }
256
257    # ------------------------------------------------------------------
258    # ANALYZE PAGE
259    # ------------------------------------------------------------------
260    set w [$itk_component(notebook) insert end analyze]
261
262    frame $w.top
263    pack $w.top -side top -fill x -pady 8
264    label $w.top.l -text "Result:" -font $itk_option(-font)
265    pack $w.top.l -side left
266
267    itk_component add resultselector {
268        Rappture::Combobox $w.top.sel -width 10 -editable no
269    } {
270        usual
271        rename -font -textfont textFont Font
272    }
273    pack $itk_component(resultselector) -side left -expand yes -fill x
274    bind $itk_component(resultselector) <<Value>> [itcl::code $this _fixResult]
275    bind $itk_component(resultselector) <Enter> \
276        [itcl::code $this download coming]
277
278    Rappture::Tooltip::for $itk_component(resultselector) \
279        "@[itcl::code $this _resultTooltip]"
280
281    $itk_component(resultselector) choices insert end \
282        --- "---"
283
284    itk_component add download {
285        button $w.top.dl -image [Rappture::icon download] -anchor e \
286            -borderwidth 1 -relief flat -overrelief raised \
287            -command [itcl::code $this download start $w.top.dl]
288    }
289    pack $itk_component(download) -side right -padx {4 0}
290    bind $itk_component(download) <Enter> \
291        [itcl::code $this download coming]
292
293    $itk_component(resultselector) choices insert end \
294        @download [Rappture::filexfer::label download]
295
296    if {[Rappture::filexfer::enabled]} {
297        Rappture::Tooltip::for $itk_component(download) "Downloads the current result to a new web browser window on your desktop.  From there, you can easily print or save results.
298
299NOTE:  Your web browser must allow pop-ups from this site.  If your output does not appear, look for a 'pop-up blocked' message and enable pop-ups."
300    } else {
301        Rappture::Tooltip::for $itk_component(download) "Saves the current result to a file on your desktop."
302    }
303
304    itk_component add results {
305        Rappture::Panes $w.pane -sashwidth 1 -sashrelief solid -sashpadding {4 0}
306    }
307    pack $itk_component(results) -expand yes -fill both
308    set f [$itk_component(results) pane 0]
309
310    itk_component add resultpages {
311        Rappture::Notebook $f.nb
312    }
313    pack $itk_component(resultpages) -expand yes -fill both
314
315    set f [$itk_component(results) insert end -fraction 0.1]
316    itk_component add resultset {
317        Rappture::ResultSet $f.rset \
318            -clearcommand [itcl::code $this clear] \
319            -settingscommand [itcl::code $this _plot] \
320            -promptcommand [itcl::code $this _simState]
321    }
322    pack $itk_component(resultset) -expand yes -fill both
323    bind $itk_component(resultset) <<Control>> [itcl::code $this _fixSize]
324    bind $itk_component(results) <Configure> [itcl::code $this _fixSize]
325
326    eval itk_initialize $args
327
328    $itk_component(runinfo) tag configure ERROR -foreground red
329    $itk_component(runinfo) tag configure text -font $itk_option(-textfont)
330
331    #
332    # Load up tool info on the first page.
333    #
334    $itk_component(toolinfo) tag configure title \
335        -font $itk_option(-boldtextfont)
336
337    set mesg [$tool xml get tool.title]
338    if {"" != $mesg} {
339        $itk_component(toolinfo) insert end $mesg title
340        $itk_component(toolinfo) insert end "\n\n"
341    }
342
343    set mesg [$tool xml get tool.about]
344    if {"" != $mesg} {
345        $itk_component(toolinfo) insert end $mesg
346    }
347    $itk_component(toolinfo) configure -state disabled
348    $itk_component(notebook) current about
349
350    # tool can run on "manual" (default) or "auto"
351    set cntl [$tool xml get tool.control]
352    if {"" == $cntl} {
353        set cntl [$tool xml get tool.control.type]
354    }
355    if {"" != $cntl} {
356        set _control $cntl
357    }
358
359    # reset everything to a clean state
360    reset
361}
362
363# ----------------------------------------------------------------------
364# DESTRUCTOR
365# ----------------------------------------------------------------------
366itcl::body Rappture::Analyzer::destructor {} {
367    foreach obj $_runs {
368        itcl::delete object $obj
369    }
370    after cancel [itcl::code $this simulate]
371}
372
373# ----------------------------------------------------------------------
374# USAGE: simulate ?-ifneeded?
375# USAGE: simulate ?<path1> <value1> <path2> <value2> ...?
376#
377# Kicks off the simulator by executing the tool.command associated
378# with the tool.  If any arguments are specified, they are used to
379# set parameters for the simulation.  While the simulation is running,
380# it shows status.  When the simulation is finished, it switches
381# automatically to "analyze" mode and shows the results.
382# ----------------------------------------------------------------------
383itcl::body Rappture::Analyzer::simulate {args} {
384    if {$args == "-ifneeded"} {
385        # check to see if simulation is really needed
386        $_tool sync
387        if {[$itk_component(resultset) contains [$_tool xml object]]
388              && ![string equal $_control "manual-resim"]} {
389            # not needed -- show results and return
390            $itk_component(notebook) current analyze
391            return
392        }
393        set args ""
394    }
395
396    # simulation is needed -- go to simulation page
397    $itk_component(notebook) current simulate
398
399    # no progress messages yet
400    pack forget $itk_component(progress)
401    lappend args -output [itcl::code $this _simOutput]
402
403    _simState off
404    $itk_component(runinfo) configure -state normal
405    $itk_component(runinfo) delete 1.0 end
406    $itk_component(runinfo) insert end "Running simulation...\n\n" text
407    $itk_component(runinfo) configure -state disabled
408
409    # if the hold window is set, then put up a busy cursor
410    if {$itk_option(-holdwindow) != ""} {
411        blt::busy hold $itk_option(-holdwindow)
412        raise $itk_component(hull)
413    }
414
415    # execute the job
416    foreach {status result} [eval $_tool run $args] break
417
418    # if job was aborted, then allow simulation again
419    if {$result == "ABORT"} {
420        _simState on "Aborted"
421    }
422
423    # load results from run.xml into analyzer
424    if {$status == 0 && $result != "ABORT"} {
425        set status [catch {load $result} result]
426    }
427
428    # back to normal
429    if {$itk_option(-holdwindow) != ""} {
430        blt::busy release $itk_option(-holdwindow)
431    }
432    $itk_component(abort) configure -state disabled
433
434    if {$status != 0} {
435        $itk_component(runinfo) configure -state normal
436        $itk_component(runinfo) delete 1.0 end
437        $itk_component(runinfo) insert end "Problem launching job:\n\n" text
438        _simOutput $result
439        $itk_component(runinfo) configure -state disabled
440        $itk_component(runinfo) see 1.0
441
442        # Try to create a support ticket for this error.
443        # It may be a real problem.
444        if {[Rappture::bugreport::shouldReport for jobs]} {
445            Rappture::bugreport::register "Problem launching job:\n\n$result\n== RAPPTURE INPUT ==\n[$_tool xml xml]"
446        }
447    } else {
448        $itk_component(notebook) current analyze
449    }
450
451    # do this last -- after _simOutput above
452    pack forget $itk_component(progress)
453}
454
455# ----------------------------------------------------------------------
456# USAGE: reset ?-eventually|-now?
457#
458# Used to reset the analyzer whenever the input to a simulation has
459# changed.  Sets the mode back to "simulate", so the user has to
460# simulate again to see the output.  If the <start> option is set
461# to "auto", the simulation is invoked immediately.
462# ----------------------------------------------------------------------
463itcl::body Rappture::Analyzer::reset {{when -eventually}} {
464    if {$when == "-eventually"} {
465        after cancel [list catch [itcl::code $this reset -now]]
466        after idle [list catch [itcl::code $this reset -now]]
467        return
468    }
469
470    # check to see if simulation is really needed
471    $_tool sync
472    if {![$itk_component(resultset) contains [$_tool xml object]]
473          || [string equal $_control "manual-resim"]} {
474        # if control mode is "auto", then simulate right away
475        if {[string match auto* $_control]} {
476            # auto control -- don't need button
477            pack forget $itk_interior.simol
478
479            after cancel [itcl::code $this simulate]
480            after idle [itcl::code $this simulate]
481        } else {
482            _simState on "new input parameters"
483        }
484    } else {
485        _simState off
486    }
487}
488
489# ----------------------------------------------------------------------
490# USAGE: load <xmlobj>
491#
492# Loads the data from the given <xmlobj> into the appropriate results
493# sets.  If necessary, new results sets are created to store the data.
494# ----------------------------------------------------------------------
495itcl::body Rappture::Analyzer::load {xmlobj} {
496    # only show the last result? then clear first
497    if {[$_tool xml get tool.analyzer] == "last"} {
498        clear
499    }
500
501    # look for all output.load children and load them first
502    # each run.xml is loaded as a previous simulation.
503    foreach item [$xmlobj children -type run output.load] {
504        set loadfile [$xmlobj get output.load.$item]
505        set loadobj [Rappture::library $loadfile]
506        load $loadobj
507    }
508
509    foreach item [$xmlobj children -type run output.include] {
510        set id [$xmlobj element -as id output.include.$item]
511        set inclfile [$xmlobj get output.include.$item]
512        set inclobj [Rappture::library $inclfile]
513        foreach c [$inclobj children output] {
514            switch -glob -- $c {
515                # we don't want to include these tags
516                include* - time* - status* - user* {
517                    continue
518                }
519                default {
520                    set oldid [$inclobj element -as id output.$c]
521                    set oldtype [$inclobj element -as type output.$c]
522                    set newcomp "$oldtype\($id-$oldid\)"
523                    $xmlobj copy output.$newcomp from $inclobj output.$c
524                }
525            }
526        }
527    }
528
529    lappend _runs $xmlobj
530
531    # detect molecule elements that contain trajectory data and convert
532    # to sequences.
533    _trajToSequence $xmlobj output
534
535    # go through the analysis and find all result sets
536    set haveresults 0
537    foreach item [_reorder [$xmlobj children output]] {
538        switch -glob -- $item {
539            log* {
540                _autoLabel $xmlobj output.$item "Output Log" counters
541            }
542            number* {
543                _autoLabel $xmlobj output.$item "Number" counters
544            }
545            integer* {
546                _autoLabel $xmlobj output.$item "Integer" counters
547            }
548            string* {
549                _autoLabel $xmlobj output.$item "String" counters
550            }
551            histogram* - curve* - field* {
552                _autoLabel $xmlobj output.$item "Plot" counters
553            }
554            structure* {
555                _autoLabel $xmlobj output.$item "Structure" counters
556            }
557            table* {
558                _autoLabel $xmlobj output.$item "Energy Levels" counters
559            }
560            sequence* {
561                _autoLabel $xmlobj output.$item "Sequence" counters
562            }
563        }
564        set label [$xmlobj get output.$item.about.group]
565        if {"" == $label} {
566            set label [$xmlobj get output.$item.about.label]
567        }
568
569        set hidden [$xmlobj get output.$item.hide]
570        set hidden [expr {"" != $hidden && $hidden}]
571
572        if {"" != $label && !$hidden} {
573            set haveresults 1
574        }
575    }
576
577    # if there are any valid results, add them to the resultset
578    if {$haveresults} {
579        set index [$itk_component(resultset) add $xmlobj]
580
581        # add each result to a result viewer
582        foreach item [_reorder [$xmlobj children output]] {
583            set label [$xmlobj get output.$item.about.group]
584            if {"" == $label} {
585                set label [$xmlobj get output.$item.about.label]
586            }
587
588            set hidden [$xmlobj get output.$item.hide]
589            set hidden [expr {"" != $hidden && $hidden}]
590
591            if {"" != $label && !$hidden} {
592                if {![info exists _label2page($label)]} {
593                    set name "page[incr _pages]"
594                    set page [$itk_component(resultpages) insert end $name]
595                    set _label2page($label) $page
596                    set _label2desc($label) \
597                        [$xmlobj get output.$item.about.description]
598                    Rappture::ResultViewer $page.rviewer
599                    pack $page.rviewer -expand yes -fill both -pady 4
600
601                    set end [$itk_component(resultselector) \
602                        choices index -value ---]
603                    if {$end < 0} {
604                        set end "end"
605                    }
606                    $itk_component(resultselector) choices insert $end \
607                        $name $label
608                }
609
610                # add/replace the latest result into this viewer
611                set page $_label2page($label)
612
613                if {![info exists reset($page)]} {
614                    $page.rviewer clear $index
615                    set reset($page) 1
616                }
617                $page.rviewer add $index $xmlobj output.$item
618            }
619        }
620    }
621
622    # show the first page by default
623    set max [$itk_component(resultselector) choices size]
624    for {set i 0} {$i < $max} {incr i} {
625        set first [$itk_component(resultselector) choices get -label $i]
626        if {$first != ""} {
627            set page [$itk_component(resultselector) choices get -value $i]
628            set char [string index $page 0]
629            if {$char != "@" && $char != "-"} {
630                $itk_component(resultpages) current $page
631                $itk_component(resultselector) value $first
632                set _lastlabel $first
633                break
634            }
635        }
636    }
637}
638
639# ----------------------------------------------------------------------
640# USAGE: clear
641#
642# Discards all results previously loaded into the analyzer.
643# ----------------------------------------------------------------------
644itcl::body Rappture::Analyzer::clear {} {
645    foreach obj $_runs {
646        itcl::delete object $obj
647    }
648    set _runs ""
649
650    $itk_component(resultset) clear
651
652    # reset the size of the controls area
653    set ht [winfo height $itk_component(results)]
654    set cntlht [$itk_component(resultset) size -controlarea]
655    set frac [expr {double($cntlht)/$ht}]
656    $itk_component(results) fraction end $frac
657
658    foreach label [array names _label2page] {
659        set page $_label2page($label)
660        $page.rviewer clear
661    }
662    $itk_component(resultselector) value ""
663    $itk_component(resultselector) choices delete 0 end
664    catch {unset _label2page}
665    catch {unset _label2desc}
666    set _plotlist ""
667
668    $itk_component(resultselector) choices insert end --- "---"
669    $itk_component(resultselector) choices insert end \
670        @download [Rappture::filexfer::label download]
671    set _lastlabel ""
672
673    #
674    # HACK ALERT!!
675    # The following statement should be in place, but it causes
676    # vtk to dump core.  Leave it out until we can fix the core dump.
677    # In the mean time, we leak memory...
678    #
679    #$itk_component(resultpages) delete -all
680    #set _pages 0
681
682    _simState on
683    _fixSimControl
684    reset
685}
686
687# ----------------------------------------------------------------------
688# USAGE: download coming
689# USAGE: download controls <downloadCommand>
690# USAGE: download start ?widget?
691# USAGE: download now ?widget?
692#
693# Spools the current result so the user can download it.
694# ----------------------------------------------------------------------
695itcl::body Rappture::Analyzer::download {option args} {
696    set title [$itk_component(resultselector) value]
697    set page [$itk_component(resultselector) translate $title]
698
699    switch -- $option {
700        coming {
701            #
702            # Warn result that a download is coming, in case
703            # it needs to take a screen snap.
704            #
705            if {![regexp {^(|@download|---)$} $page]} {
706                set f [$itk_component(resultpages) page $page]
707                $f.rviewer download coming
708            }
709        }
710        controls {
711            # no controls for this download yet
712            return ""
713        }
714        start {
715            set widget $itk_component(download)
716            if {[llength $args] > 0} {
717                set widget [lindex $args 0]
718                if {[catch {winfo class $widget}]} {
719                    set widget $itk_component(download)
720                }
721            }
722            #
723            # See if this download has any controls.  If so, then
724            # post them now and let the user continue the download
725            # after selecting a file format.
726            #
727            if {$page != ""} {
728                set ext ""
729                set f [$itk_component(resultpages) page $page]
730                set arg [itcl::code $this download now $widget]
731                set popup [$f.rviewer download controls $arg]
732                if {"" != $popup} {
733                    $popup activate $widget below
734                } else {
735                    download now $widget
736                }
737            } else {
738                # this shouldn't happen
739                set file error.html
740                set data "<h1>Not Found</h1>There is no result selected."
741            }
742        }
743        now {
744            set widget $itk_component(download)
745            if {[llength $args] > 0} {
746                set widget [lindex $args 0]
747                if {[catch {winfo class $widget}]} {
748                    set widget $itk_component(download)
749                }
750            }
751            #
752            # Perform the actual download.
753            #
754            if {$page != ""} {
755                set ext ""
756                set f [$itk_component(resultpages) page $page]
757                set item [$itk_component(resultselector) value]
758                set result [$f.rviewer download now $widget $_appName $item]
759                if { $result == "" } {
760                    return;             # User cancelled the download.
761                }
762                foreach {ext data} $result break
763                if {"" == $ext} {
764                    if {"" != $widget} {
765                        Rappture::Tooltip::cue $widget \
766                            "Can't download this result."
767                    }
768                    return
769                }
770                regsub -all {[\ -\/\:-\@\{-\~]} $title {} title
771                set file "$title$ext"
772            } else {
773                # this shouldn't happen
774                set file error.html
775                set data "<h1>Not Found</h1>There is no result selected."
776            }
777
778            set mesg [Rappture::filexfer::download $data $file]
779            if {[string length $mesg] > 0} {
780                Rappture::Tooltip::cue $widget $mesg
781            }
782        }
783        default {
784            error "bad option \"$option\": should be coming, controls, now, start"
785        }
786    }
787}
788
789# ----------------------------------------------------------------------
790# USAGE: _plot ?<index> <options> <index> <options>...?
791#
792# Used internally to update the plot shown in the current result
793# viewer whenever the resultset settings have changed.  Causes the
794# desired results to show up on screen.
795# ----------------------------------------------------------------------
796itcl::body Rappture::Analyzer::_plot {args} {
797    set _plotlist $args
798
799    set page [$itk_component(resultselector) value]
800    set page [$itk_component(resultselector) translate $page]
801    if {"" != $page} {
802        set f [$itk_component(resultpages) page $page]
803        $f.rviewer plot clear
804        foreach {index opts} $_plotlist {
805            $f.rviewer plot add $index $opts
806        }
807    }
808}
809
810# ----------------------------------------------------------------------
811# USAGE: _reorder <compList>
812#
813# Used internally to change the order of a series of output components
814# found in the <output> section.  Moves the <log> elements to the end
815# and returns the updated list.
816# ----------------------------------------------------------------------
817itcl::body Rappture::Analyzer::_reorder {comps} {
818    set i 0
819    set max [llength $comps]
820    while {$i < $max} {
821        set c [lindex $comps $i]
822        if {[string match log* $c]} {
823            set comps [lreplace $comps $i $i]
824            lappend comps $c
825            incr max -1
826        } else {
827            incr i
828        }
829    }
830    return $comps
831}
832
833# ----------------------------------------------------------------------
834# USAGE: _autoLabel <xmlobj> <path> <title> <cntVar>
835#
836# Used internally to check for an about.label property at the <path>
837# in <xmlobj>.  If this object doesn't have a label, then one is
838# supplied using the given <title>.  The <cntVar> is an array of
839# counters in the calling scopes for titles that have been used
840# in the past.  This is used to create titles like "Plot #2" the
841# second time it is encountered.
842#
843# The <xmlobj> is updated so that the label is inserted directly in
844# the tree.
845# ----------------------------------------------------------------------
846itcl::body Rappture::Analyzer::_autoLabel {xmlobj path title cntVar} {
847    upvar $cntVar counters
848
849    set group [$xmlobj get $path.about.group]
850    set label [$xmlobj get $path.about.label]
851    if {"" == $label} {
852        # no label -- make one up using the title specified
853        if {![info exists counters($group-$title)]} {
854            set counters($group-$title) 1
855            set label $title
856        } else {
857            set label "$title (#[incr counters($group-$title)])"
858        }
859        $xmlobj put $path.about.label $label
860    } else {
861        # handle the case of two identical labels in <output>
862        if {![info exists counters($group-$label)]} {
863            set counters($group-$label) 1
864        } else {
865            set label "$label (#[incr counters($group-$label)])"
866            $xmlobj put $path.about.label $label
867        }
868    }
869    return $label
870}
871
872# ----------------------------------------------------------------------
873# USAGE: _fixResult
874#
875# Used internally to change the result page being displayed whenever
876# the user selects a page from the results combobox.
877# ----------------------------------------------------------------------
878itcl::body Rappture::Analyzer::_fixResult {} {
879    set name [$itk_component(resultselector) value]
880    set page ""
881    if {"" != $name} {
882        set page [$itk_component(resultselector) translate $name]
883    }
884    if {$page == "@download"} {
885        # put the combobox back to its last value
886        $itk_component(resultselector) component entry configure -state normal
887        $itk_component(resultselector) component entry delete 0 end
888        $itk_component(resultselector) component entry insert end $_lastlabel
889        $itk_component(resultselector) component entry configure -state disabled
890        # perform the actual download
891        download start $itk_component(download)
892    } elseif {$page == "---"} {
893        # put the combobox back to its last value
894        $itk_component(resultselector) component entry configure -state normal
895        $itk_component(resultselector) component entry delete 0 end
896        $itk_component(resultselector) component entry insert end $_lastlabel
897        $itk_component(resultselector) component entry configure -state disabled
898    } elseif {$page != ""} {
899        set _lastlabel $name
900        set win [winfo toplevel $itk_component(hull)]
901        blt::busy hold $win
902        $itk_component(resultpages) current $page
903
904        set f [$itk_component(resultpages) page $page]
905        $f.rviewer plot clear
906        eval $f.rviewer plot add $_plotlist
907        blt::busy release [winfo toplevel $itk_component(hull)]
908    }
909}
910
911# ----------------------------------------------------------------------
912# USAGE: _fixSize
913#
914# Used internally to change the size of the result set area whenever
915# a new control appears.  Adjusts the size available for the result
916# set up to some maximum.
917# ----------------------------------------------------------------------
918itcl::body Rappture::Analyzer::_fixSize {} {
919    set ht [winfo height $itk_component(results)]
920    if {$ht <= 1} { set ht [winfo reqheight $itk_component(results)] }
921    set cntlht [$itk_component(resultset) size -controlarea]
922    set frac [expr {double($cntlht)/$ht}]
923
924    if {$frac < 0.4} {
925        $itk_component(results) fraction end $frac
926    }
927    _fixSimControl
928}
929
930# ----------------------------------------------------------------------
931# USAGE: _simState <boolean> ?<message>? ?<settings>?
932#
933# Used internally to change the "Simulation" button on or off.
934# If the <boolean> is on, then any <message> and <settings> are
935# displayed as well.  If the <boolean> is off, then only display
936# the message. The <message> is a note to the user about
937# what will be simulated, and the <settings> are a list of
938# tool parameter settings of the form {path1 val1 path2 val2 ...}.
939# When these are in place, the next Simulate operation will use
940# these settings.  This helps fill in missing data values.
941# ----------------------------------------------------------------------
942itcl::body Rappture::Analyzer::_simState {state args} {
943    if {$state} {
944        $itk_interior.simol configure \
945            -background $itk_option(-simcontrolactiveoutline)
946        configure -simcontrolcolor $itk_option(-simcontrolactivebackground)
947
948        $itk_component(abort) configure -state disabled
949        $itk_component(simulate) configure -state normal \
950            -command [itcl::code $this simulate]
951
952        #
953        # If there's a special message, then put it up next to the button.
954        #
955        set mesg [lindex $args 0]
956        if {"" != $mesg} {
957            $itk_component(simstatus) configure -state normal
958            $itk_component(simstatus) delete 1.0 end
959            $itk_component(simstatus) insert end $mesg
960
961            #
962            # If there are any settings, then install them in the
963            # "Simulate" button.  Also, pop them up as a tooltip
964            # for the message.
965            #
966            set settings [lindex $args 1]
967            if {[llength $settings] > 0} {
968                $itk_component(simulate) configure \
969                    -command [eval itcl::code $this simulate $settings]
970
971                set details ""
972                foreach {path val} $settings {
973                    set str [$_tool xml get $path.about.label]
974                    if {"" == $str} {
9751                       set str [$_tool xml element -as id $path]
976                    }
977                    append details "$str = $val\n"
978                }
979                set details [string trim $details]
980
981                Rappture::Tooltip::for $itk_component(simstatus) $details
982                $itk_component(simstatus) insert end " "
983                $itk_component(simstatus) insert end "(details...)" popup
984            }
985            $itk_component(simstatus) configure -state disabled
986        }
987    } else {
988        if {"" != $itk_option(-simcontrolbackground)} {
989            set simcbg $itk_option(-simcontrolbackground)
990        } else {
991            set simcbg $itk_option(-background)
992        }
993        $itk_interior.simol configure \
994            -background $itk_option(-simcontroloutline)
995        configure -simcontrolcolor $simcbg
996
997        $itk_component(simulate) configure -state disabled
998        $itk_component(abort) configure -state normal
999
1000        $itk_component(simstatus) configure -state normal
1001        $itk_component(simstatus) delete 1.0 end
1002        set mesg [lindex $args 0]
1003        if {"" != $mesg} {
1004            $itk_component(simstatus) insert end $mesg
1005        }
1006        $itk_component(simstatus) configure -state disabled
1007    }
1008}
1009
1010# ----------------------------------------------------------------------
1011# USAGE: _simOutput <message>
1012#
1013# Invoked automatically whenever output comes in while running the
1014# tool.  Extracts any =RAPPTURE-???=> messages from the output and
1015# sends the output to the display.  For example, any
1016# =RAPPTURE-PROGRESS=> message pops up the progress meter and updates
1017# it to show the latest progress message.  This is useful for
1018# long-running tools, to let the user know how much longer the
1019# simulation will take.
1020# ----------------------------------------------------------------------
1021itcl::body Rappture::Analyzer::_simOutput {message} {
1022    #
1023    # Scan through and pick out any =RAPPTURE-PROGRESS=> messages first.
1024    #
1025    while {[regexp -indices \
1026               {=RAPPTURE-PROGRESS=> *([-+]?[0-9]+) +([^\n]*)(\n|$)} $message \
1027                match percent mesg]} {
1028
1029        foreach {i0 i1} $percent break
1030        set percent [string range $message $i0 $i1]
1031
1032        foreach {i0 i1} $mesg break
1033        set mesg [string range $message $i0 $i1]
1034
1035        pack $itk_component(progress) -fill x -padx 10 -pady 10
1036        $itk_component(progress) settings -percent $percent -message $mesg
1037
1038        foreach {i0 i1} $match break
1039        set message [string replace $message $i0 $i1]
1040    }
1041
1042    #
1043    # Break up the remaining lines according to =RAPPTURE-ERROR=> messages.
1044    # Show errors in a special color.
1045    #
1046    $itk_component(runinfo) configure -state normal
1047
1048    while {[regexp -indices \
1049               {=RAPPTURE-([a-zA-Z]+)=>([^\n]*)(\n|$)} $message \
1050                match type mesg]} {
1051
1052        foreach {i0 i1} $match break
1053        set first [string range $message 0 [expr {$i0-1}]]
1054        if {[string length $first] > 0} {
1055            $itk_component(runinfo) insert end $first
1056            $itk_component(runinfo) insert end \n
1057        }
1058
1059        foreach {t0 t1} $type break
1060        set type [string range $message $t0 $t1]
1061        foreach {m0 m1} $mesg break
1062        set mesg [string range $message $m0 $m1]
1063        if {[string length $mesg] > 0 && $type != "RUN"} {
1064            $itk_component(runinfo) insert end $mesg $type
1065            $itk_component(runinfo) insert end \n $type
1066        }
1067
1068        set message [string range $message [expr {$i1+1}] end]
1069    }
1070
1071    if {[string length $message] > 0} {
1072        $itk_component(runinfo) insert end $message
1073        if {[$itk_component(runinfo) get end-2char] != "\n"} {
1074            $itk_component(runinfo) insert end "\n"
1075        }
1076        $itk_component(runinfo) see end
1077    }
1078    $itk_component(runinfo) configure -state disabled
1079}
1080
1081# ----------------------------------------------------------------------
1082# USAGE: _resultTooltip
1083#
1084# Used internally to build the tooltip string displayed for the
1085# result selector.  If the current page has an associated description,
1086# then it is displayed beneath the result.
1087#
1088# Returns the string for the tooltip.
1089# ----------------------------------------------------------------------
1090itcl::body Rappture::Analyzer::_resultTooltip {} {
1091    set tip ""
1092    set name [$itk_component(resultselector) value]
1093    if {[info exists _label2desc($name)] &&
1094         [string length $_label2desc($name)] > 0} {
1095        append tip "$_label2desc($name)\n\n"
1096    }
1097    if {[array size _label2page] > 1} {
1098        append tip "Use this control to display other output results."
1099    }
1100    return $tip
1101}
1102
1103# ----------------------------------------------------------------------
1104# USAGE: _fixSimControl
1105#
1106# Used internally to add or remove the simulation control at the
1107# top of the analysis area.  This is controlled by the -simcontrol
1108# option.
1109# ----------------------------------------------------------------------
1110itcl::body Rappture::Analyzer::_fixSimControl {} {
1111    switch -- $itk_option(-simcontrol) {
1112        on {
1113            pack $itk_interior.simol -fill x -before $itk_interior.nb
1114        }
1115        off {
1116            pack forget $itk_interior.simol
1117        }
1118        auto {
1119            #
1120            # If we have two or more radiodials, then there is a
1121            # chance of encountering a combination of parameters
1122            # with no data, requiring simulation.
1123            #
1124            if {[$itk_component(resultset) size -controls] >= 2} {
1125                pack $itk_interior.simol -fill x -before $itk_interior.nb
1126            } else {
1127                pack forget $itk_interior.simol
1128            }
1129        }
1130        default {
1131            error "bad value \"$itk_option(-simcontrol)\": should be on, off, auto"
1132        }
1133    }
1134}
1135
1136# ----------------------------------------------------------------------
1137# USAGE: _fixNotebook
1138#
1139# Used internally to switch the active notebook page
1140# ----------------------------------------------------------------------
1141itcl::body Rappture::Analyzer::_fixNotebook {} {
1142    switch -- $itk_option(-notebookpage) {
1143        about {
1144            $itk_component(notebook) current about
1145        }
1146        simulate {
1147            $itk_component(notebook) current simulate
1148        }
1149        analyze {
1150            $itk_component(notebook) current analyze
1151        }
1152        default {
1153            error "bad value \"$itk_option(-notebookpage)\": should be about, simulate, analyze"
1154        }
1155    }
1156}
1157
1158# ----------------------------------------------------------------------
1159# USAGE: _isPdbTrajectory <data>
1160#
1161# Used internally to determine whether pdb or lammps data represents a
1162# trajectory rather than a single frame
1163# ----------------------------------------------------------------------
1164itcl::body Rappture::Analyzer::_isPdbTrajectory {data} {
1165    if { [llength $data]  == 0 } {
1166        return 0
1167    }
1168    set nModels 0
1169    foreach line $data {
1170        if { [string match "MODEL*" $line] }  {
1171            incr nModels
1172            if { $nModels > 1 } {
1173                # Stop if more than one model found.  No need to count them
1174                # all.
1175                return 1
1176            }
1177        }
1178    }
1179    return 0
1180}
1181
1182# ----------------------------------------------------------------------
1183# USAGE: _isLammpsTrajectory <data>
1184#
1185# Used internally to determine whether pdb or lammps data represents a
1186# trajectory rather than a single frame
1187# ----------------------------------------------------------------------
1188itcl::body Rappture::Analyzer::_isLammpsTrajectory { data } {
1189    if { [llength $data]  == 0 } {
1190        return 0
1191    }
1192    set nModels 0
1193    foreach line $data {
1194        if { [regexp {^[\t ]*ITEM:[ \t]+TIMESTEP} $line] } {
1195            incr nModels
1196            if { $nModels > 1 } {
1197                # Stop if more than one model found.  No need to count them
1198                # all.
1199                return 1
1200            }
1201        }
1202    }
1203    return 0
1204}
1205
1206# ----------------------------------------------------------------------
1207# USAGE: _trajtosequence <xmlobj> ?<path>?
1208#
1209    # If the molecule element is a trajectory, delete the original
1210    # and create a sequence of individual molecules.
1211# Used internally to detect any molecule output elements that contain
1212# trajectory data.  Trajectories will be converted into sequences of
1213# individual molecules.  All other elements will be unaffected. Scans
1214# the entire xml tree if a starting path is not specified.
1215# ----------------------------------------------------------------------
1216itcl::body Rappture::Analyzer::_pdbToSequence {xmlobj path id child data} {
1217
1218    set seqLabel [$xmlobj get ${child}.about.label]
1219    set descr    [$xmlobj get ${child}.about.description]
1220    set formula  [$xmlobj get ${child}.components.molecule.formula]
1221    $xmlobj remove $child
1222
1223    set seqPath  $path.sequence($id)
1224    $xmlobj put ${seqPath}.about.label $seqLabel
1225    $xmlobj put ${seqPath}.about.description $descr
1226    $xmlobj put ${seqPath}.index.label "Frame"
1227
1228    set frameNum 0
1229    set frameContents ""
1230    set inModel 0
1231    foreach line $data {
1232        set line [string trim $line]
1233        if { $line == "" } {
1234            continue;                   # Skip blank lines
1235        }
1236        if { [string match "MODEL*" $line] } {
1237            if { $inModel && $frameContents != "" } {
1238                # Dump the current contents into the last model
1239
1240                set framePath ${seqPath}.element($frameNum)
1241                $xmlobj put ${framePath}.index $frameNum
1242               
1243                set molPath ${framePath}.structure.components.molecule
1244                $xmlobj put ${molPath}.pdb $frameContents
1245                $xmlobj put ${molPath}.formula $formula
1246               
1247                incr frameNum
1248                set frameContents ""
1249            }
1250            set inModel 1
1251        } elseif {[string match "ATOM*" $line] } {
1252            if { !$inModel } {
1253                puts stderr "found \"$line\" without previous MODEL line"
1254                set inModel 1
1255            }
1256            append frameContents $line\n
1257        }
1258    }
1259    if { $frameContents != "" } {
1260        # Dump the current contents into the last model
1261
1262        set framePath ${seqPath}.element($frameNum)
1263        $xmlobj put ${framePath}.index $frameNum
1264       
1265        set molPath ${framePath}.structure.components.molecule
1266        $xmlobj put ${molPath}.pdb $frameContents
1267        $xmlobj put ${molPath}.formula $formula
1268    }
1269}
1270
1271itcl::body Rappture::Analyzer::_lammpsToSequence {xmlobj path id child data} {
1272
1273    set seqLabel [$xmlobj get ${child}.about.label]
1274    set descr    [$xmlobj get ${child}.about.description]
1275    set typemap  [$xmlobj get ${child}.components.molecule.lammpstypemap]
1276    $xmlobj remove $child
1277
1278    set seqPath ${path}.sequence($id)
1279    $xmlobj put ${seqPath}.about.label $seqLabel
1280    $xmlobj put ${seqPath}.about.description $descr
1281    $xmlobj put ${seqPath}.index.label "Frame"
1282
1283    set frameNum 0
1284    set frameContents ""
1285    set inModel 0
1286    foreach line $data {
1287        set line [string trim $line]
1288        if { $line == "" } {
1289            continue;                   # Skip blank lines
1290        }
1291        if {[regexp {^[\t ]*ITEM:[ \t]+ATOMS} $line] } {
1292            if { $inModel && $frameContents != "" } {
1293                set framePath ${seqPath}.element($frameNum)
1294                $xmlobj put ${framePath}.index $frameNum
1295               
1296                set molPath ${framePath}.structure.components.molecule
1297                $xmlobj put ${molPath}.lammps $frameContents
1298                $xmlobj put ${molPath}.lammpstypemap $typemap
1299               
1300                incr frameNum
1301                set frameContents ""
1302            }
1303            set inModel 1
1304        } elseif { [scan $line "%d %d %f %f %f" a b c d e] == 5 } {
1305            if { !$inModel } {
1306                puts stderr "found \"$line\" without previous \"ITEM: ATOMS\""
1307                set inModel 1
1308            }
1309            append frameContents $line\n
1310        }
1311    }
1312    if { $frameContents != "" } {
1313        set framePath ${seqPath}.element($frameNum)
1314        $xmlobj put ${framePath}.index $frameNum
1315       
1316        set molPath ${framePath}.structure.components.molecule
1317        $xmlobj put ${molPath}.lammps $frameContents
1318        $xmlobj put ${molPath}.lammpstypemap $typemap
1319    }
1320}
1321
1322# ----------------------------------------------------------------------
1323# USAGE: _trajtosequence <xmlobj> ?<path>?
1324#
1325#       Check for PDB and LAMMPS trajectories in molecule data and rewrite
1326#       the individual models as a sequence of molecules.  Used internally
1327#       to detect any molecule output elements that contain trajectory data.
1328#       Trajectories will be converted into sequences of individual molecules.
1329#       All other elements will be unaffected. Scans the entire xml tree if a
1330#       starting path is not specified. 
1331#
1332# ----------------------------------------------------------------------
1333itcl::body Rappture::Analyzer::_trajToSequence {xmlobj {path ""}} {
1334    puts stderr "path=$path"
1335    # Remove leading dot from path, if present.
1336    if { [string index $path 0] == "." } {
1337        set path [string range $path 1 end]
1338    }
1339    # Otherwise check each child.
1340    foreach child [$xmlobj children $path] {
1341        set current ${path}.${child}
1342        if { [string match "structure*" $child] } {
1343            # Look for trajectory if molecule element found.  Check both pdb
1344            # data and lammps data.
1345            set type [$xmlobj element -as type $current]
1346            set id   [$xmlobj element -as id $current]
1347            set pdbdata    [$xmlobj get ${current}.components.molecule.pdb]
1348            set lammpsdata [$xmlobj get ${current}.components.molecule.lammps]
1349            if { $pdbdata != "" && $lammpsdata != "" } {
1350                puts stderr \
1351                    "found both <pdb> and <lammps> elements: picking pdb"
1352            }
1353            set pdbdata [split $pdbdata \n]
1354            set lammpsdata [split $lammpsdata \n]
1355            if { [_isPdbTrajectory $pdbdata] } {
1356                _pdbToSequence $xmlobj $path $id $current $pdbdata
1357            } elseif { [_isLammpsTrajectory $lammpsdata] } {
1358                _lammpsToSequence $xmlobj $path $id $current $lammpsdata
1359            }
1360            continue
1361        }
1362        # Recurse over all child nodes.
1363        _trajToSequence $xmlobj $current
1364    }
1365}
1366
1367# ----------------------------------------------------------------------
1368# CONFIGURATION OPTION: -simcontrol
1369#
1370# Controls whether or not the Simulate button is showing.  In some
1371# cases, it is not needed.
1372# ----------------------------------------------------------------------
1373itcl::configbody Rappture::Analyzer::simcontrol {
1374    _fixSimControl
1375}
1376
1377# ----------------------------------------------------------------------
1378# CONFIGURATION OPTION: -notebookpage
1379#
1380# Controls which page of the analyzer notebook is shown. It is
1381# particularly needed when using rerun, when you don't want to
1382# "simulate -ifneeded" because an actual simulation might be
1383# kicked off due to differences between tool.xml and run.xml
1384# ----------------------------------------------------------------------
1385itcl::configbody Rappture::Analyzer::notebookpage {
1386    _fixNotebook
1387}
Note: See TracBrowser for help on using the repository browser.