source: trunk/gui/scripts/analyzer.tcl @ 1831

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