ultraparse.py 19.3 KB
Newer Older
1 2
import os, sys, inspect

3 4 5 6 7
try:
    import pyparsing
except:
    raise VisItException("LoadUltra requires PyParsing to be installed in python's site-packages.")

8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
#make the ultrawrapper modules available for import
sys.path.append(os.path.dirname(os.path.realpath(inspect.getfile(inspect.currentframe()))))

from UltraCurve import *
from UltraGrammar import *


class UltraQuit(object):
    """ a class to hold ultra's exit status """

    def __init__(self):
        self.timeToQuit = 0

#-----------------------------------------------------------------------------
# convenience methods 
#-----------------------------------------------------------------------------
def getShownPlots():
    rv = ()
    pl = GetPlotList()
    for i in range(GetNumPlots()):
        if not pl.GetPlots(i).hiddenFlag:
           rv += i,
    return rv

def getHiddenPlots():
    rv = ()
    pl = GetPlotList()
    for i in range(GetNumPlots()):
        if pl.GetPlots(i).hiddenFlag:
           rv += i,
    return rv

def makeAllPlotsActive():
    ap = ()
    for i in range(GetNumPlots()):
        ap += i, 
    SetActivePlots(ap)

def setAsActivePlot(curvePlotId):
    pl = GetPlotList()
    for i in range(GetNumPlots()):
        if pl.GetPlots(i).id == curvePlotId:
            SetActivePlots(i)
            return i
    return -1
  
def delAllExpr(curve):
    for i in range(len(curve.expressions)):
        DeleteExpression(curve.expressions[i])

def getBoxOperatorId(id):
    plot = GetPlotList().GetPlots(id)
    for i in range(len(plot.operatorNames)):
        if (plot.operatorNames[i] == "Box"):
            return i
    return -1

65 66 67 68 69 70 71
#-----------------------------------------------------------------------------
# Creates cmfe with the 2 curves (c1 being the 'active db')
#
# Modifications:
#   Kathleen Bonnell, Tue Feb 22 15:45:58 PST 2011
#   Take into account expressions attached to the curve
#-----------------------------------------------------------------------------
72 73

def createCurveCMFE(c1, c2):
74 75
    var1 = "<%s>" % c1.getUseVar()
    var2 = "<%s:%s>" % (c2.fileName, c2.getUseVar()) 
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
    cmfe = "curve_cmfe(%s,%s)" % (var2, var1)
    return cmfe

    
def toggleToInt(t):
    if t == "off":
        return 0
    else:
        return 1
            
#-----------------------------------------------------------------------------
# Some globals
#-----------------------------------------------------------------------------

menuList     = CurveList()
selectedList = CurveList()

quitTime = UltraQuit()

openedDBList = []

plotHiddenState = []

#-----------------------------------------------------------------------------
# parse actions 
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Read in curves 
#-----------------------------------------------------------------------------

def ultra_rd(s):
    t = LongFileName(s)
    md = GetMetaData(t)
    for i in range (md.GetNumCurves()):
        c = md.GetCurves(i)
        e = c.minSpatialExtents, c.maxSpatialExtents, \
            c.minDataExtents, c.maxDataExtents
        curve = MenuCurveItem(c.name, e, t)
        menuList.add(curve)

#-----------------------------------------------------------------------------
# handle file ops 
#-----------------------------------------------------------------------------

def ultra_file(t):
    if t.cmd == 'rd':
        ultra_rd(t.path)

#-----------------------------------------------------------------------------
# Handle singleton ops, like 'menu' and 'lst' 
#-----------------------------------------------------------------------------

def ultra_singleton(t):
    if t.cmd == 'menu' and menuList.curves != []:
        print menuList 
    elif t.cmd == 'lst' and selectedList.curves != []:
        print selectedList
    elif t.cmd == 'erase' and selectedList.curves != []:
        DeleteAllPlots() 
        for curve in selectedList.curves:
            delAllExpr(curve)
        selectedList.removeAll()
    elif (t.cmd == 'quit') or (t.cmd == 'end'):
        DeleteAllPlots()
        for curve in selectedList.curves:
            delAllExpr(curve)
        selectedList.removeAll()
        menuList.removeAll()
        quitTime.timeToQuit = 1

