def test_FunctionWrapper(): import sympy n, m, theta, phi = sympy.symbols("n, m, theta, phi") r = sympy.Ynm(n, m, theta, phi) s = Integer(2)*r assert isinstance(s, Mul) assert isinstance(s.args[1]._sympy_(), sympy.Ynm) x = symbols("x") e = x + sympy.loggamma(x) assert str(e) == "x + loggamma(x)" assert isinstance(e, Add) assert e + sympy.loggamma(x) == x + 2*sympy.loggamma(x) f = e.subs({x : 10}) assert f == 10 + log(362880) f = e.subs({x : 2}) assert f == 2 f = e.subs({x : 100}); v = f.n(53, real=True); assert abs(float(v) - 459.13420537) < 1e-7 f = e.diff(x) assert f == 1 + sympy.polygamma(0, x)
def run_benchmark(n): a0 = symbols("a0") a1 = symbols("a1") e = a0 + a1 f = 0; for i in range(2, n): s = symbols("a%s" % i) e = e + sin(s) f = f + sin(s) f = -f t1 = clock() e = expand(e**2) e = e.xreplace({a0: f}) e = expand(e) t2 = clock() print("%s ms" % (1000 * (t2 - t1)))
def run_benchmark(n): x, y = symbols("x y") e = (1 + sqrt(3) * x + sqrt(5) * y) ** n f = e * (e + sqrt(7)) t1 = clock() f = expand(f) t2 = clock() print("%s ms" % (1000 * (t2 - t1)))
def test_DenseMatrix_symbols(): x, y, z = symbols("x y z") D = DenseMatrix(4, 4, [1, 0, 1, 0, 0, z, y, 0, z, 1, x, 1, 1, 1, 0, 0]) assert D.get(1, 2) == y
def _get_array(): X, Y, Z = inp = array.array('d', [1, 2, 3]) args = x, y, z = se.symbols('x y z') exprs = [x+y+z, se.sin(x)*se.log(y)*se.exp(z)] ref = [X+Y+Z, math.sin(X)*math.log(Y)*math.exp(Z)] def check(arr): assert all([abs(x1-x2) < 1e-13 for x1, x2 in zip(ref, arr)]) return args, exprs, inp, check
def test_excessive_args(): if not HAVE_NUMPY: # nosetests work-around return x = se.symbols('x') lmb = se.Lambdify([x], [-x]) inp = np.ones(2) out = lmb(inp) assert np.allclose(inp, [1, 1]) assert len(out) == 2 # broad casting assert np.allclose(out, -1)
def test_Lambdify_LLVM(): n = 7 args = x, y, z = se.symbols('x y z') if not se.have_llvm: raises(ValueError, lambda: se.Lambdify(args, [x+y+z, x**2, (x-y)/z, x*y*z], backend='llvm')) return l = se.Lambdify(args, [x+y+z, x**2, (x-y)/z, x*y*z], backend='llvm') assert allclose(l(range(n, n+len(args))), [3*n+3, n**2, -1/(n+2), n*(n+1)*(n+2)])
def test_broadcast(): if not HAVE_NUMPY: # nosetests work-around return a = np.linspace(-np.pi, np.pi) inp = np.vstack((np.cos(a), np.sin(a))).T # 50 rows 2 cols x, y = se.symbols('x y') distance = se.Lambdify([x, y], [se.sqrt(x**2 + y**2)]) assert np.allclose(distance([inp[0, 0], inp[0, 1]]), [1]) dists = distance(inp) assert dists.shape == (50, 1) assert np.allclose(dists, 1)
def test_jacobian(): x, y, z, t = symbols("x y z t") J_correct = DenseMatrix(4, 4, [1, 0, 1, 0, 0, z, y, 0, z, 1, x, 1, 1, 1, 0, 0]) D = DenseMatrix(4, 1, [x+z, y*z, z*x+y+t, x+y]) x = DenseMatrix(4, 1, [x, y, z, t]) J = D.jacobian(x) assert J == J_correct
def test_excessive_out(): if not HAVE_NUMPY: # nosetests work-around return x = se.symbols('x') lmb = se.Lambdify([x], [-x]) inp = np.ones(1) out = np.ones(2) out = lmb(inp, out) assert np.allclose(inp, [1, 1]) assert out.shape == (2,) assert out[0] == -1 assert out[1] == 1
def test_jacobian(): if not HAVE_NUMPY: # nosetests work-around return x, y = se.symbols('x, y') args = se.DenseMatrix(2, 1, [x, y]) v = se.DenseMatrix(2, 1, [x**3 * y, (x+1)*(y+1)]) jac = v.jacobian(args) lmb = se.Lambdify(args, jac) out = np.empty((2, 2)) inp = X, Y = 7, 11 lmb(inp, out) assert np.allclose(out, [[3 * X**2 * Y, X**3], [Y + 1, X + 1]])
def test_broadcast_multiple_extra_dimensions(): if not HAVE_NUMPY: # nosetests work-around return inp = np.arange(12.).reshape((4, 3, 1)) x = se.symbols('x') cb = se.Lambdify([x], [x**2, x**3]) assert np.allclose(cb([inp[0, 2]]), [4, 8]) out = cb(inp) assert out.shape == (4, 3, 2) assert abs(out[2, 1, 0] - 7**2) < 1e-14 assert abs(out[2, 1, 1] - 7**3) < 1e-14 assert abs(out[-1, -1, 0] - 11**2) < 1e-14 assert abs(out[-1, -1, 1] - 11**3) < 1e-14
def _get_2_to_2by2_numpy(): args = x, y = se.symbols('x y') exprs = np.array([[x+y+1.0, x*y], [x/y, x**y]]) l = se.Lambdify(args, exprs) def check(A, inp): X, Y = inp assert abs(A[0, 0] - (X+Y+1.0)) < 1e-15 assert abs(A[0, 1] - (X*Y)) < 1e-15 assert abs(A[1, 0] - (X/Y)) < 1e-15 assert abs(A[1, 1] - (X**Y)) < 1e-13 return l, check
def _get_2_to_2by2_list(real=True): args = x, y = se.symbols('x y') exprs = [[x + y*y, y*y], [x*y*y, se.sqrt(x)+y*y]] l = se.Lambdify(args, exprs, real=real) def check(A, inp): X, Y = inp assert A.shape[-2:] == (2, 2) ref = [X + Y*Y, Y*Y, X*Y*Y, cmath.sqrt(X)+Y*Y] ravA = ravelled(A) size = _size(ravA) for i in range(size//4): for j in range(4): assert isclose(ravA[i*4 + j], ref[j]) return l, check
def _get_1_to_2by3_matrix(): x = se.symbols('x') args = x, exprs = se.DenseMatrix(2, 3, [x+1, x+2, x+3, 1/x, 1/(x*x), 1/(x**3.0)]) l = se.Lambdify(args, exprs) def check(A, inp): X, = inp assert abs(A[0, 0] - (X+1)) < 1e-15 assert abs(A[0, 1] - (X+2)) < 1e-15 assert abs(A[0, 2] - (X+3)) < 1e-15 assert abs(A[1, 0] - (1/X)) < 1e-15 assert abs(A[1, 1] - (1/(X*X))) < 1e-15 assert abs(A[1, 2] - (1/(X**3.0))) < 1e-15 return l, check
def test_jacobian__broadcast(): if not HAVE_NUMPY: # nosetests work-around return x, y = se.symbols('x, y') args = se.DenseMatrix(2, 1, [x, y]) v = se.DenseMatrix(2, 1, [x**3 * y, (x+1)*(y+1)]) jac = v.jacobian(args) lmb = se.Lambdify(args, jac) out = np.empty((3, 2, 2)) inp0 = 7, 11 inp1 = 8, 13 inp2 = 5, 9 inp = np.array([inp0, inp1, inp2]) lmb(inp, out) for idx, (X, Y) in enumerate([inp0, inp1, inp2]): assert np.allclose(out[idx, ...], [[3 * X**2 * Y, X**3], [Y + 1, X + 1]])
def test_DictBasic(): x, y, z = symbols("x y z") d = DictBasic({x: 2, y: z}) assert str(d) == "{x: 2, y: z}" or str(d) == "{y: z, x: 2}" assert d[x] == 2 raises(KeyError, lambda: d[2*z]) if 2*z in d: assert False d[2*z] = x assert d[2*z] == x if 2*z not in d: assert False assert set(d.items()) == set([(2*z, x), (x, Integer(2)), (y, z)]) del d[x] assert set(d.keys()) == set([2*z, y]) assert set(d.values()) == set([x, z]) e = y + sin(2*z) assert e.subs(d) == z + sin(x)
def SS(A, num_iterates=10000, interval_length=0.01): """ Computes equation 3.42: the volume of the number of perturbations that cause a sign switch in some part of the matrix :param A: input matrix, numpy array :return: Scalar (percent of perturbations that caused some sign switch) """ if not is_stable(A): raise Exception( "The input matrix is not stable itself (one or more eigenvalues have non-negative real part). Cannot continue analysis.") t0 = timeit.default_timer() entries_to_perturb = get_entries_to_perturb(A) Ainv = sp.Matrix(np.linalg.inv(A).tolist()) (m,n) = A.shape # get the variables we are going to perturb pert_locations_i, pert_locations_j = np.where(entries_to_perturb) symbol_string = "" for i, j in zip(pert_locations_i, pert_locations_j): symbol_string += "eps_%d_%d " % (i, j) if len(pert_locations_i) == 1: symbol_tup = [sp.symbols(symbol_string)] else: symbol_tup = list(sp.symbols(symbol_string)) # create the matrix with the symbolic perturbation values B_temp = np.zeros(A.shape).tolist() #sp.Matrix(np.zeros(A.shape).tolist()) iter = 0 for i, j in zip(pert_locations_i, pert_locations_j): B_temp[i][j] = symbol_tup[iter] iter += 1 #B_temp = sp.Matrix(B_temp) t1 = timeit.default_timer() print("preprocess time: %f" %(t1 - t0)) t0 = timeit.default_timer() # form the symbolic matrix (A+B)^(-1)./A^(-1) print(B_temp) B = sp.Matrix(B_temp) print(B) AplusB = sp.Matrix(A.tolist()) + B AplusBinv = AplusB.inv() #AplusBinv = AplusB.inv(method='LU', try_block_diag=True) #AplusBinv = AplusB.inv(method='ADJ', try_block_diag=True) t1 = timeit.default_timer() print("AplusBinv time: %f" %(t1 - t0)) t0 = timeit.default_timer() # component-wise division AplusBinvDivAinv = sp.Matrix(np.zeros(A.shape).tolist()) for i in range(A.shape[0]): for j in range(A.shape[1]): AplusBinvDivAinv[i, j] = AplusBinv[i, j] / float(Ainv[i, j]) t1 = timeit.default_timer() print("AplusBinvDivAinv time: %f" % (t1 - t0)) t0 = timeit.default_timer() # lambdafy the symbolic quantity AplusBinvDivAinvEval = sp.lambdify(symbol_tup, AplusBinvDivAinv, "numpy") AplusBEval = sp.lambdify(symbol_tup, AplusB, "numpy") t1 = timeit.default_timer() print("lambdify time: %f" % (t1 - t0)) #num_iterates = 10000 #interval_length = 0.01 switch_count = 0 is_stable_count = 0 # initialize the dictionaries of values to pass eps_dicts = [] for iterate in range(num_iterates): eps_dicts.append(dict()) t0 = timeit.default_timer() # for each one of the symbols, sample from the appropriate distribution for symbol in symbol_tup: symbol_name = symbol.name i = eval(symbol_name.split('_')[1]) j = eval(symbol_name.split('_')[2]) interval = intervals(A[i, j], interval_length) dist = st.uniform(interval[0], interval[1]) vals = dist.rvs(num_iterates) iter = 0 for eps_dict in eps_dicts: eps_dict[symbol_name] = vals[iter] iter += 1 t1 = timeit.default_timer() print("Sample time: %f" % (t1 - t0)) # check for sign switches and stability t0 = timeit.default_timer() for eps_dict in eps_dicts: val_list = [] for var in symbol_tup: val_list.append(eps_dict[var.name]) stab_indicator = is_stable(AplusBEval(*val_list)[0].reshape(A.shape)) if stab_indicator: is_stable_count += 1 if exists_switch(eps_dict, AplusBinvDivAinvEval, symbol_tup, n) and stab_indicator: switch_count += 1 t1 = timeit.default_timer() print("Actual eval time: %f" % (t1 - t0)) #print(switch_count) #print(num_iterates) #print(is_stable_count) return switch_count / float(num_iterates) # this is how it was done in the paper/mathematica
def test_check_undefined_variable(self): x = symengine.symbols("x") DDE = jitcdde([x]) with self.assertRaises(ValueError): DDE.check()
class TestGenerator(TestIntegration): @classmethod def setUpClass(self): self.DDE = jitcdde(f_generator) self.DDE.set_integration_parameters(**test_parameters) class TestGeneratorPython(TestGenerator): def generator(self): self.DDE.generate_lambdas() class TestGeneratorChunking(TestGenerator): def generator(self): self.DDE.compile_C(chunk_size=1, extra_compile_args=compile_args) delayed_y, y3m10, coupling_term = symengine.symbols("delayed_y y3m10 coupling_term") f_alt_helpers = [ (delayed_y, y(0,t-delay)), (coupling_term, 0.25 * (delayed_y - y(3))), (y3m10, y(3)-10) ] f_alt = [ omega[0] * (-y(1) - y(2)), omega[0] * (y(0) + 0.165 * y(1)), omega[0] * (0.2 + y(2) * (y(0) - 10.0)), omega[1] * (-y(4) - y(5)) + coupling_term, omega[1] * (y3m10 + 10 + 0.165 * y(4)), omega[1] * (0.2 + y(5) * y3m10) ]
def test_Lambdify(): n = 7 args = x, y, z = se.symbols('x y z') l = se.Lambdify(args, [x+y+z, x**2, (x-y)/z, x*y*z]) assert allclose(l(range(n, n+len(args))), [3*n+3, n**2, -1/(n+2), n*(n+1)*(n+2)])
def pt(): return sp.symbols('pt_x, pt_y, pt_z')
def obj_acc(): return sp.symbols('acc_x, acc_y, acc_z')
import symengine as sp from symengine import sqrt, cos, sin, Piecewise, atan2 import sympy import math phase_0, phase_1 = sp.symbols('phase_0, phase_1') tilt_0, tilt_1 = sp.symbols('tilt_0, tilt_1') curve_0, curve_1 = sp.symbols('curve_0, curve_1') gibPhase_0, gibPhase_1 = sp.symbols('gibPhase_0, gibPhase_1') gibMag_0, gibMag_1 = sp.symbols('gibMag_0, gibMag_1') ogeePhase_0, ogeePhase_1 = sp.symbols('ogeePhase_0, ogeePhase_1') ogeeMag_0, ogeeMag_1 = sp.symbols('ogeeMag_0, ogeeMag_1') def time(): return sp.symbols('time') class SurviveType: pass class BaseStationCal(SurviveType): def __init__(self, cal): (self.phase, self.tilt, self.curve, self.gibpha, self.gibmag, self.ogeephase, self.ogeemag) = cal def bsd(): return [bsc0(), bsc1()]
def test_Lambdify_gh174(): # Tests array broadcasting if the expressions form an N-dimensional array # of say shape (k, l, m) and it contains 'n' arguments (x1, ... xn), then # if the user provides a Fortran ordered (column-major) input array of shape # (n, o, p, q), then the returned array will be of shape (k, l, m, o, p, q) args = x, y = se.symbols('x y') nargs = len(args) vec1 = se.DenseMatrix([x, x**2, x**3]) assert vec1.shape == (3, 1) assert np.asarray(vec1).shape == (3, 1) lmb1 = se.Lambdify([x], vec1) out1 = lmb1(3) assert out1.shape == (3, 1) assert np.all(out1 == [[3], [9], [27]]) assert lmb1([2, 3]).shape == (2, 3, 1) lmb1.order = 'F' # change order out1a = lmb1([2, 3]) assert out1a.shape == (3, 1, 2) ref1a_squeeze = [[2, 3], [4, 9], [8, 27]] assert np.all(out1a.squeeze() == ref1a_squeeze) assert out1a.flags['F_CONTIGUOUS'] assert not out1a.flags['C_CONTIGUOUS'] lmb2c = se.Lambdify(args, vec1, x + y, order='C') lmb2f = se.Lambdify(args, vec1, x + y, order='F') for out2a in [lmb2c([2, 3]), lmb2f([2, 3])]: assert np.all(out2a[0] == [[2], [4], [8]]) assert out2a[0].ndim == 2 assert out2a[1] == 5 assert out2a[1].ndim == 0 inp2b = np.array([[2.0, 3.0], [1.0, 2.0], [0.0, 6.0]]) raises(ValueError, lambda: (lmb2c(inp2b.T))) out2c = lmb2c(inp2b) out2f = lmb2f(np.asfortranarray(inp2b.T)) assert out2c[0].shape == (3, 3, 1) assert out2f[0].shape == (3, 1, 3) for idx, (_x, _y) in enumerate(inp2b): assert np.all(out2c[0][idx, ...] == [[_x], [_x**2], [_x**3]]) assert np.all(out2c[1] == [5, 3, 6]) assert np.all(out2f[1] == [5, 3, 6]) assert out2c[1].shape == (3, ) assert out2f[1].shape == (3, ) def _mtx3(_x, _y): return [[_x**row_idx + _y**col_idx for col_idx in range(3)] for row_idx in range(4)] mtx3c = np.array(_mtx3(x, y), order='C') mtx3f = np.array(_mtx3(x, y), order='F') lmb3c = se.Lambdify([x, y], x * y, mtx3c, vec1, order='C') lmb3f = se.Lambdify([x, y], x * y, mtx3f, vec1, order='F') inp3c = np.array([[2., 3], [3, 4], [5, 7], [6, 2], [3, 1]]) inp3f = np.asfortranarray(inp3c.T) raises(ValueError, lambda: (lmb3c(inp3c.T))) out3c = lmb3c(inp3c) assert out3c[0].shape == (5, ) assert out3c[1].shape == (5, 4, 3) assert out3c[2].shape == ( 5, 3, 1) # user can apply numpy.squeeze if they want to. for a, b in zip(out3c, lmb3c(np.ravel(inp3c))): assert np.all(a == b) out3f = lmb3f(inp3f) assert out3f[0].shape == (5, ) assert out3f[1].shape == (4, 3, 5) assert out3f[2].shape == ( 3, 1, 5) # user can apply numpy.squeeze if they want to. for a, b in zip(out3f, lmb3f(np.ravel(inp3f, order='F'))): assert np.all(a == b) for idx, (_x, _y) in enumerate(inp3c): assert out3c[0][idx] == _x * _y assert out3f[0][idx] == _x * _y assert np.all(out3c[1][idx, ...] == _mtx3(_x, _y)) assert np.all(out3f[1][..., idx] == _mtx3(_x, _y)) assert np.all(out3c[2][idx, ...] == [[_x], [_x**2], [_x**3]]) assert np.all(out3f[2][..., idx] == [[_x], [_x**2], [_x**3]])
class TestGeneratorChunking(TestGenerator): def generator(self): self.DDE.compile_C(chunk_size=1, extra_compile_args=compile_args) f_dict = { y(i):entry for i,entry in enumerate(f) } class TestDictionary(TestIntegration): @classmethod def setUpClass(self): self.DDE = jitcdde(f_dict) self.DDE.set_integration_parameters(**test_parameters) delayed_y, y3m10, coupling_term = symengine.symbols("delayed_y y3m10 coupling_term") f_alt_helpers = [ (delayed_y, y(0,t-delay)), (coupling_term, 0.25 * (delayed_y - y(3))), (y3m10, y(3)-10) ] f_alt = [ omega[0] * (-y(1) - y(2)), omega[0] * (y(0) + 0.165 * y(1)), omega[0] * (0.2 + y(2) * (y(0) - 10.0)), omega[1] * (-y(4) - y(5)) + coupling_term, omega[1] * (y3m10 + 10 + 0.165 * y(4)), omega[1] * (0.2 + y(5) * y3m10) ]
def up_in_obj(): return list(sp.symbols('obj_up_x, obj_up_y, obj_up_z'))
def gyro_bias(): return sp.symbols('gbx, gby, gbz')
def test_sage_conversions(): try: import sage.all as sage except ImportError: return x, y = sage.SR.var('x y') x1, y1 = symbols('x, y') # Symbol assert x1._sage_() == x assert x1 == sympify(x) # Integer assert Integer(12)._sage_() == sage.Integer(12) assert Integer(12) == sympify(sage.Integer(12)) # Rational assert (Integer(1) / 2)._sage_() == sage.Integer(1) / 2 assert Integer(1) / 2 == sympify(sage.Integer(1) / 2) # Operators assert x1 + y == x1 + y1 assert x1 * y == x1 * y1 assert x1 ** y == x1 ** y1 assert x1 - y == x1 - y1 assert x1 / y == x1 / y1 assert x + y1 == x + y assert x * y1 == x * y # Doesn't work in Sage 6.1.1ubuntu2 # assert x ** y1 == x ** y assert x - y1 == x - y assert x / y1 == x / y # Conversions assert (x1 + y1)._sage_() == x + y assert (x1 * y1)._sage_() == x * y assert (x1 ** y1)._sage_() == x ** y assert (x1 - y1)._sage_() == x - y assert (x1 / y1)._sage_() == x / y assert x1 + y1 == sympify(x + y) assert x1 * y1 == sympify(x * y) assert x1 ** y1 == sympify(x ** y) assert x1 - y1 == sympify(x - y) assert x1 / y1 == sympify(x / y) # Functions assert sin(x1) == sin(x) assert sin(x1)._sage_() == sage.sin(x) assert sin(x1) == sympify(sage.sin(x)) assert cos(x1) == cos(x) assert cos(x1)._sage_() == sage.cos(x) assert cos(x1) == sympify(sage.cos(x)) assert function_symbol('f', x1, y1)._sage_() == sage.function('f', x, y) assert function_symbol('f', 2 * x1, x1 + y1).diff(x1)._sage_() == sage.function('f', 2 * x, x + y).diff(x) # For the following test, sage needs to be modified # assert sage.sin(x) == sage.sin(x1) # Constants assert pi._sage_() == sage.pi assert E._sage_() == sage.e assert I._sage_() == sage.I assert pi == sympify(sage.pi) assert E == sympify(sage.e) # SympyConverter does not support converting the following # assert I == sympify(sage.I) # Matrix assert DenseMatrix(1, 2, [x1, y1])._sage_() == sage.matrix([[x, y]]) # SympyConverter does not support converting the following # assert DenseMatrix(1, 2, [x1, y1]) == sympify(sage.matrix([[x, y]])) # Sage Number a = sage.Mod(2, 7) b = PyNumber(a, sage_module) a = a + 8 b = b + 8 assert isinstance(b, PyNumber) assert b._sage_() == a a = a + x b = b + x assert isinstance(b, Add) assert b._sage_() == a # Sage Function e = x1 + wrap_sage_function(sage.log_gamma(x)) assert str(e) == "x + log_gamma(x)" assert isinstance(e, Add) assert e + wrap_sage_function(sage.log_gamma(x)) == x1 + 2*wrap_sage_function(sage.log_gamma(x)) f = e.subs({x1 : 10}) assert f == 10 + log(362880) f = e.subs({x1 : 2}) assert f == 2 f = e.subs({x1 : 100}); v = f.n(53, real=True); assert abs(float(v) - 459.13420537) < 1e-7 f = e.diff(x1)
def test_symbols(): x = Symbol('x') y = Symbol('y') z = Symbol('z') assert symbols('x') == x assert symbols('x ') == x assert symbols(' x ') == x assert symbols('x,') == (x,) assert symbols('x, ') == (x,) assert symbols('x ,') == (x,) assert symbols('x , y') == (x, y) assert symbols('x,y,z') == (x, y, z) assert symbols('x y z') == (x, y, z) assert symbols('x,y,z,') == (x, y, z) assert symbols('x y z ') == (x, y, z) xyz = Symbol('xyz') abc = Symbol('abc') assert symbols('xyz') == xyz assert symbols('xyz,') == (xyz,) assert symbols('xyz,abc') == (xyz, abc) assert symbols(('xyz',)) == (xyz,) assert symbols(('xyz,',)) == ((xyz,),) assert symbols(('x,y,z,',)) == ((x, y, z),) assert symbols(('xyz', 'abc')) == (xyz, abc) assert symbols(('xyz,abc',)) == ((xyz, abc),) assert symbols(('xyz,abc', 'x,y,z')) == ((xyz, abc), (x, y, z)) assert symbols(('x', 'y', 'z')) == (x, y, z) assert symbols(['x', 'y', 'z']) == [x, y, z] assert symbols(set(['x', 'y', 'z'])) == set([x, y, z]) raises(ValueError, lambda: symbols('')) raises(ValueError, lambda: symbols(',')) raises(ValueError, lambda: symbols('x,,y,,z')) raises(ValueError, lambda: symbols(('x', '', 'y', '', 'z'))) x0 = Symbol('x0') x1 = Symbol('x1') x2 = Symbol('x2') y0 = Symbol('y0') y1 = Symbol('y1') assert symbols('x0:0') == () assert symbols('x0:1') == (x0,) assert symbols('x0:2') == (x0, x1) assert symbols('x0:3') == (x0, x1, x2) assert symbols('x:0') == () assert symbols('x:1') == (x0,) assert symbols('x:2') == (x0, x1) assert symbols('x:3') == (x0, x1, x2) assert symbols('x1:1') == () assert symbols('x1:2') == (x1,) assert symbols('x1:3') == (x1, x2) assert symbols('x1:3,x,y,z') == (x1, x2, x, y, z) assert symbols('x:3,y:2') == (x0, x1, x2, y0, y1) assert symbols(('x:3', 'y:2')) == ((x0, x1, x2), (y0, y1)) a = Symbol('a') b = Symbol('b') c = Symbol('c') d = Symbol('d') assert symbols('x:z') == (x, y, z) assert symbols('a:d,x:z') == (a, b, c, d, x, y, z) assert symbols(('a:d', 'x:z')) == ((a, b, c, d), (x, y, z)) aa = Symbol('aa') ab = Symbol('ab') ac = Symbol('ac') ad = Symbol('ad') assert symbols('aa:d') == (aa, ab, ac, ad) assert symbols('aa:d,x:z') == (aa, ab, ac, ad, x, y, z) assert symbols(('aa:d','x:z')) == ((aa, ab, ac, ad), (x, y, z)) def sym(s): return str(symbols(s)) assert sym('a0:4') == '(a0, a1, a2, a3)' assert sym('a2:4,b1:3') == '(a2, a3, b1, b2)' assert sym('a1(2:4)') == '(a12, a13)' assert sym(('a0:2.0:2')) == '(a0.0, a0.1, a1.0, a1.1)' assert sym(('aa:cz')) == '(aaz, abz, acz)' assert sym('aa:c0:2') == '(aa0, aa1, ab0, ab1, ac0, ac1)' assert sym('aa:ba:b') == '(aaa, aab, aba, abb)' assert sym('a:3b') == '(a0b, a1b, a2b)' assert sym('a-1:3b') == '(a-1b, a-2b)' assert sym('a:2\,:2' + chr(0)) == '(a0,0%s, a0,1%s, a1,0%s, a1,1%s)' % ( (chr(0),)*4) assert sym('x(:a:3)') == '(x(a0), x(a1), x(a2))' assert sym('x(:c):1') == '(xa0, xb0, xc0)' assert sym('x((:a)):3') == '(x(a)0, x(a)1, x(a)2)' assert sym('x(:a:3') == '(x(a0, x(a1, x(a2)' assert sym(':2') == '(0, 1)' assert sym(':b') == '(a, b)' assert sym(':b:2') == '(a0, a1, b0, b1)' assert sym(':2:2') == '(00, 01, 10, 11)' assert sym(':b:b') == '(aa, ab, ba, bb)' raises(ValueError, lambda: symbols(':')) raises(ValueError, lambda: symbols('a:')) raises(ValueError, lambda: symbols('::')) raises(ValueError, lambda: symbols('a::')) raises(ValueError, lambda: symbols(':a:')) raises(ValueError, lambda: symbols('::a'))
def is_free(self, p): return p not in self.points or self.points[p] == symbols(self.name + '.' + p)
def sym(s): return str(symbols(s))
def test_symbols(): x = Symbol('x') y = Symbol('y') z = Symbol('z') assert symbols('x') == x assert symbols('x ') == x assert symbols(' x ') == x assert symbols('x,') == (x, ) assert symbols('x, ') == (x, ) assert symbols('x ,') == (x, ) assert symbols('x , y') == (x, y) assert symbols('x,y,z') == (x, y, z) assert symbols('x y z') == (x, y, z) assert symbols('x,y,z,') == (x, y, z) assert symbols('x y z ') == (x, y, z) xyz = Symbol('xyz') abc = Symbol('abc') assert symbols('xyz') == xyz assert symbols('xyz,') == (xyz, ) assert symbols('xyz,abc') == (xyz, abc) assert symbols(('xyz', )) == (xyz, ) assert symbols(('xyz,', )) == ((xyz, ), ) assert symbols(('x,y,z,', )) == ((x, y, z), ) assert symbols(('xyz', 'abc')) == (xyz, abc) assert symbols(('xyz,abc', )) == ((xyz, abc), ) assert symbols(('xyz,abc', 'x,y,z')) == ((xyz, abc), (x, y, z)) assert symbols(('x', 'y', 'z')) == (x, y, z) assert symbols(['x', 'y', 'z']) == [x, y, z] assert symbols(set(['x', 'y', 'z'])) == set([x, y, z]) raises(ValueError, lambda: symbols('')) raises(ValueError, lambda: symbols(',')) raises(ValueError, lambda: symbols('x,,y,,z')) raises(ValueError, lambda: symbols(('x', '', 'y', '', 'z'))) x0 = Symbol('x0') x1 = Symbol('x1') x2 = Symbol('x2') y0 = Symbol('y0') y1 = Symbol('y1') assert symbols('x0:0') == () assert symbols('x0:1') == (x0, ) assert symbols('x0:2') == (x0, x1) assert symbols('x0:3') == (x0, x1, x2) assert symbols('x:0') == () assert symbols('x:1') == (x0, ) assert symbols('x:2') == (x0, x1) assert symbols('x:3') == (x0, x1, x2) assert symbols('x1:1') == () assert symbols('x1:2') == (x1, ) assert symbols('x1:3') == (x1, x2) assert symbols('x1:3,x,y,z') == (x1, x2, x, y, z) assert symbols('x:3,y:2') == (x0, x1, x2, y0, y1) assert symbols(('x:3', 'y:2')) == ((x0, x1, x2), (y0, y1)) a = Symbol('a') b = Symbol('b') c = Symbol('c') d = Symbol('d') assert symbols('x:z') == (x, y, z) assert symbols('a:d,x:z') == (a, b, c, d, x, y, z) assert symbols(('a:d', 'x:z')) == ((a, b, c, d), (x, y, z)) aa = Symbol('aa') ab = Symbol('ab') ac = Symbol('ac') ad = Symbol('ad') assert symbols('aa:d') == (aa, ab, ac, ad) assert symbols('aa:d,x:z') == (aa, ab, ac, ad, x, y, z) assert symbols(('aa:d', 'x:z')) == ((aa, ab, ac, ad), (x, y, z)) def sym(s): return str(symbols(s)) assert sym('a0:4') == '(a0, a1, a2, a3)' assert sym('a2:4,b1:3') == '(a2, a3, b1, b2)' assert sym('a1(2:4)') == '(a12, a13)' assert sym(('a0:2.0:2')) == '(a0.0, a0.1, a1.0, a1.1)' assert sym(('aa:cz')) == '(aaz, abz, acz)' assert sym('aa:c0:2') == '(aa0, aa1, ab0, ab1, ac0, ac1)' assert sym('aa:ba:b') == '(aaa, aab, aba, abb)' assert sym('a:3b') == '(a0b, a1b, a2b)' assert sym('a-1:3b') == '(a-1b, a-2b)' assert sym('a:2\,:2' + chr(0)) == '(a0,0%s, a0,1%s, a1,0%s, a1,1%s)' % ((chr(0), ) * 4) assert sym('x(:a:3)') == '(x(a0), x(a1), x(a2))' assert sym('x(:c):1') == '(xa0, xb0, xc0)' assert sym('x((:a)):3') == '(x(a)0, x(a)1, x(a)2)' assert sym('x(:a:3') == '(x(a0, x(a1, x(a2)' assert sym(':2') == '(0, 1)' assert sym(':b') == '(a, b)' assert sym(':b:2') == '(a0, a1, b0, b1)' assert sym(':2:2') == '(00, 01, 10, 11)' assert sym(':b:b') == '(aa, ab, ba, bb)' raises(ValueError, lambda: symbols(':')) raises(ValueError, lambda: symbols('a:')) raises(ValueError, lambda: symbols('::')) raises(ValueError, lambda: symbols('a::')) raises(ValueError, lambda: symbols(':a:')) raises(ValueError, lambda: symbols('::a'))
def obj_v(): return LinmathAxisAnglePose(sp.symbols('vx, vy, vz'), sp.symbols('avx, avy, avz'))
# as dictionary f_dict = { y(i):entry for i,entry in reversed(list(enumerate(f))) } with_dictionary = {"f_sym": f_dict} # with generator def f_generator(): for entry in f: yield entry with_generator = { "f_sym":f_generator, "n":n } # with helpers f1, f2, f3, f4 = symbols("f1, f2, f3, f4") coupling, first_y, first_y_sq = symbols("coupling, first_y, first_y_sq") a_alt, b1_alt, b2_alt, c_alt, k_alt = symbols("a_alt, b1_alt, b2_alt, c_alt, k_alt") f_alt = [ f1, f2, f3, f4 ] f_alt_helpers = [ ( a_alt , a ), ( b1_alt, b1 ), ( b2_alt, b2 ), ( c_alt, c ), ( k_alt, k ), ( first_y, y(0) ), ( first_y_sq, first_y**2 ), ( coupling, k_alt*(y(2)-first_y) ), ( f1, a_alt*first_y_sq - a_alt*first_y + coupling - first_y**3 + first_y_sq - y(1) ), ( f2, b1_alt*first_y - c_alt*y(1)),
def time(): return sp.symbols('time')
def q2(): return sp.symbols('q1_w, q1_x, q1_y, q1_z')
def main(): # Check input arguments parser = get_parser() args = parser.parse_args() par = Params() plot_dir = os.path.join(args.output, "AP-protocol") if not os.path.exists(plot_dir): os.makedirs(plot_dir) # Choose parameters (make sure conductance is the last parameter) para = np.array([ 2.07E-3, 7.17E-2, 3.44E-5, 6.18E-2, 4.18E-1, 2.58E-2, 4.75E-2, 2.51E-2, 3.33E-2 ]) # Create symbols for symbolic functions p, y, v = CreateSymbols(par) k = se.symbols('k1, k2, k3, k4') # Define system equations and initial conditions k1 = p[0] * se.exp(p[1] * v) k2 = p[2] * se.exp(-p[3] * v) k3 = p[4] * se.exp(p[5] * v) k4 = p[6] * se.exp(-p[7] * v) # Notation is consistent between the two papers A = se.Matrix([[-k1 - k3 - k4, k2 - k4, -k4], [k1, -k2 - k3, k4], [-k1, k3 - k1, -k2 - k4 - k1]]) B = se.Matrix([k4, 0, k1]) rhs = np.array(A * y + B) protocol = pd.read_csv( os.path.join( os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "protocols", "AP-protocol.txt")) times = 1E3 * protocol["time"].values voltages = protocol["voltage"].values # 10*times to correct units staircase_protocol = scipy.interpolate.interp1d(times, voltages, kind="linear") staircase_protocol_safe = lambda t: staircase_protocol(t) if t < times[ -1] else par.holding_potential funcs = GetSensitivityEquations(par, p, y, v, A, B, para, times, voltage=staircase_protocol_safe) ret = funcs.SimulateForwardModelSensitivities(para), current = ret[0][0] S1 = ret[0][1] S1n = S1 * np.array(para)[None, :] state_variables = funcs.GetStateVariables(para) state_labels = ['C', 'O', 'I', 'IC'] param_labels = ['S(p' + str(i + 1) + ',t)' for i in range(par.n_params)] fig = plt.figure(figsize=(8, 8), dpi=args.dpi) ax1 = fig.add_subplot(411) ax1.plot(funcs.times, funcs.GetVoltage()) ax1.grid(True) ax1.set_xticklabels([]) ax1.set_ylabel('Voltage (mV)') ax2 = fig.add_subplot(412) ax2.plot(funcs.times, funcs.SimulateForwardModel(para)) ax2.grid(True) ax2.set_xticklabels([]) ax2.set_ylabel('Current (nA)') ax3 = fig.add_subplot(413) for i in range(par.n_state_vars + 1): ax3.plot(funcs.times, state_variables[:, i], label=state_labels[i]) ax3.legend(ncol=4) ax3.grid(True) ax3.set_xticklabels([]) ax3.set_ylabel('State occupancy') ax4 = fig.add_subplot(414) for i in range(par.n_params): ax4.plot(funcs.times, S1n[:, i], label=param_labels[i]) ax4.legend(ncol=3) ax4.grid(True) ax4.set_xlabel('Time (ms)') ax4.set_ylabel('Sensitivities') plt.tight_layout() if not args.plot: plt.savefig( os.path.join(plot_dir, 'ForwardModel_SW_{}.png'.format(args.sine_wave))) H = np.dot(S1n.T, S1n) print(H) eigvals = np.linalg.eigvals(H) print('Eigenvalues of H:\n{}'.format(eigvals.real)) # Plot the eigenvalues of H, shows the condition of H fig = plt.figure(figsize=(6, 6), dpi=args.dpi) ax = fig.add_subplot(111) for i in eigvals: ax.axhline(y=i, xmin=0.25, xmax=0.75) ax.set_yscale('log') ax.set_xticks([]) ax.grid(True) if not args.plot: plt.savefig( os.path.join(plot_dir, 'Eigenvalues_SW_{}.png'.format(args.sine_wave))) if args.plot: plt.show()
def axis_angle(): return sp.symbols('aa_x, aa_y, aa_z')
def test_basic(): x, y, z = symbols('x y z') expr = sin(cos(x + y) / z)**2 s = pickle.dumps(expr) expr2 = pickle.loads(s) assert expr == expr2
def test_sage_conversions(): try: import sage.all as sage except ImportError: return x, y = sage.SR.var('x y') x1, y1 = symbols('x, y') # Symbol assert x1._sage_() == x assert x1 == sympify(x) # Integer assert Integer(12)._sage_() == sage.Integer(12) assert Integer(12) == sympify(sage.Integer(12)) # Rational assert (Integer(1) / 2)._sage_() == sage.Integer(1) / 2 assert Integer(1) / 2 == sympify(sage.Integer(1) / 2) # Operators assert x1 + y == x1 + y1 assert x1 * y == x1 * y1 assert x1 ** y == x1 ** y1 assert x1 - y == x1 - y1 assert x1 / y == x1 / y1 assert x + y1 == x + y assert x * y1 == x * y # Doesn't work in Sage 6.1.1ubuntu2 # assert x ** y1 == x ** y assert x - y1 == x - y assert x / y1 == x / y # Conversions assert (x1 + y1)._sage_() == x + y assert (x1 * y1)._sage_() == x * y assert (x1 ** y1)._sage_() == x ** y assert (x1 - y1)._sage_() == x - y assert (x1 / y1)._sage_() == x / y assert x1 + y1 == sympify(x + y) assert x1 * y1 == sympify(x * y) assert x1 ** y1 == sympify(x ** y) assert x1 - y1 == sympify(x - y) assert x1 / y1 == sympify(x / y) # Functions assert sin(x1) == sin(x) assert sin(x1)._sage_() == sage.sin(x) assert sin(x1) == sympify(sage.sin(x)) assert cos(x1) == cos(x) assert cos(x1)._sage_() == sage.cos(x) assert cos(x1) == sympify(sage.cos(x)) assert function_symbol('f', x1, y1)._sage_() == sage.function('f', x, y) assert (function_symbol('f', 2 * x1, x1 + y1).diff(x1)._sage_() == sage.function('f', 2 * x, x + y).diff(x)) # For the following test, sage needs to be modified # assert sage.sin(x) == sage.sin(x1) # Constants assert pi._sage_() == sage.pi assert E._sage_() == sage.e assert I._sage_() == sage.I assert pi == sympify(sage.pi) assert E == sympify(sage.e) # SympyConverter does not support converting the following # assert I == sympify(sage.I) # Matrix assert DenseMatrix(1, 2, [x1, y1])._sage_() == sage.matrix([[x, y]]) # SympyConverter does not support converting the following # assert DenseMatrix(1, 2, [x1, y1]) == sympify(sage.matrix([[x, y]])) # Sage Number a = sage.Mod(2, 7) b = PyNumber(a, sage_module) a = a + 8 b = b + 8 assert isinstance(b, PyNumber) assert b._sage_() == a a = a + x b = b + x assert isinstance(b, Add) assert b._sage_() == a # Sage Function e = x1 + wrap_sage_function(sage.log_gamma(x)) assert str(e) == "x + log_gamma(x)" assert isinstance(e, Add) assert (e + wrap_sage_function(sage.log_gamma(x)) == x1 + 2*wrap_sage_function(sage.log_gamma(x))) f = e.subs({x1: 10}) assert f == 10 + log(362880) f = e.subs({x1: 2}) assert f == 2 f = e.subs({x1: 100}) v = f.n(53, real=True) assert abs(float(v) - 459.13420537) < 1e-7 f = e.diff(x1)
def main(): # Check input arguments parser = get_parser() args = parser.parse_args() par = Params() plot_dir = os.path.join(args.output, "staircase") if not os.path.exists(plot_dir): os.makedirs(plot_dir) # Choose parameters (make sure conductance is the last parameter) para = np.array([ 2.07E-3, 7.17E-2, 3.44E-5, 6.18E-2, 4.18E-1, 2.58E-2, 4.75E-2, 2.51E-2, 3.33E-2 ]) # Compute resting potential for 37 degrees C reversal_potential = calculate_reversal_potential(temp=37) par.Erev = reversal_potential print("reversal potential is {}".format(reversal_potential)) # Create symbols for symbolic functions p, y, v = CreateSymbols(par) k = se.symbols('k1, k2, k3, k4') # Define system equations and initial conditions k1 = p[0] * se.exp(p[1] * v) k2 = p[2] * se.exp(-p[3] * v) k3 = p[4] * se.exp(p[5] * v) k4 = p[6] * se.exp(-p[7] * v) # Notation is consistent between the two papers A = se.Matrix([[-k1 - k3 - k4, k2 - k4, -k4], [k1, -k2 - k3, k4], [-k1, k3 - k1, -k2 - k4 - k1]]) B = se.Matrix([k4, 0, k1]) current_limit = (p[-1] * (par.holding_potential - reversal_potential) * k1 / (k1 + k2) * k4 / (k3 + k4)).subs( v, par.holding_potential) print("{} Current limit computed as {}".format( __file__, current_limit.subs(p, para).evalf())) sens_inf = [ float(se.diff(current_limit, p[j]).subs(p, para).evalf()) for j in range(0, par.n_params) ] print("{} sens_inf calculated as {}".format(__file__, sens_inf)) protocol = pd.read_csv( os.path.join( os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "protocols", "protocol-staircaseramp.csv")) times = 1000 * protocol["time"].values voltages = protocol["voltage"].values spikes = 1000 * detect_spikes(protocol["time"], protocol["voltage"]) staircase_protocol = scipy.interpolate.interp1d(times, voltages, kind="linear") staircase_protocol_safe = lambda t: staircase_protocol(t) if t < times[ -1] else par.holding_potential funcs = GetSensitivityEquations(par, p, y, v, A, B, para, times, voltage=staircase_protocol_safe) ret = funcs.SimulateForwardModelSensitivities(para), current = ret[0][0] S1 = ret[0][1] S1n = S1 * np.array(para)[None, :] sens_inf_N = sens_inf * np.array(para)[None, :] param_labels = ['S(p' + str(i + 1) + ',t)' for i in range(par.n_params)] [ plt.plot(funcs.times, sens, label=param_labels[i]) for i, sens in enumerate(S1n.T) ] [plt.axhline(s) for s in sens_inf_N[0, :]] plt.legend() plt.xlabel("time /ms") plt.ylabel("dI(t)/dp") if args.plot: plt.show() else: plt.savefig(os.path.join(plot_dir, "sensitivities_plot")) state_variables = funcs.GetStateVariables(para) state_labels = ['C', 'O', 'I', 'IC'] param_labels = ['S(p' + str(i + 1) + ',t)' for i in range(par.n_params)] fig = plt.figure(figsize=(8, 8), dpi=args.dpi) ax1 = fig.add_subplot(411) ax1.plot(funcs.times, funcs.GetVoltage()) ax1.grid(True) ax1.set_xticklabels([]) ax1.set_ylabel('Voltage (mV)') [ax1.axvline(spike, color='red') for spike in spikes] ax2 = fig.add_subplot(412) ax2.plot(funcs.times, funcs.SimulateForwardModel(para)) ax2.grid(True) ax2.set_xticklabels([]) ax2.set_ylabel('Current (nA)') ax3 = fig.add_subplot(413) for i in range(par.n_state_vars + 1): ax3.plot(funcs.times, state_variables[:, i], label=state_labels[i]) ax3.legend(ncol=4) ax3.grid(True) ax3.set_xticklabels([]) ax3.set_ylabel('State occupancy') ax4 = fig.add_subplot(414) for i in range(par.n_params): ax4.plot(funcs.times, S1n[:, i], label=param_labels[i]) ax4.legend(ncol=3) ax4.grid(True) ax4.set_xlabel('Time (ms)') ax4.set_ylabel('Sensitivities') plt.tight_layout() if not args.plot: plt.savefig( os.path.join(plot_dir, 'ForwardModel_SW_{}.png'.format(args.sine_wave))) # Only take every 100th point # S1n = S1n[0:-1:10] H = np.dot(S1n.T, S1n) print(H) eigvals = np.linalg.eigvals(H) #Sigma2 - the observed variance. 1885 is the value taken from a fit sigma2 = 1885 / (len(funcs.times) - 1) print('Eigenvalues of H:\n{}'.format(eigvals.real)) # Plot the eigenvalues of H, shows the condition of H fig = plt.figure(figsize=(6, 6), dpi=args.dpi) ax = fig.add_subplot(111) for i in eigvals: ax.axhline(y=i, xmin=0.25, xmax=0.75) ax.set_yscale('log') ax.set_xticks([]) ax.grid(True) if not args.plot: plt.savefig( os.path.join(plot_dir, 'Eigenvalues_SW_{}.png'.format(args.sine_wave))) if args.plot: plt.show() cov = np.linalg.inv(H * sigma2) for j in range(0, par.n_params): for i in range(j + 1, par.n_params): parameters_to_view = np.array([i, j]) # sub_sens = S1n[:,[i,j]] sub_cov = cov[parameters_to_view[:, None], parameters_to_view] # sub_cov = np.linalg.inv(np.dot(sub_sens.T, sub_sens)*sigma2) eigen_val, eigen_vec = np.linalg.eigh(sub_cov) eigen_val = eigen_val.real if eigen_val[0] > 0 and eigen_val[1] > 0: print("COV_{},{} : well defined".format(i, j)) cov_ellipse(sub_cov, q=[0.75, 0.9, 0.99], offset=para[[i, j]]) plt.ylabel("parameter {}".format(i + 1)) plt.xlabel("parameter {}".format(j + 1)) if args.plot: plt.show() else: plt.savefig( os.path.join( output_dir, "covariance_for_parameters_{}_{}".format( j + 1, i + 1))) plt.clf() else: print("COV_{},{} : negative eigenvalue: {}".format( i, j, eigen_val))
import symengine vars = symengine.symbols('x y') # Define x and y variables f = symengine.sympify(['y*x**2', '5*x + sin(y)']) # Define function J = symengine.zeros(len(f), len(vars)) # Initiate Jacobian matrix # Fill Jacobian Matrix with entries for i, fi in enumerate(f): for j, s in enumerate(vars): J[i,j] = symengine.diff(fi, s) print(J)
def test_check_undefined_variable(self): x = symbols("x") SDE = jitcsde_jump( IJI, amp, [y(0)], [x] ) with self.assertRaises(ValueError): SDE.check()
def test_ravel(): x = se.symbols('x') exprs = [x + 1, x + 2, x + 3, 1 / x, 1 / (x * x), 1 / (x**3.0)] A = se.DenseMatrix(2, 3, exprs) assert np.all(np.ravel(A, order='C') == exprs)
def test_count_ops(): x, y = symbols("x, y") assert count_ops(x + y) == 1 assert count_ops((x + y, x * y)) == 2 assert count_ops([[x**y], [x + y - 1]]) == 3 assert count_ops(x + y, x * y) == 2
def add_free(self, p): self.points[p] = symbols(self.name + '.' + p) return self.auto(p)
f_dict = {y(i): entry for i, entry in reversed(list(enumerate(f)))} with_dictionary = {"f_sym": f_dict} # with generator def f_generator(): for entry in f: yield entry with_generator = {"f_sym": f_generator, "n": n} # with helpers f1, f2, f3, f4 = symbols("f1, f2, f3, f4") coupling, first_y, first_y_sq = symbols("coupling, first_y, first_y_sq") a_alt, b1_alt, b2_alt, c_alt, k_alt = symbols( "a_alt, b1_alt, b2_alt, c_alt, k_alt") f_alt = [f1, f2, f3, f4] f_alt_helpers = [ (a_alt, a), (b1_alt, b1), (b2_alt, b2), (c_alt, c), (k_alt, k), (first_y, y(0)), (first_y_sq, first_y**2), (coupling, k_alt * (y(2) - first_y)), (f1, a_alt * first_y_sq - a_alt * first_y + coupling - first_y**3 +
def test_sage_conversions(): x, y = sage.SR.var('x y') x1, y1 = symbols('x, y') # Symbol assert x1._sage_() == x assert x1 == sympify(x) # Integer assert Integer(12)._sage_() == sage.Integer(12) assert Integer(12) == sympify(sage.Integer(12)) # Rational assert (Integer(1) / 2)._sage_() == sage.Integer(1) / 2 assert Integer(1) / 2 == sympify(sage.Integer(1) / 2) # Operators assert x1 + y == x1 + y1 assert x1 * y == x1 * y1 assert x1**y == x1**y1 assert x1 - y == x1 - y1 assert x1 / y == x1 / y1 assert x + y1 == x + y assert x * y1 == x * y # Doesn't work in Sage 6.1.1ubuntu2 # assert x ** y1 == x ** y assert x - y1 == x - y assert x / y1 == x / y # Conversions assert (x1 + y1)._sage_() == x + y assert (x1 * y1)._sage_() == x * y assert (x1**y1)._sage_() == x**y assert (x1 - y1)._sage_() == x - y assert (x1 / y1)._sage_() == x / y assert x1 + y1 == sympify(x + y) assert x1 * y1 == sympify(x * y) assert x1**y1 == sympify(x**y) assert x1 - y1 == sympify(x - y) assert x1 / y1 == sympify(x / y) # Functions assert sin(x1) == sin(x) assert sin(x1)._sage_() == sage.sin(x) assert sin(x1) == sympify(sage.sin(x)) assert cos(x1) == cos(x) assert cos(x1)._sage_() == sage.cos(x) assert cos(x1) == sympify(sage.cos(x)) assert function_symbol('f', x1, y1)._sage_() == sage.function('f')(x, y) assert (function_symbol('f', 2 * x1, x1 + y1).diff(x1)._sage_() == sage.function('f')( 2 * x, x + y).diff(x)) assert LambertW(x1) == LambertW(x) assert LambertW(x1)._sage_() == sage.lambert_w(x) assert KroneckerDelta(x1, y1) == KroneckerDelta(x, y) assert KroneckerDelta(x1, y1)._sage_() == sage.kronecker_delta(x, y) assert erf(x1) == erf(x) assert erf(x1)._sage_() == sage.erf(x) assert lowergamma(x1, y1) == lowergamma(x, y) assert lowergamma(x1, y1)._sage_() == sage.gamma_inc_lower(x, y) assert uppergamma(x1, y1) == uppergamma(x, y) assert uppergamma(x1, y1)._sage_() == sage.gamma_inc(x, y) assert loggamma(x1) == loggamma(x) assert loggamma(x1)._sage_() == sage.log_gamma(x) assert beta(x1, y1) == beta(x, y) assert beta(x1, y1)._sage_() == sage.beta(x, y) assert floor(x1) == floor(x) assert floor(x1)._sage_() == sage.floor(x) assert ceiling(x1) == ceiling(x) assert ceiling(x1)._sage_() == sage.ceil(x) assert conjugate(x1) == conjugate(x) assert conjugate(x1)._sage_() == sage.conjugate(x) # For the following test, sage needs to be modified # assert sage.sin(x) == sage.sin(x1) # Constants and Booleans assert pi._sage_() == sage.pi assert E._sage_() == sage.e assert I._sage_() == sage.I assert GoldenRatio._sage_() == sage.golden_ratio assert Catalan._sage_() == sage.catalan assert EulerGamma._sage_() == sage.euler_gamma assert oo._sage_() == sage.oo assert zoo._sage_() == sage.unsigned_infinity assert nan._sage_() == sage.NaN assert true._sage_() == True assert false._sage_() == False assert pi == sympify(sage.pi) assert E == sympify(sage.e) assert GoldenRatio == sympify(sage.golden_ratio) assert Catalan == sympify(sage.catalan) assert EulerGamma == sympify(sage.euler_gamma) assert oo == sympify(sage.oo) assert zoo == sympify(sage.unsigned_infinity) assert nan == sympify(sage.NaN) # SympyConverter does not support converting the following # assert I == sympify(sage.I) # Matrix assert DenseMatrix(1, 2, [x1, y1])._sage_() == sage.matrix([[x, y]]) # SympyConverter does not support converting the following # assert DenseMatrix(1, 2, [x1, y1]) == sympify(sage.matrix([[x, y]])) # Sage Number a = sage.Mod(2, 7) b = PyNumber(a, sage_module) a = a + 8 b = b + 8 assert isinstance(b, PyNumber) assert b._sage_() == a assert str(a) == str(b) # Sage Function e = x1 + wrap_sage_function(sage.log_gamma(x)) assert str(e) == "x + log_gamma(x)" assert isinstance(e, Add) assert (e + wrap_sage_function(sage.log_gamma(x)) == x1 + 2 * wrap_sage_function(sage.log_gamma(x))) f = e.subs({x1: 10}) assert f == 10 + log(362880) f = e.subs({x1: 2}) assert f == 2 f = e.subs({x1: 100}) v = f.n(53, real=True) assert abs(float(v) - 459.13420537) < 1e-7 f = e.diff(x1)
def test_diff(): x = symbols("x") M = DenseMatrix(1, 2, [x**2, x]) result = M.diff(x) assert isinstance(result, DenseMatrix) assert result == DenseMatrix(1, 2, [2 * x, 1])
def _get_cse_exprs(): args = x, y = se.symbols('x y') exprs = [x*x + y, y/(x*x), y*x*x+x] inp = [11, 13] ref = [121+13, 13/121, 13*121 + 11] return args, exprs, inp, ref
def test_sage_conversions(): try: import sage.all as sage except ImportError: return x, y = sage.SR.var('x y') x1, y1 = symbols('x, y') # Symbol assert x1._sage_() == x assert x1 == sympify(x) # Integer assert Integer(12)._sage_() == sage.Integer(12) assert Integer(12) == sympify(sage.Integer(12)) # Rational assert (Integer(1) / 2)._sage_() == sage.Integer(1) / 2 assert Integer(1) / 2 == sympify(sage.Integer(1) / 2) # Operators assert x1 + y == x1 + y1 assert x1 * y == x1 * y1 assert x1 ** y == x1 ** y1 assert x1 - y == x1 - y1 assert x1 / y == x1 / y1 assert x + y1 == x + y assert x * y1 == x * y # Doesn't work in Sage 6.1.1ubuntu2 # assert x ** y1 == x ** y assert x - y1 == x - y assert x / y1 == x / y # Conversions assert (x1 + y1)._sage_() == x + y assert (x1 * y1)._sage_() == x * y assert (x1 ** y1)._sage_() == x ** y assert (x1 - y1)._sage_() == x - y assert (x1 / y1)._sage_() == x / y assert x1 + y1 == sympify(x + y) assert x1 * y1 == sympify(x * y) assert x1 ** y1 == sympify(x ** y) assert x1 - y1 == sympify(x - y) assert x1 / y1 == sympify(x / y) # Functions assert sin(x1) == sin(x) assert sin(x1)._sage_() == sage.sin(x) assert sin(x1) == sympify(sage.sin(x)) assert cos(x1) == cos(x) assert cos(x1)._sage_() == sage.cos(x) assert cos(x1) == sympify(sage.cos(x)) assert function_symbol('f', x1, y1)._sage_() == sage.function('f', x, y) assert function_symbol('f', 2 * x1, x1 + y1).diff(x1)._sage_() == sage.function('f', 2 * x, x + y).diff(x) # For the following test, sage needs to be modified # assert sage.sin(x) == sage.sin(x1) # Constants assert pi._sage_() == sage.pi assert E._sage_() == sage.e assert I._sage_() == sage.I assert pi == sympify(sage.pi) assert E == sympify(sage.e) # SympyConverter does not support converting the following # assert I == sympify(sage.I) # Matrix assert DenseMatrix(1, 2, [x1, y1])._sage_() == sage.matrix([[x, y]])