Skip to content

Commit

Permalink
Add array_map specializer for demonstrating tree specializers; fix re…
Browse files Browse the repository at this point in the history
…cently introduced bugs in ast_tools using Scala nodes in C++ code by being explicit; clean up print output of Asp unit tests
  • Loading branch information
Derrick Coetzee committed Dec 10, 2012
1 parent a5a29ae commit f2b9fc1
Show file tree
Hide file tree
Showing 4 changed files with 82 additions and 0 deletions.
30 changes: 30 additions & 0 deletions specializers/array_map/array_map.py
@@ -0,0 +1,30 @@
# really dumb example of using tree transformations w/asp

class ArrayMap(object):

def __init__(self):
self.pure_python = True

def map_using_trees(self, arr):
import asp.codegen.templating.template as template
import inspect
import asp.codegen.python_ast as ast
import asp.codegen.ast_tools as ast_tools

src = inspect.getsource(self.operation)
operation_ast = ast.parse(src.lstrip())
return_ast = operation_ast.body[0]
expr_ast = return_ast.body[0].value
expr_cpp = ast_tools.ConvertAST().visit(expr_ast)

mytemplate = template.Template(filename="templates/map_template.mako", disable_unicode=True)
rendered = mytemplate.render(num_items=len(arr), expr=expr_cpp)

import asp.jit.asp_module as asp_module
mod = asp_module.ASPModule()
mod.add_function("map_in_c", rendered)
return mod.map_in_c(arr)

def map(self, arr):
for i in range(0, len(arr)):
arr[i] = self.operation(arr[i])
17 changes: 17 additions & 0 deletions specializers/array_map/run_tests.sh
@@ -0,0 +1,17 @@
#!/bin/bash

PYTHONPATH=../../:$PYTHONPATH

echo PYTHONPATH
echo ${PYTHONPATH}

if [ -z "${PYTHON}" ]
then
PYTHON=python
fi
if [ -z "${PYTHONARGS}" ]
then
PYTHONARGS=
fi

PYTHONPATH=`pwd`:${PYTHONPATH} ${PYTHON} ${PYTHONARGS} tests/arraymap_test.py
11 changes: 11 additions & 0 deletions specializers/array_map/templates/map_template.mako
@@ -0,0 +1,11 @@
using namespace boost::python;

void map_in_c(list arr)
{
for (int i=0; i < ${num_items}; i++)
{
double x = extract<double>(arr[i]);
x = ${expr};
arr[i] = x;
}
}
24 changes: 24 additions & 0 deletions specializers/array_map/tests/arraymap_test.py
@@ -0,0 +1,24 @@
import unittest

from array_map import *

class ArrayMapExample(ArrayMap):
def operation(self, x):
return 2*x+5

class BasicTests(unittest.TestCase):
def test_pure_python(self):
example = ArrayMapExample()
arr = [1.0, 2.0, 3.0, 4.0]
example.map(arr)
self.assertEquals(arr[0], 7.0)

def test_generated(self):
example = ArrayMapExample()
arr = [1.0, 2.0, 3.0, 4.0]
example.map_using_trees(arr)
self.assertEquals(arr[0], 7.0)


if __name__ == '__main__':
unittest.main()

0 comments on commit f2b9fc1

Please sign in to comment.