def createAndApplyExpression(curve, expDef, cmd):
    numE = len(curve.expressions)
    newvarName = "%s_%02d" % (curve.id, numE)
    DefineCurveExpression(newvarName, expDef)
    curve.expressions.append(newvarName)
    ChangeActivePlotsVar(newvarName)
    ResetView()
    SuppressQueryOutputOn()
    Query("SpatialExtents", "actual")
    curve.extents = GetQueryOutputValue()

#-----------------------------------------------------------------------------
# Handle regular math ops
159 160 161 162
#
# Modifications:
#   Kathleen Bonnell, Tue Feb 22 16:36:52 PST 2011
#   Make use of new curve method 'getUseVar'
163 164 165 166 167 168 169 170
#-----------------------------------------------------------------------------
def ultra_doOp_percurve(curve, t):
    currentPlot = setAsActivePlot(curve.plotId)
    if (currentPlot == -1):
        return 

    curve.modified = True

171
    usevar = "<%s>"%curve.getUseVar()
172
    if t.cmd in mathOpsNoArg:
173
        newvarDef = "%s(%s)" % (t.cmd, usevar)
174 175
        if t.cmd == "ln" or t.cmd == "log10":
            newvarDef = "%s(%s, -1.0e38)" % (t.cmd, usevar)
176 177 178 179
        createAndApplyExpression(curve, newvarDef, t.cmd)

    elif t.cmd in mathOpsXNoArg:
        usecmd = mathOpsNoArg[mathOpsXNoArg.index(t.cmd)]
180
        newvarDef = "curve_domain(%s, %s(coord(%s)[0]))"  % \
181
                                 (usevar, usecmd, usevar)
182 183 184
        if usecmd == "ln" or t.cmd == "log10":
            newvarDef = "curve_domain(%s, %s(coord(%s)[0], -1.0e38))"  % \
                                 (usevar, usecmd, usevar)
185
        createAndApplyExpression(curve, newvarDef, t.cmd)
186
        ResetView()
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240


    elif t.cmd == 'ymin' or t.cmd == 'xmin':
        # need to make 'curve' the active plot
        currentPlot = setAsActivePlot(curve.plotId)
        # need to find out if 'box' has already been applied
        # and use its attributes instead of default to start
        boxId = getBoxOperatorId(currentPlot)
        if boxId == -1:
            AddOperator("Box")
            boxAtts = BoxAttributes()
            if t.cmd == 'ymin':
                boxAtts.minx = curve.extents[0]
            else :
                boxAtts.miny = curve.extents[2]
            boxAtts.maxx = curve.extents[1]
            boxAtts.maxy = curve.extents[3]
        else:
            boxAtts = GetOperatorOptions(boxId)
        if t.cmd == 'ymin':
            boxAtts.miny = float(t.arg)
        else: 
            boxAtts.minx = float(t.arg)
        SetOperatorOptions(boxAtts)
        ResetView() 

    elif t.cmd == 'ymax' or t.cmd == 'xmax':
        currentPlot = setAsActivePlot(curve.plotId)
        if (currentPlot == -1):
            return 
        # need to find out if 'box' has already been applied
        # and use its attributes instead of default to start
        boxId = getBoxOperatorId(currentPlot)
        if boxId == -1:
            AddOperator("Box")
            boxAtts = BoxAttributes()
            boxAtts.minx = curve.extents[0]
            boxAtts.miny = curve.extents[2]
            if t.cmd == 'ymax':
                boxAtts.maxx = curve.extents[1]
            else:
                boxAtts.maxy = curve.extents[3]
        else:
            boxAtts = GetOperatorOptions(boxId)
        if t.cmd == 'ymax':
            boxAtts.maxy = float(t.arg)
        else:
            boxAtts.maxx = float(t.arg)
        SetOperatorOptions(boxAtts)
        ResetView() 

    elif t.cmd in mathOpsArg:
        newvarDef = ""
        op = ""
241
        secondVar = t.arg
242 243 244 245 246 247
        if t.cmd == 'divy':
            op = "/"
        elif t.cmd == 'dy':
            op = "+"
        elif t.cmd == 'my':
            op = "*"
248 249 250 251 252 253
        elif t.cmd == 'powr':
            op = "^"
        elif t.cmd == 'powa':
            op = "^"
            secondVar = usevar
            usevar = t.arg
254 255
        else:
            return 
