diff --git a/lib/sympy_check/__init__.py b/lib/sympy_check/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/lib/sympy_check/formula.py b/lib/sympy_check/formula.py
new file mode 100644
index 0000000000..01ced8650c
--- /dev/null
+++ b/lib/sympy_check/formula.py
@@ -0,0 +1,461 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+#
+# File: formula.py
+# Date: 04-May-12
+# Author: I. Chuang Error %s in parsing OUR expected answer "%s"
' % (xs[1:-1]) # for sympy v6
+ return '[mathjax]%s[/mathjax]
' % (xs) # for sympy v7
+
+def my_evalf(expr,chop=False):
+ if type(expr)==list:
+ try:
+ return [x.evalf(chop=chop) for x in expr]
+ except:
+ return expr
+ try:
+ return expr.evalf(chop=chop)
+ except:
+ return expr
+
+#-----------------------------------------------------------------------------
+# my version of sympify to import expression into sympy
+
+def my_sympify(expr,normphase=False,matrix=False,abcsym=False,do_qubit=False,symtab=None):
+ # make all lowercase real?
+ if symtab:
+ varset = symtab
+ else:
+ varset = {'p':sympy.Symbol('p'),
+ 'g':sympy.Symbol('g'),
+ 'e':sympy.E, # for exp
+ 'i':sympy.I, # lowercase i is also sqrt(-1)
+ 'Q':sympy.Symbol('Q'), # otherwise it is a sympy "ask key"
+ #'X':sympy.sympify('Matrix([[0,1],[1,0]])'),
+ #'Y':sympy.sympify('Matrix([[0,-I],[I,0]])'),
+ #'Z':sympy.sympify('Matrix([[1,0],[0,-1]])'),
+ 'ZZ':sympy.Symbol('ZZ'), # otherwise it is the PythonIntegerRing
+ 'XI':sympy.Symbol('XI'), # otherwise it is the capital \XI
+ 'hat':sympy.Function('hat'), # for unit vectors (8.02)
+ }
+ if do_qubit: # turn qubit(...) into Qubit instance
+ varset.update({'qubit':sympy.physics.quantum.qubit.Qubit,
+ 'Ket':sympy.physics.quantum.state.Ket,
+ 'dot':dot,
+ 'bit':sympy.Function('bit'),
+ })
+ if abcsym: # consider all lowercase letters as real symbols, in the parsing
+ for letter in string.lowercase:
+ if letter in varset: # exclude those already done
+ continue
+ varset.update({letter:sympy.Symbol(letter,real=True)})
+
+ sexpr = sympify(expr,locals=varset)
+ if normphase: # remove overall phase if sexpr is a list
+ if type(sexpr)==list:
+ if sexpr[0].is_number:
+ ophase = sympy.sympify('exp(-I*arg(%s))' % sexpr[0])
+ sexpr = [ sympy.Mul(x,ophase) for x in sexpr ]
+
+ def to_matrix(x): # if x is a list of lists, and is rectangular, then return Matrix(x)
+ if not type(x)==list:
+ return x
+ for row in x:
+ if (not type(row)==list):
+ return x
+ rdim = len(x[0])
+ for row in x:
+ if not len(row)==rdim:
+ return x
+ return sympy.Matrix(x)
+
+ if matrix:
+ sexpr = to_matrix(sexpr)
+ return sexpr
+
+#-----------------------------------------------------------------------------
+# class for symbolic mathematical formulas
+
+class formula(object):
+ '''
+ Representation of a mathematical formula object. Accepts mathml math expression for constructing,
+ and can produce sympy translation. The formula may or may not include an assignment (=).
+ '''
+ def __init__(self,expr,asciimath=''):
+ self.expr = expr.strip()
+ self.asciimath = asciimath
+ self.the_cmathml = None
+ self.the_sympy = None
+
+ def is_presentation_mathml(self):
+ return 'Maxima Input Form
' in k:
+ mode = 0
+ continue
+ cmathml.append(k)
+ # return '\n'.join(cmathml)
+ cmathml = '\n'.join(cmathml[2:])
+ cmathml = ''
+ # print cmathml
+ #return unicode(cmathml)
+ return cmathml
+
+#-----------------------------------------------------------------------------
+
+def test1():
+ xmlstr = '''
+
+ '''
+ return formula(xmlstr)
+
+def test2():
+ xmlstr = u'''
+
+ '''
+ return formula(xmlstr)
+
+def test3():
+ xmlstr = '''
+
+ '''
+ return formula(xmlstr)
+
+def test4():
+ xmlstr = u'''
+
+'''
+ return formula(xmlstr)
diff --git a/lib/sympy_check/sympy_check2.py b/lib/sympy_check/sympy_check2.py
new file mode 100644
index 0000000000..abb70ed165
--- /dev/null
+++ b/lib/sympy_check/sympy_check2.py
@@ -0,0 +1,271 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+#
+# File: sympy_check2.py
+# Date: 02-May-12
+# Author: I. Chuang
Failed in evaluating check(%s,%s)' % (err,expect,ans)
+ }
+ return ret
+
+#-----------------------------------------------------------------------------
+# pretty generic checking function
+
+def check(expect,given,numerical=False,matrix=False,normphase=False,abcsym=False,do_qubit=True,symtab=None,dosimplify=False):
+ """
+ Returns dict with
+
+ 'ok': True if check is good, False otherwise
+ 'msg': response message (in HTML)
+
+ "expect" may have multiple possible acceptable answers, separated by "__OR__"
+
+ """
+
+ if "__or__" in expect: # if multiple acceptable answers
+ eset = expect.split('__or__') # then see if any match
+ for eone in eset:
+ ret = check(eone,given,numerical,matrix,normphase,abcsym,do_qubit,symtab,dosimplify)
+ if ret['ok']:
+ return ret
+ return ret
+
+ flags = {}
+ if "__autonorm__" in expect:
+ flags['autonorm']=True
+ expect = expect.replace('__autonorm__','')
+ matrix = True
+
+ threshold = 1.0e-3
+ if "__threshold__" in expect:
+ (expect,st) = expect.split('__threshold__')
+ threshold = float(st)
+ numerical=True
+
+ if str(given)=='' and not (str(expect)==''):
+ return {'ok': False, 'msg': ''}
+
+ try:
+ xgiven = my_sympify(given,normphase,matrix,do_qubit=do_qubit,abcsym=abcsym,symtab=symtab)
+ except Exception,err:
+ return {'ok': False,'msg': 'Error %s
in evaluating your expression "%s"' % (err,given)}
+
+ try:
+ xexpect = my_sympify(expect,normphase,matrix,do_qubit=do_qubit,abcsym=abcsym,symtab=symtab)
+ except Exception,err:
+ return {'ok': False,'msg': 'Error %s
in evaluating OUR expression "%s"' % (err,expect)}
+
+ if 'autonorm' in flags: # normalize trace of matrices
+ try:
+ xgiven /= xgiven.trace()
+ except Exception, err:
+ return {'ok': False,'msg': 'Error %s
in normalizing trace of your expression %s' % (err,to_latex(xgiven))}
+ try:
+ xexpect /= xexpect.trace()
+ except Exception, err:
+ return {'ok': False,'msg': 'Error %s
in normalizing trace of OUR expression %s' % (err,to_latex(xexpect))}
+
+ msg = 'Your expression was evaluated as ' + to_latex(xgiven)
+ # msg += '
Expected ' + to_latex(xexpect)
+
+ # msg += "
flags=%s" % flags
+
+ if matrix and numerical:
+ xgiven = my_evalf(xgiven,chop=True)
+ dm = my_evalf(sympy.Matrix(xexpect)-sympy.Matrix(xgiven),chop=True)
+ msg += " = " + to_latex(xgiven)
+ if abs(dm.vec().norm().evalf())
You entered: %s
' % to_latex(fans) + return {'ok':True,'msg':msg} + + # convert mathml answer to formula + mmlbox = abname+'_fromjs' + if mmlbox in adict: + mmlans = adict[mmlbox] + f = formula(mmlans) + + # get sympy representation of the formula + # if DEBUG: msg += ' mmlans=%s' % repr(mmlans).replace('<','<') + try: + fsym = f.sympy + msg += 'You entered: %s
' % to_latex(f.sympy) + except Exception,err: + msg += "Error %s in converting to sympy
" % str(err).replace('<','<') + if DEBUG: msg += "%s" % traceback.format_exc() + return {'ok':False,'msg':msg} + + # compare with expected + if fexpect.is_number: + if fsym.is_number: + if abs(abs(fsym-fexpect)/fexpect)
given = %s
" % repr(ans) + msg += "fsym = %s
" % repr(fsym) + # msg += "cmathml =
%s" % str(f.cmathml).replace('<','<') + return {'ok':False,'msg':msg} + + if fexpect==fsym: + return {'ok':True,'msg':msg} + + if type(fexpect)==list: + try: + xgiven = my_evalf(fsym,chop=True) + dm = my_evalf(sympy.Matrix(fexpect)-sympy.Matrix(xgiven),chop=True) + if abs(dm.vec().norm().evalf())
%s" % traceback.format_exc() + return {'ok':False,'msg':msg} + + #diff = (fexpect-fsym).simplify() + #fsym = fsym.simplify() + #fexpect = fexpect.simplify() + try: + diff = (fexpect-fsym) + except Exception,err: + diff = None + + if DEBUG: + msg += "
Got: %s
" % repr(fsym) + # msg += "Got: %s" % str([type(x) for x in fsym.atoms()]).replace('<','<') + msg += "Expecting: %s
" % repr(fexpect).replace('**','^').replace('hat(I)','hat(i)') + # msg += "Expecting: %s" % str([type(x) for x in fexpect.atoms()]).replace('<','<') + if diff: + msg += "Difference: %s
" % to_latex(diff) + + return {'ok':False,'msg':msg,'ex':fexpect,'got':fsym} + +def sctest1(): + x = "1/2*(1+(k_e* Q* q)/(m *g *h^2))" + y = ''' + +'''.strip() + z = "1/2(1+(k_e* Q* q)/(m *g *h^2))" + r = sympy_check2(x,z,{'a':z,'a_fromjs':y},'a') + return r +