Ignore:
Timestamp:
Oct 14, 2005, 11:26:21 AM (19 years ago)
Author:
ole
Message:

Implemented arbitrary expressions for sww2dem using code from changeset:1916

File:
1 edited

Legend:

Unmodified
Added
Removed
  • inundation/pyvolution/util.py

    r1911 r1919  
    457457    sww.store_timestep('stage')
    458458
     459
     460
     461
     462
     463
     464
     465def apply_expression_to_dictionary(expression, _):
     466    """Apply arbitrary expression to values of dictionary _
     467
     468    expression: Arbitrary, e.g. arithmetric, expression relating keys
     469                from dictionary _. A key must not be the single character '_'
     470
     471    _: Dictionary of variable names used in expression and their
     472       corresponding values. The dictinary name is chosen as the
     473       inconspicuous symbol _ in order to avoid single letter variable
     474       to inabvertently substitute parts of the dictionary name
     475   
     476
     477    Given an expression in terms of the keys, replace key by the
     478    corresponding values and evaluate.
     479
     480    Values in dictionary must support operators given in expression
     481    e.g. by overloading
     482    """
     483
     484    #FIXME: Varibles may substitute into other variables e.g. x into xmomentum.
     485   
     486    import types
     487
     488    assert isinstance(expression, basestring)
     489    assert type(_) == types.DictType
     490
     491    #Replace key names with values
     492    for key in _.keys():
     493        msg = 'Key must not be the single character "_"'
     494        assert key != '_', msg
     495        expression = expression.replace(key,
     496                                        '_["%s"]' %key)
     497
     498
     499    #Evaluate and return
     500    try:
     501        return eval(expression)
     502    except NameError, e:
     503        msg = 'Expression "%s" could not be evaluated: %s' %(expression, e)
     504        raise NameError, msg
     505   
     506
     507
     508
     509
     510
     511
     512
    459513####################################################################
    460514#Python versions of function that are also implemented in util_gateway.c
Note: See TracChangeset for help on using the changeset viewer.