256
        newvarDef = "%s %s %s" % (usevar, op, secondVar)
257 258 259 260 261
        createAndApplyExpression(curve, newvarDef, t.cmd)

    elif t.cmd in mathOpsXArg:
        newvarDef = ""
        op = ""
262
        secondVar = t.arg
263 264 265 266 267 268
        if t.cmd == 'divx':
            op = "/"
        elif t.cmd == 'dx':
            op = "+"
        elif t.cmd == 'mx':
            op = "*"
269 270 271 272 273 274
        elif t.cmd == 'powrx':
            op = "^"
        elif t.cmd == 'powax':
            op = "^"
            secondVar = usevar
            usevar = t.arg
275 276
        else:
            return 
277 278
        newvarDef = "curve_domain(%s, coord(%s)[0] %s %s)" % \
                                 (usevar, usevar, op, secondVar)
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
        createAndApplyExpression(curve, newvarDef, t.cmd)

    elif t.cmd == 'lnwidth':
        currentPlot = setAsActivePlot(curve.plotId)
        if (currentPlot == -1):
            return 
        ca = CurveAttributes(1)
        ca.lineWidth = int(t.arg)
        SetPlotOptions(ca)
    elif t.cmd == 'lnstyle':
        currentPlot = setAsActivePlot(curve.plotId)
        if (currentPlot == -1):
            return 
        ca = CurveAttributes(1)
        if (t.arg == "solid"):
            ca.lineStyle = ca.SOLID
        elif (t.arg == "dotted"):
            ca.lineStyle = ca.DOT
        elif (t.arg == "dashed"):
            ca.lineStyle = ca.DASH
        elif (t.arg == "dotdashed"):
            ca.lineStyle = ca.DOTDASH
        SetPlotOptions(ca)

#-----------------------------------------------------------------------------
# Handle math ops requiring cmfe's
305 306 307 308 309 310 311
#
# Modifications:
#   Kathleen Bonnell, Tue Feb 22 14:56:42 PST 2011
#   Activate the DB of the first curve, as it is the base for the cmfe.
#   Stop processing if AddPlot returns an error. 
#   Take into acount expressions that have been applied to a curve.
# 
312 313 314 315 316 317
#-----------------------------------------------------------------------------
def ultra_docmfemath(cl, t):
    if len(cl) < 2:
        print "Usage error: %s curve-list" % t.cmd
        return 
    curve1 = cl[0]
318 319 320
    # when building the cmfe, we want the first curve to be the active DB
    ActivateDatabase(curve1.fileName)
    fullExpression = "<%s>" % curve1.getUseVar()
321 322 323 324
    exprName = "%s" % curve1.id
    for i in range(1, len(cl)):
        curve = cl[i]
        exprName += "%s%s" % (t.cmd, curve.id)
325
        if (curve.getUseVar() not in  curve.expressions):
326 327
            cmfe = createCurveCMFE(curve1, curve)
        else:
328
            cmfe = "<%s>" % curve.getUseVar()
329 330 331 332
        fullExpression += " %s %s" %(t.cmd, cmfe)
    DefineCurveExpression(exprName, fullExpression)
    newCurve = PlotCurveItem(exprName)
    newCurve.expressions.append(exprName)
333 334 335
    # don't want to do anything more if AddPlot returns an error
    if not AddPlot("Curve", newCurve.var):
        return
336 337 338 339 340 341 342 343 344 345 346 347 348 349
    n = GetNumPlots()
    newCurve.plotId = GetPlotList().GetPlots(n-1).id
    selectedList.add(newCurve)
    ca = CurveAttributes(1)
    ca.designator = newCurve.id
    SetPlotOptions(ca)
    DrawPlots()
    SuppressQueryOutputOn()
    Query("SpatialExtents", "actual")
    newCurve.extents = GetQueryOutputValue()


#-----------------------------------------------------------------------------
# Handle ops on Menu curves
350 351 352 353 354
#
# Modifications:
#   Kathleen Bonnell, Tue Feb 22 15:04:37 PST 2011
#   Ensure the selected curve's DB is active (if not in need of opening).
#
355 356 357 358 359 360 361 362 363
#-----------------------------------------------------------------------------

