def test_n(): x = Symbol("x") raises(RuntimeError, lambda: (x.n())) x = 2 + I raises(RuntimeError, lambda: (x.n(real=True))) x = sqrt(Integer(4)) y = RealDouble(2.0) assert x.n(real=True) == y x = 1 + 2*I y = 1.0 + 2.0*I assert x.n() == y try: from symengine import RealMPFR x = sqrt(Integer(2)) y = RealMPFR('1.41421356237309504880169', 75) assert x.n(75, real=True) == y except ImportError: x = sqrt(Integer(2)) raises(ValueError, lambda: (x.n(75, real=True))) try: from symengine import ComplexMPC x = sqrt(Integer(2)) + 3*I y = ComplexMPC('1.41421356237309504880169', '3.0', 75) assert x.n(75) == y except ImportError: x = sqrt(Integer(2)) raises(ValueError, lambda: (x.n(75)))
def reproject_axis_gen2(X, Y, Z, axis, cal): #(phase_cal, tilt_cal, curve_cal, gibPhase_cal, gibMag_cal, ogeePhase_cal, ogeeMag_cal) = cal B = atan2(Z, X) Ydeg = cal.tilt + (-1 if axis else 1) * math.pi / 6. tanA = tan(Ydeg) normXZ = sqrt(X * X + Z * Z) asinArg = tanA * Y / normXZ sinYdeg = sin(Ydeg) cosYdeg = cos(Ydeg) sinPart = sin(B - asin(asinArg) + cal.ogeephase) * cal.ogeemag normXYZ = sqrt(X * X + Y * Y + Z * Z) modAsinArg = Y / normXYZ / cosYdeg asinOut = asin(modAsinArg) mod, acc = calc_cal_series(asinOut) BcalCurved = sinPart + cal.curve asinArg2 = asinArg + mod * BcalCurved / (cosYdeg - acc * BcalCurved * sinYdeg) asinOut2 = asin(asinArg2) sinOut2 = sin(B - asinOut2 + cal.gibpha) return B - asinOut2 + sinOut2 * cal.gibmag - cal.phase - math.pi / 2.
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 sqrt(expr): """Square root""" if type(expr) == GC: return GC(se.sqrt(expr.expr), { s: d / (2 * se.sqrt(expr.expr)) for s, d in expr.gradients.items() }) return se.sqrt(expr)
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_n_mpc(): try: from symengine import ComplexMPC x = sqrt(Integer(2)) + 3 * I y = ComplexMPC('1.41421356237309504880169', '3.0', 75) assert x.n(75) == y except ImportError: x = sqrt(Integer(2)) raises(ValueError, lambda: (x.n(75))) raise SkipTest("No MPC support")
def test_n_mpfr(): try: from symengine import RealMPFR x = sqrt(Integer(2)) y = RealMPFR('1.41421356237309504880169', 75) assert x.n(75, real=True) == y except ImportError: x = sqrt(Integer(2)) raises(ValueError, lambda: (x.n(75, real=True))) raise SkipTest("No MPFR support")
def diffable_slerp(q1, q2, t): """ !takes a long time to compile! :param q1: 4x1 Matrix :type q1: Matrix :param q2: 4x1 Matrix :type q2: Matrix :param t: float, 0-1 :type t: Union[float, Symbol] :return: 4x1 Matrix; Return spherical linear interpolation between two quaternions. :rtype: Matrix """ cos_half_theta = dot(q1, q2) if0 = -cos_half_theta q2 = diffable_if_greater_zero(if0, -q2, q2) cos_half_theta = diffable_if_greater_zero(if0, -cos_half_theta, cos_half_theta) if1 = diffable_abs(cos_half_theta) - 1.0 # enforce acos(x) with -1 < x < 1 cos_half_theta = diffable_min_fast(1, cos_half_theta) cos_half_theta = diffable_max_fast(-1, cos_half_theta) half_theta = acos(cos_half_theta) sin_half_theta = sqrt(1.0 - cos_half_theta * cos_half_theta) # prevent /0 sin_half_theta = diffable_if_eq_zero(sin_half_theta, 1, sin_half_theta) if2 = 0.001 - diffable_abs(sin_half_theta) ratio_a = sin((1.0 - t) * half_theta) / sin_half_theta ratio_b = sin(t * half_theta) / sin_half_theta return diffable_if_greater_eq_zero(if1, se.Matrix(q1), diffable_if_greater_zero(if2, 0.5 * q1 + 0.5 * q2, ratio_a * q1 + ratio_b * q2))
def quat2axisangle(q): qw, qi, qj, qk = q mag = sqrt(qi*qi+qj*qj+qk*qk + 1e-10) angle = 2 * atan2(mag, q[0]) return q[1] * angle / mag,\ q[2] * angle / mag,\ q[3] * angle / mag
def diffable_abs(x): """ :type x: Union[float, Symbol] :return: abs(x) :rtype: Union[float, Symbol] """ return se.sqrt(x**2)
def _derivatives(self, coupling_variables): ( I_mu, I_syn_mu_exc, I_syn_mu_inh, I_syn_sigma_exc, I_syn_sigma_inh, firing_rate, ) = self._unwrap_state_vector() exc_inp, inh_inp, exc_inp_sq, inh_inp_sq = self._compute_couplings( coupling_variables) I_sigma = se.sqrt( 2 * self.params["Jie_max"]**2 * I_syn_sigma_exc * self.params["tau_se"] * self.params["taum"] / ((1.0 + exc_inp) * self.params["taum"] + self.params["tau_se"]) + 2 * self.params["Jii_max"]**2 * I_syn_sigma_inh * self.params["tau_si"] * self.params["taum"] / ((1.0 + inh_inp) * self.params["taum"] + self.params["tau_si"]) + self.params["sigmai_ext"]**2) # get values from linear-nonlinear lookup table firing_rate_now = self.callback_functions["firing_rate_lookup"]( I_mu, I_sigma) tau = self.callback_functions["tau_lookup"](I_mu, I_sigma) d_I_mu = (self.params["Jie_max"] * I_syn_mu_exc + self.params["Jii_max"] * I_syn_mu_inh + system_input(self.noise_input_idx[0]) + self.params["ext_inh_current"] - I_mu) / tau d_I_syn_mu_exc = ((1.0 - I_syn_mu_exc) * exc_inp - I_syn_mu_exc) / self.params["tau_se"] d_I_syn_mu_inh = ((1.0 - I_syn_mu_inh) * inh_inp - I_syn_mu_inh) / self.params["tau_si"] d_I_syn_sigma_exc = ( (1.0 - I_syn_mu_exc)**2 * exc_inp_sq + (exc_inp_sq - 2.0 * self.params["tau_se"] * (exc_inp + 1.0)) * I_syn_sigma_exc) / (self.params["tau_se"]**2) d_I_syn_sigma_inh = ( (1.0 - I_syn_mu_inh)**2 * inh_inp_sq + (inh_inp_sq - 2.0 * self.params["tau_si"] * (inh_inp + 1.0)) * I_syn_sigma_inh) / (self.params["tau_si"]**2) # firing rate as dummy dynamical variable with infinitely fast # fixed-point dynamics d_firing_rate = -self.params["lambda"] * (firing_rate - firing_rate_now) return [ d_I_mu, d_I_syn_mu_exc, d_I_syn_mu_inh, d_I_syn_sigma_exc, d_I_syn_sigma_inh, d_firing_rate, ]
def cylinder_grasp_affordance(self, gripper, obj_input): frame = obj_input.get_frame() shape = obj_input.get_dimensions() cylinder_z = z_col(frame) cylinder_pos = pos_of(frame) gripper_x = x_col(gripper.frame) gripper_z = z_col(gripper.frame) gripper_pos = pos_of(gripper.frame) c_to_g = gripper_pos - cylinder_pos zz_align = abs(dot(gripper_z, cylinder_z)) xz_align = dot(gripper_x, cylinder_z) dist_z = dot(cylinder_z, c_to_g) border_z = (shape[2] - gripper.height) * 0.5 cap_dist_normalized_signed = dist_z / border_z cap_dist_normalized = abs(cap_dist_normalized_signed) cap_grasp = tip_at_one(-xz_align * cap_dist_normalized_signed) dist_z_center_normalized = -saturate(cap_dist_normalized) dist_ax = sp.sqrt( dot(x_col(frame), c_to_g)**2 + dot(y_col(frame), c_to_g)**2) center_grasp = (1 - dist_z_center_normalized - dist_ax) * zz_align return max(center_grasp, cap_grasp) * obj_input.get_class_probability()
def axis_angle_from_matrix(rotation_matrix): """ :param rotation_matrix: 4x4 or 3x3 Matrix :type rotation_matrix: Matrix :return: 3x1 Matrix, angle :rtype: (Matrix, Union[float, Symbol]) """ rm = rotation_matrix angle = (trace(rm[:3, :3]) - 1) / 2 angle = se.Min(angle, 1) angle = se.Max(angle, -1) angle = se.acos(angle) x = (rm[2, 1] - rm[1, 2]) y = (rm[0, 2] - rm[2, 0]) z = (rm[1, 0] - rm[0, 1]) n = se.sqrt(x * x + y * y + z * z) m = if_eq_zero(n, 1, n) axis = se.Matrix([ if_eq_zero(n, 0, x / m), if_eq_zero(n, 0, y / m), if_eq_zero(n, 1, z / m) ]) sign = diffable_sign(angle) axis *= sign angle = sign * angle return axis, angle
def quaternion_from_matrix(matrix): """ !takes a loooong time to compile! :param matrix: 4x4 or 3x3 Matrix :type matrix: Matrix :return: 4x1 Matrix :rtype: Matrix """ q = Matrix([0, 0, 0, 0]) M = Matrix(matrix) t = trace(M) if0 = t - M[3, 3] if1 = M[1, 1] - M[0, 0] m_i_i = if_greater_zero(if1, M[1, 1], M[0, 0]) m_i_j = if_greater_zero(if1, M[1, 2], M[0, 1]) m_i_k = if_greater_zero(if1, M[1, 0], M[0, 2]) m_j_i = if_greater_zero(if1, M[2, 1], M[1, 0]) m_j_j = if_greater_zero(if1, M[2, 2], M[1, 1]) m_j_k = if_greater_zero(if1, M[2, 0], M[1, 2]) m_k_i = if_greater_zero(if1, M[0, 1], M[2, 0]) m_k_j = if_greater_zero(if1, M[0, 2], M[2, 1]) m_k_k = if_greater_zero(if1, M[0, 0], M[2, 2]) if2 = M[2, 2] - m_i_i m_i_i = if_greater_zero(if2, M[2, 2], m_i_i) m_i_j = if_greater_zero(if2, M[2, 0], m_i_j) m_i_k = if_greater_zero(if2, M[2, 1], m_i_k) m_j_i = if_greater_zero(if2, M[0, 2], m_j_i) m_j_j = if_greater_zero(if2, M[0, 0], m_j_j) m_j_k = if_greater_zero(if2, M[0, 1], m_j_k) m_k_i = if_greater_zero(if2, M[1, 2], m_k_i) m_k_j = if_greater_zero(if2, M[1, 0], m_k_j) m_k_k = if_greater_zero(if2, M[1, 1], m_k_k) t = if_greater_zero(if0, t, m_i_i - (m_j_j + m_k_k) + M[3, 3]) q[0] = if_greater_zero( if0, M[2, 1] - M[1, 2], if_greater_zero(if2, m_i_j + m_j_i, if_greater_zero(if1, m_k_i + m_i_k, t))) q[1] = if_greater_zero( if0, M[0, 2] - M[2, 0], if_greater_zero(if2, m_k_i + m_i_k, if_greater_zero(if1, t, m_i_j + m_j_i))) q[2] = if_greater_zero( if0, M[1, 0] - M[0, 1], if_greater_zero(if2, t, if_greater_zero(if1, m_i_j + m_j_i, m_k_i + m_i_k))) q[3] = if_greater_zero(if0, t, m_k_j - m_j_k) q *= 0.5 / sp.sqrt(t * M[3, 3]) return q
def acosh(expr): """Hyperbolic arccosine""" if type(expr) == GC: return GC(se.acosh(expr.expr), { s: d / se.sqrt(expr.expr**2 - 1) for s, d in expr.gradients.items() }) return se.acosh(expr)
def acos(expr): """Arccosine""" if type(expr) == GC: return GC(se.acos(expr.expr), { s: -d / se.sqrt(1 - expr.expr**2) for s, d in expr.gradients.items() }) return se.acos(expr)
def preMatrixMinus(self, a): b = si.sqrt(1 + a**2) matrix = si.zeros(2) matrix[0, 0] = 1 - b matrix[0, 1] = -a matrix[1, 0] = a matrix[1, 1] = 1 + b return matrix
def abs(expr): """Absolute value""" if type(expr) == GC: return GC( fake_abs(expr.expr), { s: d * expr.expr / se.sqrt(expr.expr**2) for s, d in expr.gradients.items() }) return fake_abs(expr)
def test_Pow_base_exp(): x = Symbol("x") y = Symbol("y") e = Pow(x + y, 2) assert isinstance(e, Pow) assert e.exp == 2 assert e.base == x + y assert sqrt(x - 1).as_base_exp() == (x - 1, Rational(1, 2))
def test_broadcast(): a = np.linspace(-np.pi, np.pi) inp = np.ascontiguousarray(np.vstack((np.cos(a), np.sin(a))).T) # 50 rows 2 cols assert inp.flags['C_CONTIGUOUS'] 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 norm(v): """ :type v: Matrix :return: |v|_2 :rtype: Union[float, Symbol] """ r = 0 for x in v: r += x**2 return se.sqrt(r)
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 f_Xt(self, x=Symbol('x'), t=Symbol('t', positive=True), order=3, simplify=True, from_cache=True): if from_cache and self.cached_order == order and self.cached_f_Xt is not None: return self.cached_f_Xt expr1_f_xt = self.Sigma(t) expr2_f_xt = x / sqrt(expr1_f_xt) # coef expr3_f_xt = 0.5 * self.n(x, expr1_f_xt) if order <= 1: if simplify: output = self.simplify(expr3_f_xt * 2) else: output = expr3_f_xt * 2 self.cached_order = order self.cached_f_Xt = output return output # term1 expr4_f_xt = self.q3(t) / (expr1_f_xt**3) * self.hermite(expr2_f_xt, 6) # term2 if order == 2: expr5_f_xt = self.q4(t) / (expr1_f_xt**2) * self.hermite( expr2_f_xt, 4) else: expr5_f_xt = (2 * self.q2(t) + self.q4(t)) / ( expr1_f_xt**2) * self.hermite(expr2_f_xt, 4) # term3 expr6_f_xt = 2 * self.q1(t) / (expr1_f_xt**1.5) * self.hermite( expr2_f_xt, 3) # term4 expr7_f_xt = self.q5(t) / expr1_f_xt * self.hermite(expr2_f_xt, 2) if simplify: output = self.simplify( expr3_f_xt * (expr4_f_xt + expr5_f_xt + expr6_f_xt + expr7_f_xt + 2)) else: output = expr3_f_xt * (expr4_f_xt + expr5_f_xt + expr6_f_xt + expr7_f_xt + 2) self.cached_order = order self.cached_f_Xt = output return output
def test_sin(): x = Symbol("x") e = sin(x) assert e == sin(x) assert e != cos(x) assert sin(x).diff(x) == cos(x) assert cos(x).diff(x) == -sin(x) e = sqrt(x).diff(x).diff(x) f = sin(e) g = f.diff(x).diff(x) assert isinstance(g, Add)
def test_n(): x = Symbol("x") raises(RuntimeError, lambda: (x.n())) x = 2 + I raises(RuntimeError, lambda: (x.n(real=True))) x = sqrt(Integer(4)) y = RealDouble(2.0) assert x.n(real=True) == y x = 1 + 2 * I y = 1.0 + 2.0 * I assert x.n() == y
def _get_current_sigma(self, I_syn_sigma_exc, I_syn_sigma_inh, exc_inp, inh_inp, J_exc_max, J_inh_max, ext_sigma): """ Compute membrane current standard deviation sigma. """ return se.sqrt( 2 * J_exc_max**2 * I_syn_sigma_exc * self.params["tau_se"] * (self.params["C"] / self.params["gL"]) / ((1.0 + exc_inp) * (self.params["C"] / self.params["gL"]) + self.params["tau_se"]) + 2 * J_inh_max**2 * I_syn_sigma_inh * self.params["tau_si"] * (self.params["C"] / self.params["gL"]) / ((1.0 + inh_inp) * (self.params["C"] / self.params["gL"]) + self.params["tau_si"]) + ext_sigma**2)
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_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 axis_angle_from_quaternion(x, y, z, w): """ :type x: Union[float, Symbol] :type y: Union[float, Symbol] :type z: Union[float, Symbol] :type w: Union[float, Symbol] :return: 4x1 Matrix :rtype: Matrix """ # TODO buggy, angle goes from 0 - 2*pi instead of -pi - +pi w2 = sp.sqrt(1 - w**2) angle = (2 * sp.acos(w)) x = x / w2 y = y / w2 z = z / w2 return sp.Matrix([x, y, z]), angle
def axis_angle_from_quaternion(x, y, z, w): """ :type x: Union[float, Symbol] :type y: Union[float, Symbol] :type z: Union[float, Symbol] :type w: Union[float, Symbol] :return: 4x1 Matrix :rtype: Matrix """ l = norm([x, y, z, w]) x, y, z, w = x / l, y / l, z / l, w / l w2 = se.sqrt(1 - w**2) angle = (2 * se.acos(se.Min(se.Max(-1, w), 1))) m = if_eq_zero(w2, 1, w2) # avoid /0 x = if_eq_zero(w2, 0, x / m) y = if_eq_zero(w2, 0, y / m) z = if_eq_zero(w2, 1, z / m) return se.Matrix([x, y, z]), angle
def axis_angle_from_matrix(rotation_matrix): """ :param rotation_matrix: 4x4 or 3x3 Matrix :type rotation_matrix: Matrix :return: 3x1 Matrix, angle :rtype: (Matrix, Union[float, Symbol]) """ # TODO nan if angle 0 # TODO use 'if' to make angle always positive? rm = rotation_matrix angle = (trace(rm[:3, :3]) - 1) / 2 angle = sp.acos(angle) x = (rm[2, 1] - rm[1, 2]) y = (rm[0, 2] - rm[2, 0]) z = (rm[1, 0] - rm[0, 1]) n = sp.sqrt(x * x + y * y + z * z) axis = sp.Matrix([x / n, y / n, z / n]) return axis, angle
def solve_chi_saddlepoint(mu, Sigma): """Compute the saddlepoint approximation for the generalized chi square distribution given a mean and a covariance matrix. Currently has two different ways of solving: 1. If the mean is close to zero, the system can be solved symbolically.""" P = None eigenvalues, eigenvectors = np.linalg.eig(Sigma) if (eigenvectors == np.diag(eigenvalues)).all(): P = np.eye(len(mu)) else: P = eigenvectors.T Sigma_12 = np.linalg.cholesky(Sigma) b = P @ Sigma_12 @ mu x = sym.Symbol("x") t = sym.Symbol("t") # Cumulant function K = 0 for i, l in enumerate(eigenvalues): K += (t * b[i]**2 * l) / (1 - 2 * t * l) - 1 / 2 * sym.log(1 - 2 * l * t) Kp = sym.diff(K, t).simplify() Kpp = sym.diff(K, t, t).simplify() roots = sym.lib.symengine_wrapper.solve(sym.Eq(Kp, x), t).args if len(roots) > 1: for expr in roots: trial = Kpp.subs(t, expr).subs(x, np.dot(b, b)) if trial >= 0.0: s_hat = expr else: s_hat = roots[0] f = 1 / sym.sqrt(2 * sym.pi * Kpp.subs( t, s_hat)) * sym.exp(K.subs(t, s_hat) - s_hat * x) fp = sym.Lambdify(x, f.simplify()) c = integrate.quad(fp, 0, np.inf)[0] return lambda x: 1 / c * fp(x)
def sym_real_norm_2(x): return sym.sqrt((x.T*x)[0, 0])