def __init__(self, n: int, r: Callable, obstacle: Union[np.ndarray, Callable] = None, need_hessian: bool = True) -> None: super().__init__(n, r, obstacle) _, grad_expression, hessian_expression = get_symbolic_exp( get_aim_func(self.n, self.get_height, get_cal_area_func(sympy_sqrt)), self.dim, need_hessian) print('Start evaling the gradient expression...') start = time.time() grad_strs = str(Array(grad_expression)[0]) self._cal_gradient = eval('lambda x:' + grad_strs) end = time.time() end_sep = '' if need_hessian else '\n' print( f'time cost in evaling gradient: {round(end - start, 3)} second(s){end_sep}' ) if need_hessian: print('Start evaling hessian expression...') start = time.time() hessian_strs = str(Array(hessian_expression)) self._cal_hessian = eval('lambda x:' + hessian_strs) end = time.time() print( f'time cost in evaling hessian: {round(end - start, 3)} second(s)\n' )
def __init__(self, syms_arr, exprs_arr, syms=None, exprs=None): for sym_arr in syms_arr: assert (isinstance(sym_arr, _np.array)) assert (sym_arr.ndim == 1) for expr_arr in exprs_arr: assert (isinstance(expr_arr, _np.array)) assert (expr_arr.shape == tuple(sym_arr.size for sym_arr in syms_arr)) self._syms_arr = list(syms_arr) self._exprs_arr = list(exprs_arr) from sympy import Array, oo if exprs is not None: if not isinstance(exprs, list) and not isinstance(exprs, Array): raise ValueError( "The ctor arg of GeometryMap -- exprs -- should be a list of sympy expressions." ) self._exprs = Array(exprs) else: self._exprs = Array([None] * len(exprs_arr)) # if not isinstance(syms, list): # raise ValueError("The ctor arg of GeometryMap -- syms -- should be a list of sympy variables, or a list of (sympy.Symbol, inf, sup)") self._syms = [] for sym in syms: if isinstance(sym, tuple): assert (len(sym) == 3) self._syms.append(sym) else: self._syms.append((sym, -oo, +oo))
def test_TransformationMatrix_classmethod_new2old(cart2sph_matrix): obj = cart2sph_matrix cmp_array = Array([[1 / cos(q), 1 / sin(q)], [-1 / (p * sin(q)), 1 / (p * cos(q))]]) zero_array = Array(np.zeros(shape=cmp_array.shape, dtype=int)) assert simplify_sympy_array(cmp_array - obj) == zero_array
def geodesic_ncurve(surface: ParametricSurface, ic_uv, ic_uv_t, t1=5, dt=0.05): from sympy import lambdify from scipy.integrate import ode as sciode import numpy as np from sympy import symbols, Function, Array, tensorproduct, tensorcontraction t = symbols('t', real=True) u = Function(surface.sym(0), real=True)(t) v = Function(surface.sym(1), real=True)(t) second_term_tensor = tensorproduct( surface.christoffel_symbol.tensor().subs( {surface.sym(0):u, surface.sym(1):v}), Array([u, v]).diff(t), Array([u, v]).diff(t)) second_term_tensor = tensorcontraction(second_term_tensor, (1, 3), (2, 4)) u_t = Function(str(u)+'^{\prime}', real=True)(t) v_t = Function(str(v)+'^{\prime}', real=True)(t) lambdify_sympy = lambdify((u, u_t, v, v_t), [ u_t, -second_term_tensor[0].subs({u.diff(t):u_t, v.diff(t):v_t}), v_t, -second_term_tensor[1].subs({u.diff(t):u_t, v.diff(t):v_t})]) x0, t0 = [ic_uv[0], ic_uv_t[0], ic_uv[1], ic_uv_t[1]], 0.0 scioder = sciode(lambda t,X: lambdify_sympy(*X)).set_integrator('vode', method='bdf') scioder.set_initial_value(x0, t0) num_of_t = int(t1 / dt); # num_of_t u_arr = np.empty((num_of_t, 4)); u_arr[0] = x0 t_arr = np.arange(num_of_t) * dt i = 0 while scioder.successful() and i < num_of_t-1: i += 1 u_arr[i] = scioder.integrate(scioder.t+dt) return t_arr, (u_arr[:, 0], u_arr[:, 2])
def test_array_expr_reshape(): A = MatrixSymbol("A", 2, 2) B = ArraySymbol("B", (2, 2, 2)) C = Array([1, 2, 3, 4]) expr = Reshape(A, (4,)) assert expr.expr == A assert expr.shape == (4,) assert expr.as_explicit() == Array([A[0, 0], A[0, 1], A[1, 0], A[1, 1]]) expr = Reshape(B, (2, 4)) assert expr.expr == B assert expr.shape == (2, 4) ee = expr.as_explicit() assert isinstance(ee, ImmutableDenseNDimArray) assert ee.shape == (2, 4) assert ee == Array([[B[0, 0, 0], B[0, 0, 1], B[0, 1, 0], B[0, 1, 1]], [B[1, 0, 0], B[1, 0, 1], B[1, 1, 0], B[1, 1, 1]]]) expr = Reshape(A, (k, 2)) assert expr.shape == (k, 2) raises(ValueError, lambda: Reshape(A, (2, 3))) raises(ValueError, lambda: Reshape(A, (3,))) expr = Reshape(C, (2, 2)) assert expr.expr == C assert expr.shape == (2, 2) assert expr.doit() == Array([[1, 2], [3, 4]])
def laplace0(rank0_): "Copied from Mathematica script" temp1 = Array([diff(rank0_, x) for x in xx]) temp2 = Array([[ diff(temp1[i], xx[k]) - sum([Gamma[sigma, i, k] * temp1[sigma] for sigma in range(dim)]) for k in range(dim) ] for i in range(dim)]) return simplify(sum([g_inv[k, k] * temp2[k, k] for k in range(dim)]))
def __init__(self, deg, basis_type): deg = int(deg) if basis_type == 'L': #1D Lagrange basis of degree deg z = Symbol('z') Xi = np.linspace(-1, 1, deg + 1) def lag_basis(k): n = 1. for i in range(len(Xi)): if k != i: n *= (z - Xi[i]) / (Xi[k] - Xi[i]) return n N = Array([simplify(lag_basis(m)) for m in range(deg + 1)]) dfN = diff(N, z) + 1.e-25 * N self.Ns = lambdify(z, N, 'numpy') self.dN = lambdify(z, dfN, 'numpy') self.enrich = enrch elif basis_type == 'M': #1D Legendre Polynomials (Fischer calls this spectral) z = Symbol('z') x = Symbol('x') def gen_legendre_basis(n): if n == -2: return (1 - 1 * z) / 2 elif n == -1: return (1 + 1 * z) / 2 else: return ((2 * (n + 3) - 3) / 2.)**0.5 * integrate( legendre((n + 1), x), (x, -1, z)) N = Array([gen_legendre_basis(i - 2) for i in range(deg + 1)]) N2 = N.tolist() N2[-1] = N[1] N2[1] = N[-1] N = Array(N2) dfN = diff(N, z) + 1.e-25 * N # print(N) self.Ns = lambdify(z, N, 'numpy') self.dN = lambdify(z, dfN, 'numpy') self.enrich = enrch elif basis_type == 'G': #1D GFEM Functions (degree denotes the total approximation space) z = Symbol('z') Xi = np.linspace(-1, 1, deg + 1) def lag_basis(k): n = 1. for i in range(len(Xi)): if k != i: n *= (z - Xi[i]) / (Xi[k] - Xi[i]) return n N = Array([simplify(lag_basis(m)) for m in range(deg + 1)]) dfN = diff(N, z) + 1.e-25 * N self.Ns = lambdify(z, N, 'numpy') self.dN = lambdify(z, dfN, 'numpy') self.enrich = enrch #Enrichment order corresponding to GFEM shape functions else: raise Exception('Element type not implemented yet')
def test_TransformationMatrix_inv_function(cart2sph_matrix): assert cart2sph_matrix._inv is None obj = cart2sph_matrix.inv() assert cart2sph_matrix._inv is not None obj = cart2sph_matrix.inv() cmp_array = Array([[cos(q), sin(q)], [-1 * p * sin(q), p * cos(q)]]) zero_array = Array(np.zeros(shape=cmp_array.shape, dtype=int)) assert simplify_sympy_array(cmp_array - obj) == zero_array
def test_array_expr_as_explicit_with_explicit_component_arrays(): # Test if .as_explicit() works with explicit-component arrays # nested in array expressions: from sympy.abc import x, y, z, t A = Array([[x, y], [z, t]]) assert ArrayTensorProduct(A, A).as_explicit() == tensorproduct(A, A) assert ArrayDiagonal(A, (0, 1)).as_explicit() == tensordiagonal(A, (0, 1)) assert ArrayContraction(A, (0, 1)).as_explicit() == tensorcontraction(A, (0, 1)) assert ArrayAdd(A, A).as_explicit() == A + A assert ArrayElementwiseApplyFunc(sin, A).as_explicit() == A.applyfunc(sin) assert PermuteDims(A, [1, 0]).as_explicit() == permutedims(A, [1, 0]) assert Reshape(A, [4]).as_explicit() == A.reshape(4)
def __init__(self, ref_el, degree): if degree < 1: raise Exception("Trimmed Serendipity_k edge elements only valid for k >= 1") flat_el = flatten_reference_cube(ref_el) dim = flat_el.get_spatial_dimension() if dim != 2: if dim != 3: raise Exception("Trimmed Serendipity_k edge elements only valid for dimensions 2 and 3") verts = flat_el.get_vertices() dx = ((verts[-1][0] - x)/(verts[-1][0] - verts[0][0]), (x - verts[0][0])/(verts[-1][0] - verts[0][0])) dy = ((verts[-1][1] - y)/(verts[-1][1] - verts[0][1]), (y - verts[0][1])/(verts[-1][1] - verts[0][1])) x_mid = 2*x-(verts[-1][0] + verts[0][0]) y_mid = 2*y-(verts[-1][1] + verts[0][1]) try: dz = ((verts[-1][2] - z)/(verts[-1][2] - verts[0][2]), (z - verts[0][2])/(verts[-1][2] - verts[0][2])) z_mid = 2*z-(verts[-1][2] + verts[0][2]) except IndexError: dz = None z_mid = None if dim == 2: EL = e_lambda_1_2d_part_one(degree, dx, dy, x_mid, y_mid) else: EL = e_lambda_1_3d_trimmed(degree, dx, dy, dz, x_mid, y_mid, z_mid) if degree >= 2: if dim == 2: FL = trimmed_f_lambda_2d(degree, dx, dy, x_mid, y_mid) else: FL = f_lambda_1_3d_trimmed(degree, dx, dy, dz, x_mid, y_mid, z_mid) else: FL = () if dim == 3: if degree >= 4: IL = I_lambda_1_3d(degree, dx, dy, dz, x_mid, y_mid, z_mid) + I_lambda_1_tilde_3d(degree, dx, dy, dz, x_mid, y_mid, z_mid) else: IL = () Sminus_list = EL + FL if dim == 3: Sminus_list = Sminus_list + IL if dim == 2: self.basis = {(0, 0): Array(Sminus_list)} else: self.basis = {(0, 0, 0): Array(Sminus_list)} super(TrimmedSerendipityEdge, self).__init__(ref_el=ref_el, degree=degree, mapping="covariant piola")
def Ejp(x, xalph, halph, enrich): z = Symbol('z') N = Array([((z - xalph) / halph)**n + 1.e-26 * (z - xalph) / halph for n in range(enrich + 1) ]) #shape consistency take E_o = 1 dfN = lambdify(z, diff(N, z) + 1.e-26 * N, 'numpy') #shape consistency return dfN(x)
def __init__(self, ref_el, degree): if degree < 1: raise Exception("Trimmed serendipity face elements only valid for k >= 1") flat_el = flatten_reference_cube(ref_el) dim = flat_el.get_spatial_dimension() if dim != 2: raise Exception("Trimmed serendipity face elements only valid for dimensions 2") verts = flat_el.get_vertices() dx = ((verts[-1][0] - x)/(verts[-1][0] - verts[0][0]), (x - verts[0][0])/(verts[-1][0] - verts[0][0])) dy = ((verts[-1][1] - y)/(verts[-1][1] - verts[0][1]), (y - verts[0][1])/(verts[-1][1] - verts[0][1])) x_mid = 2*x-(verts[-1][0] + verts[0][0]) y_mid = 2*y-(verts[-1][1] + verts[0][1]) EL = e_lambda_1_2d_part_one(degree, dx, dy, x_mid, y_mid) if degree >= 2: FL = trimmed_f_lambda_2d(degree, dx, dy, x_mid, y_mid) else: FL = () Sminus_list = EL + FL Sminus_list = [[-a[1], a[0]] for a in Sminus_list] self.basis = {(0, 0): Array(Sminus_list)} super(TrimmedSerendipityFace, self).__init__(ref_el=ref_el, degree=degree, mapping="contravariant piola")
def Ej(x, xalph, halph, enrich): z = Symbol('z') N = Array([((z - xalph) / halph)**n + 1.e-26 * (z - xalph) / halph for n in range(enrich + 1) ]) #shape consistency take E_o = 1 Nf = lambdify(z, N, 'numpy') return Nf(x)
def steepest_descent(f, alpha, max_iter, threshold, X0, *func_vars): """The steepest descent algorithm for numerically finding the minimum value of a function, based on the gradient of that function. It uses the gradient function (or the scalar derivative, if the function is single-valued) to determine the direction in which a function is decreasing most rapidly. Each successive iteration of the algorithm moves along this direction for a specified step size, and recomputes the gradient to determine the new direction to travel. Args: f (function): function to minimize. alpha (float): learning rate. max_iter (int): the maximum number of iterations. threshold (float): whenever the computed "NEW POINT" [x1, x2, x3, ...] changes is less than threshold (sum of changes of all components), the function stops. X0 (array_like): an array like of initial point. For example if the function f is a two variable function, then initial point could be a tuple or list or array with length 2. e.g. X0 = [0, 0] *func_vars (sympy.Symbol): a list of function variables. the derivative of the function f will be computed with respect to these parameters. Returns: list: The history of X0, X1, X2, ..., xn. The first item is the initial point (X0) and the last one is the best point that minimizes the function f. Examples: >>> from sympy import symbols >>> def f1(x1, x2): return x1**2 + 25 * x2**2 >>> x1, x2 = symbols('x1 x2') >>> alpha = 0.01 >>> threshold = 0.001 >>> X0 = [0.5, 0.5] >>> max_iter = 300 >>> X = steepest_descent(f1, alpha, max_iter, threshold, X0, x1, x2) >>> print('First 5 points:\n', np.array(X[:5], dtype=np.float)) First 5 points: [[0.5 0.5 ] [0.49 0.25 ] [0.4802 0.125 ] [0.470596 0.0625 ] [0.46118408 0.03125 ]] >>> print('Minimum point:\n', np.round(np.array(X[-1], dtype=np.float))) Minimum point: [0. 0.] """ grad = derive_by_array(f(*func_vars), func_vars) X0 = Array( X0 ) # X0 should be an array to support subtraction (old_X - alpha * grad(f, old_X)) X = [X0] # list of history old_X = X0 new_X = old_X - alpha * grad.xreplace(dict(zip(func_vars, old_X))) i = 1 while np.sum(np.abs(new_X - old_X) > threshold) and i < max_iter: X.append(new_X) old_X = new_X new_X = old_X - alpha * grad.xreplace(dict(zip(func_vars, old_X))) i += 1 return X
def __init__(self, syms, exprs): from sympy import Array, oo if not isinstance(exprs, list) and not isinstance(exprs, Array): raise ValueError( "The ctor arg of GeometryMap -- exprs -- should be a list of sympy expressions." ) self._exprs = Array(exprs) # if not isinstance(syms, list): # raise ValueError("The ctor arg of GeometryMap -- syms -- should be a list of sympy variables, or a list of (sympy.Symbol, inf, sup)") self._syms = [] for sym in syms: if isinstance(sym, tuple): assert (len(sym) == 3) self._syms.append(sym) else: self._syms.append((sym, -oo, +oo))
def __new__(cls, symbol, coords, matrix, **kwargs): """ Create a new Metric object. Parameters ---------- symbol : str Name of the tensor and the symbol to denote it by when printed. coords : iterable List of ~sympy.Symbol objects to denote the coordinates by which derivatives are taken with respect to. matrix : (list, tuple, ~sympy.Matrix, ~sympy.Array) Matrix representation of the tensor to be used in substitution. Can be of any type that is acceptable by ~sympy.Array. Examples -------- >>> from sympy import diag, symbols >>> from einsteinpy.symbolic.tensor import indices, expand_tensor >>> from einsteinpy.symbolic.metric import Metric >>> t, x, y, z = symbols('t x y z') >>> eta = Metric('eta', [t, x, y, z], diag(1, -1, -1, -1)) >>> mu, nu = indices('mu nu', eta) >>> expr = eta(mu, nu) * eta(-mu, -nu) >>> expand_tensor(expr) 4 """ array = Array(matrix) if array.rank() != 2 or array.shape[0] != array.shape[1]: raise ValueError( "matrix must be square, received matrix of shape {}".format( array.shape)) obj = TensorIndexType.__new__( cls, symbol, metric=cls._MetricId(symbol, False), dim=array.shape[0], dummy_fmt=symbol, **kwargs, ) obj = AbstractTensor.__new__(cls, obj, array) obj.metric = Tensor(obj.name, array, obj, covar=(-1, -1)) obj.coords = tuple(coords) ReplacementManager[obj] = array return obj
def __init__(self, ref_el, degree): if degree < 1: raise Exception("Trimmed serendipity face elements only valid for k >= 1") flat_el = flatten_reference_cube(ref_el) dim = flat_el.get_spatial_dimension() if dim != 2: if dim != 3: raise Exception("Trimmed serendipity face elements only valid for dimensions 2 and 3") verts = flat_el.get_vertices() dx = ((verts[-1][0] - x)/(verts[-1][0] - verts[0][0]), (x - verts[0][0])/(verts[-1][0] - verts[0][0])) dy = ((verts[-1][1] - y)/(verts[-1][1] - verts[0][1]), (y - verts[0][1])/(verts[-1][1] - verts[0][1])) x_mid = 2*x-(verts[-1][0] + verts[0][0]) y_mid = 2*y-(verts[-1][1] + verts[0][1]) try: dz = ((verts[-1][2] - z)/(verts[-1][2] - verts[0][2]), (z - verts[0][2])/(verts[-1][2] - verts[0][2])) z_mid = 2*z-(verts[-1][2] + verts[0][2]) except IndexError: dz = None z_mid = None if dim == 3: FL = f_lambda_2_3d(degree, dx, dy, dz, x_mid, y_mid, z_mid) if (degree > 1): IL = I_lambda_2_3d(degree, dx, dy, dz, x_mid, y_mid, z_mid) else: IL = () Sminus_list = FL + IL self.basis = {(0, 0, 0): Array(Sminus_list)} super(TrimmedSerendipityDiv, self).__init__(ref_el=ref_el, degree=degree, mapping="contravariant piola") else: # Put all 2 dimensional stuff here. if degree < 1: raise Exception("Trimmed serendipity face elements only valid for k >= 1") EL = e_lambda_1_2d_part_one(degree, dx, dy, x_mid, y_mid) if degree >= 2: FL = trimmed_f_lambda_2d(degree, dx, dy, x_mid, y_mid) else: FL = () Sminus_list = EL + FL Sminus_list = [[-a[1], a[0]] for a in Sminus_list] self.basis = {(0, 0): Array(Sminus_list)} super(TrimmedSerendipityDiv, self).__init__(ref_el=ref_el, degree=degree, mapping="contravariant piola")
def test_Tensor(): x, y, z = symbols("x y z") test_list = [[[x, y], [y, sin(2 * z) - 2 * sin(z) * cos(z)]], [[z ** 2, x], [y, z]]] test_arr = Array(test_list) obj1 = Tensor(test_arr) obj2 = Tensor(test_list) assert obj1.tensor() == obj2.tensor() assert isinstance(obj1.tensor(), Array)
def test_Tensor(): from sympy.tensor.tensor import tensorsymmetry (coords, metric) = _generate_simple() T = Tensor("T", coords, metric) assert isinstance(T, TensorHead) assert T.as_array() == Array(coords) assert T.covar == (1,) assert T.symmetry == tensorsymmetry([1])
def test_create_from_matrix(self): """Test creation from a matrix""" cs = coords.toroidal_coords(dim=2) a, b = symbols('a b') matrix = Array([[a, 0], [0, b]]) with pytest.raises(ValueError): metric.Metric(matrix=matrix) g = metric.Metric(matrix=matrix, coord_system=cs) assert isinstance(g, metric.Metric)
def test_array_negative_indices(): for ArrayType in array_types: test_array = ArrayType([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]) assert test_array[:, -1] == Array([5, 10]) assert test_array[:, -2] == Array([4, 9]) assert test_array[:, -3] == Array([3, 8]) assert test_array[:, -4] == Array([2, 7]) assert test_array[:, -5] == Array([1, 6]) assert test_array[:, 0] == Array([1, 6]) assert test_array[:, 1] == Array([2, 7]) assert test_array[:, 2] == Array([3, 8]) assert test_array[:, 3] == Array([4, 9]) assert test_array[:, 4] == Array([5, 10]) raises(ValueError, lambda: test_array[:, -6]) raises(ValueError, lambda: test_array[-3, :]) assert test_array[-1, -1] == 10
def get_symbolic_empirical_distribution_function(t_array): """ Возвращает символьное представление эмпирической функции :param t_array: исходные измерения :return: эмпирическая функция распределения """ ar = Array(t_array) n = len(t_array) i, x_arg = symbols("i x", integer=True) return (summation(Heaviside(x_arg - ar[i]), (i, 0, n - 1)) / n, x_arg)
def compute_Gamma(g_deriv, gUP): """Return Christoffel symbols """ g_derivT = Array([(g_deriv[:, :, i]).transpose() for i in range(4)]) gUgd = tensorproduct(gUP, g_deriv) gUgdT = tensorproduct(gUP, g_derivT) return 1 / 2 * (tensorcontraction(gUgd, (1, 3)) + tensorcontraction( gUgdT, (1, 3)) - tensorcontraction(gUgd, (1, 2)))
def __init__(self,deg,basis_type): deg = int(deg) from sympy import Symbol,diff,Array,lambdify,legendre,integrate,simplify,permutedims if basis_type == 'L': #1D Lagrange basis of degree deg z=Symbol('z') Xi=np.linspace(-1,1,deg+1) def lag_basis(k): n = 1. for i in range(len(Xi)): if k != i: n *= (z-Xi[i])/(Xi[k]-Xi[i]) return n N = Array([simplify(lag_basis(m)) for m in range(deg+1)]) dfN = diff(N,z)+1.e-25*N self.Ns=lambdify(z,N,'numpy') self.dN=lambdify(z,dfN,'numpy') # if deg==2.: # denotes the number of nodes # N=1/2*Array([1-z,1+z]) # dfN=diff(N,z) # self.Ns=lambdify(z,N,'numpy') # self.dN=lambdify(z,dfN,'numpy') # elif deg==3.: # N=1/2*Array([z*(z-1),2*(1+z)*(1-z),z*(1+z)]) # dfN=diff(N,z) # self.Ns=lambdify(z,N,'numpy') # self.dN=lambdify(z,dfN,'numpy') # elif deg==4.: #not implemented yet. the no. of nodes change. define a general geom.nNnodes (?) # N=1/2*Array([z*(z-1),2*(1+z)*(1-z),z*(1+z)]) # dfN=diff(N,z) # self.Ns=lambdify(z,N,'numpy') # self.dN=lambdify(z,dfN,'numpy') # else: # raise Exception('Element type not implemented yet') elif basis_type == 'M': #1D Legendre Polynomials (Fischer calls this spectral) z = Symbol('z') x=Symbol('x') def gen_legendre_basis(n): if n==-2: return (1-1*z)/2 elif n==-1: return (1+1*z)/2 else: return ((2*(n+3)-3)/2.)**0.5*integrate(legendre((n+1),x),(x,-1,z)) N=Array([gen_legendre_basis(i-2) for i in range(deg+1)]) # print(N) N2 = N.tolist() N2[-1] = N[1] N2[1] = N[-1] #N[-1] = N[-1] - N[1] N=Array(N2) dfN=diff(N,z)+1.e-25*N # print(N) self.Ns=lambdify(z,N,'numpy') self.dN=lambdify(z,dfN,'numpy') else: raise Exception('Element type not implemented yet')
def test_Tensor_covariance_transform(): (coords, t, r, th, ph, schw, g, mu, nu) = _generate_schwarzschild() E, p1, p2, p3 = symbols("E p_1:4", positive=True) p = Tensor("p", [E, p1, p2, p3], g) res = p.covariance_transform(-mu) expect = Array( [E * (1 - 1 / r), -p1 / (1 - 1 / r), -p2 * r ** 2, -p3 * r ** 2 * sin(th) ** 2] ) assert res[0].equals(expect[0]) assert res[1].equals(expect[1]) assert res[2].equals(expect[2]) assert res[3].equals(expect[3])
class GeometryMap: """Base class for geometry map. """ def __init__(self, syms, exprs): from sympy import Array, oo if not isinstance(exprs, list) and not isinstance(exprs, Array): raise ValueError( "The ctor arg of GeometryMap -- exprs -- should be a list of sympy expressions." ) self._exprs = Array(exprs) # if not isinstance(syms, list): # raise ValueError("The ctor arg of GeometryMap -- syms -- should be a list of sympy variables, or a list of (sympy.Symbol, inf, sup)") self._syms = [] for sym in syms: if isinstance(sym, tuple): assert (len(sym) == 3) self._syms.append(sym) else: self._syms.append((sym, -oo, +oo)) @property def exprs(self): return self._exprs def expr(self, i: int): return self._exprs[i] def subs(self, *arg): return GeometryMap(self, self._exprs.subs(*arg), self._syms) @property def syms(self): return [sym[0] for sym in self._syms] def sym(self, i: int): return self._syms[i][0] @property def sym_limits(self): return [sym[1:] for sym in self._syms] def sym_limit(self, i: int): return self._syms[i][1:] @cached_property def jacobian(self): from sympy import Array return self.exprs.diff(Array(self.syms)) def lambdified(self, *arg, **kwarg): from sympy import lambdify return lambdify(self.syms, self.exprs.tolist(), *arg, **kwarg)
def test_issue_18361(): A = Array([sin(2 * x) - 2 * sin(x) * cos(x)]) B = Array([sin(x)**2 + cos(x)**2, 0]) C = Array([(x + x**2)/(x*sin(y)**2 + x*cos(y)**2), 2*sin(x)*cos(x)]) assert simplify(A) == Array([0]) assert simplify(B) == Array([1, 0]) assert simplify(C) == Array([x + 1, sin(2*x)])
def competition_compare_PAF(n, Q, lamb_0=None, plot=False): """" Simulates the link across fitnesses for the PAF model and applies the ABS measure to the empirical and theoretical sequence :param n = the number of vertices :param Q = the fitness probability distribution :param lamb_0: if None, calculate it, otherwise use the given value """ # Create an instance of the PAF graph G, fitness = paf_graph(n, Q) # Compute lamb_0 based on Q => solve equation (if not given) if lamb_0 is None: Qs = Array(Q) l, j = symbols('l,j') eq = summation(j * Qs[j - 1] / (l - j), (j, 1, len(Q))) lamb_0 = max(np.abs(solve(eq - 1, l))) # For each fitness value, store the total degree degrees = list(dict(G.degree()).values()) fit_link = {el: 0 for el in range(1, len(Q) + 1)} for i in range(len(degrees)): fit_link[fitness[i]] += degrees[i] # Make a list of the fitness values and the corresponding counts link_k = list(fit_link.keys()) link_v = list(fit_link.values()) link_k, link_v = zip(*sorted(zip(link_k, link_v))) # sort ascending link_v = [l / n for l in link_v] # scale by n # Compute the nu sequence nu = [lamb_0 * Q[j - 1] / (lamb_0 - j) for j in range(1, len(Q) + 1)] # Compute the sum of absolute differences abs_difference = np.abs(np.array(nu) - np.array(link_v)) ABS = sum(abs_difference) # Make a bar plot if Plot=True if plot: plt.plot([i for i in range(1, len(Q) + 1)], nu, 'ro', label='Nu sequence') plt.bar(link_k, link_v, label='Scaled link count') plt.title('Scaled link count per fitness value, n = %i, ABS = %5.4f' % (n, ABS)) plt.xlabel('Fitness value') plt.ylabel('Scaled link count') plt.legend() plt.show() return ABS
def deg_compare_PAF_sim(n, Q, I): Qs = Array(Q) l, j = symbols('l,j') eq = summation(j * Qs[j - 1] / (l - j), (j, 1, len(Q))) lamb_0 = max(np.abs(solve(eq - 1, l))) abs_values = np.zeros(I) for i in range(I): print(i) abs_values[i] = deg_compare_PAF(n, Q, lamb_0, False) mean_abs = np.mean(abs_values) std_abs = np.std(abs_values) return mean_abs, std_abs
def test_TensorProduct_construction(): assert TensorProduct(3, 4) == 12 assert isinstance(TensorProduct(A, A), TensorProduct) expr = TensorProduct(TensorProduct(x, y), z) assert expr == x * y * z expr = TensorProduct(TensorProduct(A, B), C) assert expr == TensorProduct(A, B, C) expr = TensorProduct(Matrix.eye(2), [[0, -1], [1, 0]]) assert expr == Array([[[[0, -1], [1, 0]], [[0, 0], [0, 0]]], [[[0, 0], [0, 0]], [[0, -1], [1, 0]]]])