def ultra_multiCurveNum(t):
    if t.cmd == 'select' and menuList.curves != []: 
        cl =  menuList.slice(t.clist)
        for curve in cl:
            if not curve.fileName in openedDBList:
                openedDBList.append(curve.fileName)
                OpenDatabase(curve.fileName)
364 365
            else:
                ActivateDatabase(curve.fileName)
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
            AddPlot("Curve", curve.var)
            n = GetNumPlots()
            c2 = PlotCurveItem(curve.var, curve.extents, curve.fileName)
            c2.plotId = GetPlotList().GetPlots(n-1).id
            selectedList.add(c2)
            ca = CurveAttributes(1)
            ca.designator = c2.id
            SetPlotOptions(ca)
        DrawPlots()


#-----------------------------------------------------------------------------
# Ops on selected (plotted) curves 
#-----------------------------------------------------------------------------

def ultra_multiCurveAlpha(t):
    if len(selectedList.curves) == 0:
        return 

    cl =  selectedList.slice(t.clist)
    if  len(cl) == 0:
        return

    if t.cmd == 'del':
        for curve in cl:
            selectedList.remove(curve)
            if setAsActivePlot(curve.plotId) >= 0:
                DeleteActivePlots()
            delAllExpr(curve)
    elif t.cmd in mathOpsNoArg:
        for curve in cl:
            ultra_doOp_percurve(curve, t) 
    elif t.cmd in mathOpsXNoArg:
        for curve in cl:
            ultra_doOp_percurve(curve, t) 
    elif t.cmd in cmfeOps:
        ultra_docmfemath(cl, t)
403
    elif t.cmd in mathOpsArg or t.cmd in mathOpsXArg:
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
        if not t.arg:
            UltraUsage(cmd)
        else:
            for curve in cl:
                ultra_doOp_percurve(curve, t)
    elif t.cmd in opsArg or t.cmd == "lnstyle":
        if not t.arg:
            UltraUsage(cmd)
        else:
            for curve in cl:
                ultra_doOp_percurve(curve, t)

#-----------------------------------------------------------------------------
# Plot control operations 
#-----------------------------------------------------------------------------
def ultra_plotControl_toggleOps(t):

    if t.cmd == "axis":
        a = GetAnnotationAttributes()
        if not t.arg:
            print "  %d" % a.axes2D.visible
        elif t.arg == "on" or t.arg == "off":
            a.axes2D.visible = toggleToInt(t.arg)
            SetAnnotationAttributes(a)

    elif t.cmd == "grid":
        a = GetAnnotationAttributes()
        if not t.arg:
            print "  %d" % a.axes2D.xAxis.grid 
        elif t.arg == "on" or t.arg == "off":
            a.axes2D.xAxis.grid = toggleToInt(t.arg)
            a.axes2D.yAxis.grid = toggleToInt(t.arg)
            SetAnnotationAttributes(a)

    elif t.cmd == "x-log-scale":
        v = GetViewCurve()
        if not t.arg:
            print "  %d" % v.domainScale
        elif t.arg == "on":
            v.domainScale = v.LOG
            SetViewCurve(v)
        elif t.arg == "off":
            v.domainScale = v.LINEAR
            SetViewCurve(v)

    elif t.cmd == "y-log-scale":
        v = GetViewCurve()
        if not t.arg:
            print "  %d" % v.rangeScale
        elif t.arg == "on":
            v.rangeScale = v.LOG
            SetViewCurve(v)
        elif t.arg == "off":
            v.rangeScale = v.LINEAR
            SetViewCurve(v)

    elif t.cmd == "data-id":
        if not t.arg:
            print "  %d" % selectedList.__class__.data_id
            return
        elif t.arg != "on" and t.arg != "off":
            return

        tval = toggleToInt(t.arg)
        selectedList.__class__.data_id = tval
        # first want to hide all plots, modify the curve atts for all
        # plots (individually so as to only overwrite the 'showLabels' att),
        # then unhide them.  However, we need to take into account the fact
        # that some plots may already be hidden.  

        # get a list of visible plots
        shownPlots = getShownPlots()
        SetActivePlots(shownPlots)

        # this toggles the 'hidden' state, as we are only applying it
        # to shown plots, they will now be hidden.
        HideActivePlots()
        for i in range(GetNumPlots()):
           SetActivePlots(i)
           ca = CurveAttributes(1)
           ca.showLabels = tval
           SetPlotOptions(ca)
        SetActivePlots(shownPlots)
        # toggle back to 'on' the hidden state of the previously shown plots
        HideActivePlots()

