Created
March 12, 2013 03:59
-
-
Save jsofra/5140234 to your computer and use it in GitHub Desktop.
An example of using a LazyDist in Python to create a computation graph
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# the LazyDict implementation, callable values are evaluated before returning them | |
class LazyDict(dict): | |
def __getitem__(self, k): | |
val = dict.__getitem__(self, k) | |
if callable(val): | |
val = val() | |
self[k] = val | |
return val | |
# creates lambdas of all the dict entries | |
def compileGraph(inputs, graph): | |
compGraph = LazyDict(inputs) | |
for k, (fn, args) in graph.items(): | |
def constructLambda(): | |
fn_ = fn | |
args_ = args | |
compGraph[k] = lambda: fn_(*[compGraph[arg] for arg in args_]) | |
constructLambda() | |
return compGraph | |
# example usage, args is a dict of input arguments into the graph | |
def testCalc(args): | |
graph = {'windowSize': (windowSize, ('filterWidth')), | |
'terrainMask': (calcTerrainMask, ('topo')), | |
'composite': (compositeGrid, ('siteGrid', 'siteMask', 'neighbourGrid', 'noDataValue')), | |
'diffGrid': (greatestAbsDiffFilter, ('composite', 'windowSize')), | |
'thresholdedMask': (calcThresholdMask, ('diffGrid', 'terrainMask', 'thresholds')), | |
'aoiMask': (areaOfInterest, ('siteMask', 'otherSiteMasks', 'filterWidth')), | |
'borderPercentage': (borderPercentage, ('thresholdedMask', 'aoiMask')) | |
} | |
computationGraph = compileGraph(args, graph) | |
print "Border Percentage:", computationGraph['borderPercentage'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Anything with lazy in the name gets my vote