def ultra_plotControl_rangeOps(t):
    if not t.arg:
        return

    elif t.cmd == "domain":
        v = GetViewCurve()
        if t.arg == "de":
           # keep range as it is, but reset domain
           r = v.rangeCoords
           shownPlots = getShownPlots()
           SetActivePlots(shownPlots)
           HideActivePlots()
           ResetView()
           v = GetViewCurve()
           v.rangeCoords = r
           SetViewCurve(v)
           HideActivePlots()
        elif len(t.arg) == 2:
           v.domainCoords = (t.arg[0], t.arg[1])
           SetViewCurve(v)
    elif t.cmd == "range":
        v = GetViewCurve()
        if t.arg == "de":
           # keep domain as it is, but reset domain
           d = v.domainCoords
           shownPlots = getShownPlots()
           SetActivePlots(shownPlots)
           HideActivePlots()
           ResetView()
           v = GetViewCurve()
           v.domainCoords = d
           SetViewCurve(v)
           HideActivePlots()
        elif len(t.arg) == 2:
            v.rangeCoords = (t.arg[0], t.arg[1])
            SetViewCurve(v)
        

def ultra_plotControl(t):
    if t.cmd in togglePlotOps:
        ultra_plotControl_toggleOps(t) 
    elif t.cmd in rangePlotOps:
        ultra_plotControl_rangeOps(t)

#-----------------------------------------------------------------------------
# Write out curves to ultra files
#-----------------------------------------------------------------------------
           
def ultra_saveCurve(t):
539 540 541 542
    # type not currently supported, always saves as ascii
    #stype = "ascii"
    #if t.type:
    #    stype = t.type
543 544 545 546 547 548 549 550 551 552 553
    if len(selectedList.curves) == 0:
        return 
    cl =  selectedList.slice(t.clist)
    if  len(cl) == 0:
        return
   
    FILE = open(t.file, "w") 
    for curve in cl:
        currentPlot = setAsActivePlot(curve.plotId)
        if (currentPlot != -1):
            # This is how we need to do it for VisIt 2.0
554
            s = GetPlotInformation()['Curve']
555 556 557 558 559 560 561
            FILE.write("# %s\n"%curve.var) 
            for i in range(0, len(s), 2):
                FILE.write("%13.6e %13.6e\n"%(s[i], s[i+1]))
    FILE.close()

#-----------------------------------------------------------------------------
# Execution of wrapper
562 563 564 565
#
# Modifications:
#   Kathleen Bonnell, Tue Feb 22 14:56:42 PST 2011
#   Remove exception from message printed on error. 
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
#-----------------------------------------------------------------------------
def runUltraWrapper():
    quitTime.timeToQuit = 0

    #define parse actions for grammar

    singletonCommand.setParseAction(lambda t: ultra_singleton(t))
    fileOp.setParseAction(lambda t: ultra_file(t))
    multiCurveOpNum.setParseAction(lambda t: ultra_multiCurveNum(t))
    multiCurveOpAlpha.setParseAction(lambda t: ultra_multiCurveAlpha(t))
    lnstylecmd.setParseAction(lambda t: ultra_multiCurveAlpha(t))
    plotOp.setParseAction(lambda t: ultra_plotControl(t))
    saveCmd.setParseAction(lambda t: ultra_saveCurve(t))
    helpCmd.setParseAction(lambda t: UltraHelp(t.arg)) 

    while True:
        if quitTime.timeToQuit == 1:
            break
        if (GetUltraScript() != ""):
            cmd = "runscript %s" %GetUltraScript()
            SetUltraScript("")
        else: 
            cmd = raw_input('U-> ')
589 590 591 592 593 594 595 596
        
        if cmd != '': 
            if cmd.split()[0] == 'runscript':
                ultrascript.parseFile(cmd.split()[1])
                continue
            try:
                ulRes = ultracommand.parseString(cmd)
            except ParseException, err: 
597 598 599
                # the actual exception is not useful for users 
                #print 'Exception (%s) while parsing command: %s' %(err,cmd)
                print 'Exception while parsing command: %s' %(cmd)
600 601
                UltraUsage(cmd.split()[0])
                continue
602 603 604 605 606




runUltraWrapper()