Esempio n. 1
0
def test_tensorproduct():
    x, y, z, t = symbols("x y z t")
    from sympy.abc import a, b, c, d

    assert tensorproduct() == 1
    assert tensorproduct([x]) == Array([x])
    assert tensorproduct([x], [y]) == Array([[x * y]])
    assert tensorproduct([x], [y], [z]) == Array([[[x * y * z]]])
    assert tensorproduct([x], [y], [z], [t]) == Array([[[[x * y * z * t]]]])

    assert tensorproduct(x) == x
    assert tensorproduct(x, y) == x * y
    assert tensorproduct(x, y, z) == x * y * z
    assert tensorproduct(x, y, z, t) == x * y * z * t

    for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray]:
        A = ArrayType([x, y])
        B = ArrayType([1, 2, 3])
        C = ArrayType([a, b, c, d])

        assert tensorproduct(A, B, C) == ArrayType([
            [
                [a * x, b * x, c * x, d * x],
                [2 * a * x, 2 * b * x, 2 * c * x, 2 * d * x],
                [3 * a * x, 3 * b * x, 3 * c * x, 3 * d * x],
            ],
            [
                [a * y, b * y, c * y, d * y],
                [2 * a * y, 2 * b * y, 2 * c * y, 2 * d * y],
                [3 * a * y, 3 * b * y, 3 * c * y, 3 * d * y],
            ],
        ])

        assert tensorproduct([x, y], [1, 2, 3]) == tensorproduct(A, B)

        assert tensorproduct(A, 2) == ArrayType([2 * x, 2 * y])
        assert tensorproduct(A, [2]) == ArrayType([[2 * x], [2 * y]])
        assert tensorproduct([2], A) == ArrayType([[2 * x, 2 * y]])
        assert tensorproduct(a, A) == ArrayType([a * x, a * y])
        assert tensorproduct(a, A,
                             B) == ArrayType([[a * x, 2 * a * x, 3 * a * x],
                                              [a * y, 2 * a * y, 3 * a * y]])
        assert tensorproduct(A, B,
                             a) == ArrayType([[a * x, 2 * a * x, 3 * a * x],
                                              [a * y, 2 * a * y, 3 * a * y]])
        assert tensorproduct(B, a, A) == ArrayType([[a * x, a * y],
                                                    [2 * a * x, 2 * a * y],
                                                    [3 * a * x, 3 * a * y]])

    # tests for large scale sparse array
    for SparseArrayType in [ImmutableSparseNDimArray, MutableSparseNDimArray]:
        a = SparseArrayType({1: 2, 3: 4}, (1000, 2000))
        b = SparseArrayType({1: 2, 3: 4}, (1000, 2000))
        assert tensorproduct(a, b) == ImmutableSparseNDimArray(
            {
                2000001: 4,
                2000003: 8,
                6000001: 8,
                6000003: 16
            }, (1000, 2000, 1000, 2000))
Esempio n. 2
0
def symbol_calc_fx1y1_6d_diff_x1(n, shape=None):

    fx1, v = symbol_eqtn_fx1(n, model="6d", x1_neg=True, slope="slope", Iext1="Iext1", shape=None)[1:]
    fx1 = fx1.tolist()

    fy1, vy = symbol_eqtn_fy1(n, shape=None)[1:]
    fy1 = fy1.tolist()

    v.update(vy)
    del vy

    dfx1 = []
    for ix in range(n):
        fy1[ix] = fy1[ix].subs(v["y1"][ix], 0.0).subs(v["tau1"][ix], 1.0)
        fx1[ix] = fx1[ix].subs(v["y1"][ix], fy1[ix])
        dfx1.append(fx1[ix].diff(v["x1"][ix]))

    dfx1 = Array(dfx1)
    if shape is not None:
        if len(shape) > 1:
            dfx1 = dfx1.reshape(shape[0], shape[1])
        else:
            dfx1 = dfx1.reshape(shape[0], )

    return lambdify([v["x1"], v["yc"], v["Iext1"], v["a"], v["b"], v["d"], v["tau1"]], dfx1, "numpy"), dfx1, v
def symbol_calc_2d_taylor(n,
                          x_taylor="x1lin",
                          order=2,
                          x1_neg=True,
                          slope="slope",
                          Iext1="Iext1",
                          shape=None):
    fx1ser, v = symbol_eqtn_fx1(n,
                                model="2d",
                                x1_neg=x1_neg,
                                slope=slope,
                                Iext1=Iext1)[1:]
    fx1ser = fx1ser.tolist()
    x_taylor = symbol_vars(n, [x_taylor])[0]
    v.update({"x_taylor": x_taylor})
    for ix in range(shape_to_size(v["x1"].shape)):
        fx1ser[ix] = series(fx1ser[ix],
                            x=v["x1"][ix],
                            x0=x_taylor[ix],
                            n=order).removeO()  #
    fx1ser = Array(fx1ser)
    if shape is not None:
        if len(shape) > 1:
            fx1ser = fx1ser.reshape(shape[0], shape[1])
        else:
            fx1ser = fx1ser.reshape(shape[0], )
    return lambdify([
        v["x1"], x_taylor, v["z"], v["y1"], v[Iext1], v[slope], v["a"], v["b"],
        v["d"], v["tau1"]
    ], fx1ser, "numpy"), fx1ser, v
Esempio n. 4
0
 def create_states(self, size: int, level: int = 0):
     names_list = ['p{}'.format(i + 1) for i in range(size)]
     names_string = ', '.join(names_list)
     if (',' in names_string):
         return Array(dynamicsymbols(names_string, level))
     else:
         return Array([dynamicsymbols(names_string, level)])
Esempio n. 5
0
def symbol_eqtn_fx2y2(n, x2_neg=False, shape=None):

    y2eq, vy = symbol_eqtn_fy2(n, x2_neg=x2_neg)[1:]
    y2eq = y2eq.tolist()

    for iv in range(n):
        y2eq[iv] = y2eq[iv].subs([(vy["tau1"][iv], 1.0), (vy["tau2"][iv], 1.0), (vy["y2"][iv], 0.0)])

    fx2, v = symbol_eqtn_fx2(n, Iext2="Iext2")[1:]
    fx2 = fx2.tolist()

    v.update(vy)
    del vy

    for iv in range(n):
        fx2[iv] = fx2[iv].subs(v["y2"][iv], y2eq[iv])

    fx2 = Array(fx2)
    if shape is not None:
        if len(shape) > 1:
            fx2 = fx2.reshape(shape[0], shape[1])
        else:
            fx2 = fx2.reshape(shape[0], )

    return lambdify([v["x2"], v["z"], v["g"], v["Iext2"], v["s"], v["tau1"]], fx2, 'numpy'), fx2, v
Esempio n. 6
0
    def __init__(self):
        self.q1, self.q2 = dynamicsymbols('q1 q2')
        self.q1d, self.q2d = dynamicsymbols('q1 q2', 1)
        self.q = [self.q1, self.q2]
        self.qd = [self.q1d, self.q2d]
        self.l1, self.l2 = symbols('l_1 l_2', positive=True)
        self.l = [self.l1, self.l2]
        self.ln = [1.5, 1.0]  ############################

        # COM vectors
        self.r1, self.r2 = symbols('r1 r2')
        self.r11 = zeros(3, 1)
        # self.r11[0] = self.r1
        self.r11[0] = 1  ################################
        self.r22 = zeros(3, 1)
        # self.r22[0] = self.r2
        self.r22[0] = 1  #################################
        self.r = zeros(3, 2)
        self.r[:, 0] = self.r11
        self.r[:, 1] = self.r22

        self.a = Array([0, self.l[0], self.l[1]])
        self.d = Array([0.0, 0.0, 0.0])
        self.alpha = Array([0.0, 0.0, 0.0])
        self.T_eff = eye(4)
        self.T_eff[0, 3] = self.l[-1]

        self.q_i = Symbol("q_i")
        self.alpha_i = Symbol("alpha_i")
        self.a_i = Symbol("a_i")
        self.d_i = Symbol("d_i")
Esempio n. 7
0
    def __process_init_input__(self, arg:str, level:int=0) -> Matrix:
        """
        Return the correct format of the processed __init__input. For a one-element input a different approach to create the parameter is needed.

        Parameters
        -----------
        arg : string or array-like
            an __init__ input string that needs to be processed. The variables are separated by ','. Or an NDimArray object, which is returned without any adaptations.
        level : int
            Level of differentiation of the returned function.

        Returns
        --------
        matrix [Matrix]: a Matrix of dynamic symbols given by arg. 
        """
        if arg is None:
            return None
        elif isinstance(arg, NDimArray):
            if level == 0:
                return arg
            else:
                return Array([diff(st, Symbol('t'), level) for st in arg])
        else:
            if (',' in arg):
                return Array(dynamicsymbols(arg, level))
            else:
                return Array([dynamicsymbols(arg, level)])
Esempio n. 8
0
def symbol_eqtn_fx1z(n, model="6d", zmode=array("lin"), shape=None):  #x1_neg=True, z_pos=True,

    # TODO: for the extreme z_pos = False case where we have terms like 0.1 * z ** 7
    # TODO: for the extreme x1_neg = False case where we have to solve for x2 as well

    fx1, v = symbol_eqtn_fx1(n, model, x1_neg=True, slope="slope", Iext1="Iext1")[1:]
    fx1 = fx1.tolist()

    fz, vz = symbol_eqtn_fz(n, zmode, True, model, x0="x0", K="K")[1:]
    fz = fz.tolist()

    v.update(vz)
    del vz

    if model != "2d":

        y1eq, vy = symbol_eqtn_fy1(n)[1:]
        y1eq = y1eq.tolist()

        for iv in range(n):
            y1eq[iv] = y1eq[iv].subs([(vy["tau1"][iv], 1.0), (vy["y1"][iv], 0.0)])

        v.update(vy)
        del vy

        z = []
        for iv in range(n):
            z.append(fx1[iv].subs([(v["tau1"][iv], 1.0), (v["y1"][iv], y1eq[iv]), (v["z"][iv], 0.0)]))

    else:

        z = []
        for iv in range(n):
            z.append(fx1[iv].subs([(v["tau1"][iv], 1.0), (v["z"][iv], 0.0)]))

    fx1z = []
    for iv in range(n):
        fx1z.append(fz[iv].subs([(v["z"][iv], z[iv])]))

    # Convert the solution of x0cr from expression to function that accepts numpy arrays as inputs:
    fx1z = Array(fx1z)
    if shape is not None:
        if len(shape) > 1:
            fx1z = fx1z.reshape(shape[0], shape[1])
        else:
            fx1z = fx1z.reshape(shape[0], )

    if model == "2d":
        fx1z_lambda = lambdify([v["x1"], v["x0"], v["K"], v["w"], v["x0cr"], v["r"], v["y1"], v["Iext1"], v["a"],
                                v["b"], v["tau1"], v["tau0"]], fx1z, 'numpy')
    else:
        fx1z_lambda = lambdify([v["x1"], v["x0"], v["K"], v["w"], v["yc"], v["Iext1"], v["a"], v["b"], v["d"],
                                v["tau1"], v["tau0"]], fx1z, 'numpy')

    return fx1z_lambda, fx1z, v
Esempio n. 9
0
    def create_closed_loop_system(self):
        '''
        Create a SystemBase object of the closed-loop system.

        Returns
        --------
        system : SystemBase
            A Systembase object of the closed-loop system.
        '''
        states, state_equations = self.__get_states__()
        system_dyn = DynamicalSystem(state_equation=Array(state_equations), state=states, output_equation=self.system.output_equation)
        return SystemBase(states=Array(states), inputs='r', sys=system_dyn)
Esempio n. 10
0
def symbol_eqtn_x0cr_r(n, zmode=numpy.array("lin"), shape=None):

    Iext1, yc, a, b, x1_rest, x1_cr, x0_rest, x0_cr, vars_dict = \
        symbol_vars(n, ["Iext1", "yc", "a", "b", "x1_rest", "x1_cr", "x0_rest", "x0_cr"], shape=shape)

    x0cr, r = eqtn_x0cr_r(yc, Iext1, a, b, x1_rest, x1_cr, x0_rest, x0_cr, zmode=zmode)

    x0cr = Array(x0cr)
    r = Array(r)

    x0cr_lambda = lambdify([yc, Iext1, a, b, x1_rest, x1_cr, x0_rest, x0_cr,], x0cr, "numpy")
    r_lambda = lambdify([yc, Iext1, a, b, x1_rest, x1_cr, x0_rest, x0_cr,], r, "numpy")

    return (x0cr_lambda, r_lambda), (x0cr, r), vars_dict
Esempio n. 11
0
def symbol_calc_x0cr_r(n, zmode=array("lin"), shape=None):

    # Define the z equilibrium expression...
    # if epileptor_model == "2d":
    zeq, vx = symbol_eqtn_fx1(n, model="2d", x1_neg=True, slope="slope", Iext1="Iext1")[1:]
    zeq = zeq.tolist()

    for iv in range(n):
        zeq[iv] = zeq[iv].subs([(vx["z"][iv], 0.0), (vx["tau1"][iv], 1.0)])

    # else:
    # zeq = calc_fx1(x1eq, z=0.0, y1=y1=calc_fy1(x1eq, y11), Iext1=I1, model="6d", x1_neg=True,
    # shape=Iext1.shape).tolist()

    # Define the fz expression...
    # fz = calc_fz(x1eq, z=zeq, x0=x0, x0cr=x0cr, r=r, zmode=zmode, z_pos=True, model="2d", shape=Iext1.shape).tolist()
    fz, v = symbol_eqtn_fz(n, zmode, z_pos=True, model="2d", x0="x0", K="K")[1:]
    fz = fz.tolist()

    for iv in range(n):
        fz[iv] = fz[iv].subs([(v['K'][iv], 0.0), (v["tau1"][iv], 1.0), (v["tau0"][iv], 1.0), (v["z"][iv], zeq[iv])])

    v.update(vx)
    del vx

    x1_rest, x1_cr, x0_rest, x0_cr, vv = symbol_vars(len(zeq), ["x1_rest", "x1_cr", "x0_rest", "x0_cr"],
                                                     shape=v["x1"].shape)
    v.update(vv)
    del vv

    # solve the fz expression for rx0 and x0cr, assuming the following two points (x1eq,x0) = [(-5/3,0.0),(-4/3,1.0)]...
    # ...and WITHOUT COUPLING
    x0cr = []
    r = []
    for iv in range(n):
        fz_sol = solve([fz[iv].subs([(v["x1"][iv], x1_rest[iv]), (v["x0"][iv], x0_rest[iv]),
                                (zeq[iv], zeq[iv].subs(v["x1"][iv], x1_rest[iv]))]),
                        fz[iv].subs([(v["x1"][iv], x1_cr[iv]), (v["x0"][iv], x0_cr[iv]),
                                (zeq[iv], zeq[iv].subs(v["x1"][iv], x1_cr[iv]))])],
                        v["x0cr"][iv], v["r"][iv])
        x0cr.append(fz_sol[v["x0cr"][iv]])
        r.append(fz_sol[v["r"][iv]])

    # Convert the solution of x0cr from expression to function that accepts numpy arrays as inputs:
    x0cr = Array(x0cr)
    r = Array(r)
    if shape is not None:
        if len(shape) > 1:
            x0cr = x0cr.reshape(shape[0], shape[1])
            r = r.reshape(shape[0], shape[1])
        else:
            x0cr = x0cr.reshape(shape[0], )
            r = r.reshape(shape[0], )

    return (lambdify([v["y1"], v["Iext1"], v["a"], v["b"], v["x1_rest"], v["x1_cr"], v["x0_rest"], v["x0_cr"]],
                     x0cr, 'numpy'),
           lambdify([v["y1"], v["Iext1"], v["a"], v["b"], v["x1_rest"], v["x1_cr"], v["x0_rest"], v["x0_cr"]],
                    r, 'numpy')), \
           (x0cr, r), v
Esempio n. 12
0
def symbol_eqtn_fg(n, shape=None):

    x1, g, gamma, tau1, vars_dict = symbol_vars(n, ["x1", "g", "gamma", "tau1"], shape=shape)

    fg = Array(eqtn_fg(x1, g, gamma, tau1))

    return lambdify([x1, g, gamma, tau1], fg, "numpy"), fg, vars_dict
Esempio n. 13
0
def symbol_calc_fz_jac_square_taylor(n):

    fx1sq, v = symbol_calc_2d_taylor(n, x_taylor="x1sq", order=3, x1_neg=True, slope="slope", Iext1="Iext1")[1:]
    fx1sq = fx1sq.tolist()

    fz, vz = symbol_eqtn_fz(n, zmode=array("lin"), z_pos=True, model="2d")[1:]
    fz = fz.tolist()
    v.update(vz)
    del vz

    x1 = []
    #dfx1z = []
    for iv in range(n):
        x1.append(list(solveset(fx1sq[iv], v["x1"][iv]))[0])
        #dfx1z.append(x1[iv].diff(v["z"][iv]))

    for iv in range(n):
        for jv in range(n):
            fz[iv] = fz[iv].subs(v["x1"][jv], x1[jv])

    fz_jac = Matrix(fz).jacobian(Matrix([v["z"]]))

    # for iv in range(n):
    #     for jv in range(n):
    #         fz_jac[iv, jv].simplify().collect(dfx1z[jv])

    fz_jac = Array(fz_jac)

    fz_jac_lambda = lambdify([v["z"], v["y1"], v["Iext1"], v["K"], v["w"], v["a"], v["b"], v["tau1"], v["tau0"],
                              v["x_taylor"]], fz_jac, 'numpy')

    return fz_jac_lambda, fz_jac, v
Esempio n. 14
0
def grad(U):
    d = U.shape[1]
    components = []
    for j in range(d):
        terms = [U[1 if (d-i == j+1) else 0, i] for i in range(d)]
        components.append(Mul(*terms))
    return Array(components)
Esempio n. 15
0
def test_TensorProduct_shape():

    expr = TensorProduct(3, 4, evaluate=False)
    assert expr.shape == ()
    assert expr.rank() == 0

    expr = TensorProduct(Array([1, 2]), Array([x, y]), evaluate=False)
    assert expr.shape == (2, 2)
    assert expr.rank() == 2
    expr = TensorProduct(expr, expr, evaluate=False)
    assert expr.shape == (2, 2, 2, 2)
    assert expr.rank() == 4

    expr = TensorProduct(Matrix.eye(2), Array([[0, -1], [1, 0]]), evaluate=False)
    assert expr.shape == (2, 2, 2, 2)
    assert expr.rank() == 4
Esempio n. 16
0
    def create_state_equations(self):
        """
        As the system contains a second derivative of the states, an extended state should be used, which contains the first derivative of the states as well. Therefore, the state equation has to be adapted to this new state vector.

        Returns
        --------
        result : sympy array object
            the state equation for each element in self.states
        """
        minimal_dstates = Matrix(self.states[1::2])
        dstates = Matrix(self.dstates[0::2])
        substitution = dict(zip(dstates, minimal_dstates))

        M_inv = self.inertia_matrix.inv()
        states_dotdot = M_inv * self.force_vector \
            - M_inv * self.damping_matrix * minimal_dstates \
            - M_inv * self.stiffness_matrix
        states_dot = []
        for i in range(len(self.states)):
            if i % 2 == 0:
                states_dot.append(self.states[i + 1])
            else:
                states_dot.append( \
                    msubs(states_dotdot[i//2].copy(), substitution))
        states_dot = Array(states_dot)
        return states_dot
Esempio n. 17
0
def symbol_eqtn_fy1(n, shape=None):

    x1, y1, yc, d, tau1, vars_dict = symbol_vars(n, ["x1", "y1", "yc", "d", "tau1"], shape=shape)

    fy1 = Array(eqtn_fy1(x1, yc, y1, d, tau1))

    return lambdify([x1, y1, yc, d, tau1], fy1, "numpy"), fy1, vars_dict
Esempio n. 18
0
def symbol_eqtn_fK(n, shape=None):

    K_var, K, tau1, tau0, vars_dict = symbol_vars(n, ["K_var", "K", "tau1", "tau0"], shape=shape)

    fK = Array(eqtn_fK(K_var, K, tau1, tau0))

    return lambdify([K_var, K, tau1, tau0], fK, "numpy"), fK, vars_dict
Esempio n. 19
0
def symbol_eqtn_fIext1(n, shape=None):

    Iext1_var, Iext1, tau1, tau0, vars_dict = symbol_vars(n, ["Iext1_var", "Iext1", "tau1", "tau0"], shape=shape)

    fIext1 = Array(eqtn_fIext1(Iext1_var, Iext1, tau1, tau0))

    return lambdify([Iext1_var, Iext1, tau1, tau0], fIext1, "numpy"), fIext1, vars_dict
Esempio n. 20
0
def symbol_eqtn_fx0(n, shape=None):

    x0_var, x0, tau1, vars_dict = symbol_vars(n, ["x0_var", "x0", "tau1"], shape=shape)

    fx0 = Array(eqtn_fx0(x0_var, x0, tau1))

    return lambdify([x0_var, x0, tau1], fx0, "numpy"), fx0, vars_dict
Esempio n. 21
0
def symbol_eqtn_fx2(n, Iext2="Iext2", shape=None):

    x2, y2, z, g, Iext2, tau1, vars_dict = symbol_vars(n, ["x2", "y2", "z", "g", Iext2, "tau1"], shape=shape)

    fx2 = Array(eqtn_fx2(x2, y2, z, g, Iext2, tau1))

    return lambdify([x2, y2, z, g, Iext2, tau1], fx2, "numpy"), fx2, vars_dict
Esempio n. 22
0
def symbol_eqtn_fy2(n, x2_neg=False, shape=None):

    x2, y2, s, tau1, tau2, vars_dict = symbol_vars(n, ["x2", "y2", "s", "tau1", "tau2"], shape=shape)

    fy2 = Array(eqtn_fy2(x2, y2, s, tau1, tau2, x2_neg))

    return lambdify([x2, y2, s, tau1, tau2], fy2, "numpy"), fy2, vars_dict
Esempio n. 23
0
def symbol_calc_fx1z_2d_x1neg_zpos_jac(n, ix0, iE):

    fx1, v = symbol_eqtn_fx1(n, model="2d", x1_neg=True, slope="slope", Iext1="Iext1", shape=None)[1:]
    fx1 = fx1.tolist()

    fz, vz = symbol_eqtn_fz(n, zmode=array("lin"), z_pos=True, model="2d", x0="x0", K="K", shape=None)[1:]
    fz = fz.tolist()

    v.update(vz)
    del vz

    x = empty_like(v["x1"])
    x[iE] = v["x0"][iE]
    x[ix0] = v["x1"][ix0]
    x = Matrix(x)

    jac = []
    for ix in range(n):
        fx1[ix] = fx1[ix].subs(v["tau1"][ix], 1.0).subs(v["z"][ix], 0.0)
        fz[ix] = fz[ix].subs(v["z"][ix], fx1[ix])
        jac.append(Matrix([fz[ix]]).jacobian(x)[:])

    jac = Array(jac)

    return lambdify([v["x1"], v["z"], v["x0"], v["x0cr"], v["r"], v["y1"], v["Iext1"], v["K"], v["w"], v["a"], v["b"],
                     v["tau1"], v["tau0"]], jac, "numpy"), jac, v
Esempio n. 24
0
def symbol_eqtn_x0(n, zmode=numpy.array("lin"), z_pos=True, K="K", shape=None):
    x1, z, K, vars_dict = symbol_vars(n, ["x1", "z", K], shape=shape)
    w, temp = symbol_vars(n, ["w"], dims=2)
    vars_dict.update(temp)
    x0 = Array(eqtn_x0(x1, z, zmode, z_pos, K, w))
    x0_lambda = lambdify([x1, z, K, w], x0, "numpy"), x0, vars_dict
    return x0_lambda, x0, vars_dict
Esempio n. 25
0
    def _get_args_shapes(self):
        from sympy import Array

        return [
            i.shape if hasattr(i, "shape") else Array(i).shape
            for i in self.args
        ]
Esempio n. 26
0
    def __init__(self, *args, **kwargs):
        if 'inputs' not in kwargs.keys():
            error_text = "[nlcontrol.systems.DynamicController] An 'inputs=' keyword is necessary."
            raise AssertionError(error_text)
        if 'states' not in kwargs.keys():
            error_text = "[nlcontrol.systems.DynamicController] A 'states=' keyword is necessary."
            raise AssertionError(error_text)
        super().__init__(*args, **kwargs)

        self.minimal_inputs = self.inputs
        self.inputs = Array(
            [val for pair in zip(self.inputs, self.dinputs) for val in pair])

        self.A = None
        self.B = None
        self.C = None
        self.f = None
        self.eta = None
        self.phi = None

        if len(args) not in (0, 6):
            error_text = '[nlcontrol.systems.DynamicController] the argument list should contain a A, B, C, f, eta, and phi matrix. If defined outside the init function, no arguments should be given.'
            raise ValueError(error_text)

        if len(args) == 6:
            self.define_controller(*args)
Esempio n. 27
0
    def __new__(cls, *args, **kwargs):
        from sympy.tensor.array import NDimArray, tensorproduct, Array
        from sympy import MatrixBase, MatrixExpr
        from sympy.strategies import flatten

        args = [sympify(arg) for arg in args]
        evaluate = kwargs.get("evaluate", global_parameters.evaluate)

        if not evaluate:
            obj = Expr.__new__(cls, *args)
            return obj

        arrays = []
        other = []
        scalar = S.One
        for arg in args:
            if isinstance(arg, (Iterable, MatrixBase, NDimArray)):
                arrays.append(Array(arg))
            elif isinstance(arg, (MatrixExpr, )):
                other.append(arg)
            else:
                scalar *= arg

        coeff = scalar * tensorproduct(*arrays)
        if len(other) == 0:
            return coeff
        if coeff != 1:
            newargs = [coeff] + other
        else:
            newargs = other
        obj = Expr.__new__(cls, *newargs, **kwargs)
        return flatten(obj)
Esempio n. 28
0
def test_issue_19764():
    if not numpy:
        skip("numpy not installed")

    expr = Array([x, x**2])
    f = lambdify(x, expr, 'numpy')

    assert f(1).__class__ == numpy.ndarray
Esempio n. 29
0
def test_tensordiagonal():
    from sympy.matrices.dense import eye
    expr = Array(range(9)).reshape(3, 3)
    raises(ValueError, lambda: tensordiagonal(expr, [0], [1]))
    raises(ValueError, lambda: tensordiagonal(expr, [0, 0]))
    assert tensordiagonal(eye(3), [0, 1]) == Array([1, 1, 1])
    assert tensordiagonal(expr, [0, 1]) == Array([0, 4, 8])
    x, y, z = symbols("x y z")
    expr2 = tensorproduct([x, y, z], expr)
    assert tensordiagonal(expr2, [1, 2]) == Array([[0, 4*x, 8*x], [0, 4*y, 8*y], [0, 4*z, 8*z]])
    assert tensordiagonal(expr2, [0, 1]) == Array([[0, 3*y, 6*z], [x, 4*y, 7*z], [2*x, 5*y, 8*z]])
    assert tensordiagonal(expr2, [0, 1, 2]) == Array([0, 4*y, 8*z])
    # assert tensordiagonal(expr2, [0]) == permutedims(expr2, [1, 2, 0])
    # assert tensordiagonal(expr2, [1]) == permutedims(expr2, [0, 2, 1])
    # assert tensordiagonal(expr2, [2]) == expr2
    # assert tensordiagonal(expr2, [1], [2]) == expr2
    # assert tensordiagonal(expr2, [0], [1]) == permutedims(expr2, [2, 0, 1])

    a, b, c, X, Y, Z = symbols("a b c X Y Z")
    expr3 = tensorproduct([x, y, z], [1, 2, 3], [a, b, c], [X, Y, Z])
    assert tensordiagonal(expr3, [0, 1, 2, 3]) == Array([x*a*X, 2*y*b*Y, 3*z*c*Z])
    assert tensordiagonal(expr3, [0, 1], [2, 3]) == tensorproduct([x, 2*y, 3*z], [a*X, b*Y, c*Z])

    # assert tensordiagonal(expr3, [0], [1, 2], [3]) == tensorproduct([x, y, z], [a, 2*b, 3*c], [X, Y, Z])
    assert tensordiagonal(tensordiagonal(expr3, [2, 3]), [0, 1]) == tensorproduct([a*X, b*Y, c*Z], [x, 2*y, 3*z])

    raises(ValueError, lambda: tensordiagonal([[1, 2, 3], [4, 5, 6]], [0, 1]))
    raises(ValueError, lambda: tensordiagonal(expr3.reshape(3, 3, 9), [1, 2]))
def test_derivative_by_array():
    from sympy.abc import a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z

    bexpr = x * y**2 * exp(z) * log(t)
    sexpr = sin(bexpr)
    cexpr = cos(bexpr)

    a = Array([sexpr])

    assert derive_by_array(
        sexpr, t) == x * y**2 * exp(z) * cos(x * y**2 * exp(z) * log(t)) / t
    assert derive_by_array(sexpr, [x, y, z]) == Array(
        [bexpr / x * cexpr, 2 * y * bexpr / y**2 * cexpr, bexpr * cexpr])
    assert derive_by_array(a,
                           [x, y, z]) == Array([[bexpr / x * cexpr],
                                                [2 * y * bexpr / y**2 * cexpr],
                                                [bexpr * cexpr]])

    assert derive_by_array(sexpr, [[x, y], [z, t]]) == Array(
        [[bexpr / x * cexpr, 2 * y * bexpr / y**2 * cexpr],
         [bexpr * cexpr, bexpr / log(t) / t * cexpr]])
    assert derive_by_array(a, [[x, y], [z, t]]) == Array(
        [[[bexpr / x * cexpr], [2 * y * bexpr / y**2 * cexpr]],
         [[bexpr * cexpr], [bexpr / log(t) / t * cexpr]]])
    assert derive_by_array([[x, y], [z, t]], [x, y]) == Array([[[1, 0], [0,
                                                                         0]],
                                                               [[0, 1], [0,
                                                                         0]]])
    assert derive_by_array([[x, y], [z, t]],
                           [[x, y], [z, t]]) == Array([[[[1, 0], [0, 0]],
                                                        [[0, 1], [0, 0]]],
                                                       [[[0, 0], [1, 0]],
                                                        [[0, 0], [0, 1]]]])
Esempio n. 31
0
def test_array_permutedims():
    sa = symbols('a0:144')

    m1 = Array(sa[:6], (2, 3))
    assert permutedims(m1, (1, 0)) == transpose(m1)
    assert m1.tomatrix().T == permutedims(m1, (1, 0)).tomatrix()

    assert m1.tomatrix().T == transpose(m1).tomatrix()
    assert m1.tomatrix().C == conjugate(m1).tomatrix()
    assert m1.tomatrix().H == adjoint(m1).tomatrix()

    assert m1.tomatrix().T == m1.transpose().tomatrix()
    assert m1.tomatrix().C == m1.conjugate().tomatrix()
    assert m1.tomatrix().H == m1.adjoint().tomatrix()

    raises(ValueError, lambda: permutedims(m1, (0,)))
    raises(ValueError, lambda: permutedims(m1, (0, 0)))
    raises(ValueError, lambda: permutedims(m1, (1, 2, 0)))

    # Some tests with random arrays:
    dims = 6
    shape = [random.randint(1,5) for i in range(dims)]
    elems = [random.random() for i in range(tensorproduct(*shape))]
    ra = Array(elems, shape)
    perm = list(range(dims))
    # Randomize the permutation:
    random.shuffle(perm)
    # Test inverse permutation:
    assert permutedims(permutedims(ra, perm), _af_invert(perm)) == ra
    # Test that permuted shape corresponds to action by `Permutation`:
    assert permutedims(ra, perm).shape == tuple(Permutation(perm)(shape))

    z = Array.zeros(4,5,6,7)

    assert permutedims(z, (2, 3, 1, 0)).shape == (6, 7, 5, 4)
    assert permutedims(z, [2, 3, 1, 0]).shape == (6, 7, 5, 4)
    assert permutedims(z, Permutation([2, 3, 1, 0])).shape == (6, 7, 5, 4)

    po = Array(sa, [2, 2, 3, 3, 2, 2])

    raises(ValueError, lambda: permutedims(po, (1, 1)))
    raises(ValueError, lambda: po.transpose())
    raises(ValueError, lambda: po.adjoint())

    assert permutedims(po, reversed(range(po.rank()))) == Array(
        [[[[[[sa[0], sa[72]], [sa[36], sa[108]]], [[sa[12], sa[84]], [sa[48], sa[120]]], [[sa[24],
                                                                                           sa[96]], [sa[60], sa[132]]]],
           [[[sa[4], sa[76]], [sa[40], sa[112]]], [[sa[16],
                                                    sa[88]], [sa[52], sa[124]]],
            [[sa[28], sa[100]], [sa[64], sa[136]]]],
           [[[sa[8],
              sa[80]], [sa[44], sa[116]]], [[sa[20], sa[92]], [sa[56], sa[128]]], [[sa[32],
                                                                                    sa[104]], [sa[68], sa[140]]]]],
          [[[[sa[2], sa[74]], [sa[38], sa[110]]], [[sa[14],
                                                    sa[86]], [sa[50], sa[122]]], [[sa[26], sa[98]], [sa[62], sa[134]]]],
           [[[sa[6],
              sa[78]], [sa[42], sa[114]]], [[sa[18], sa[90]], [sa[54], sa[126]]], [[sa[30],
                                                                                    sa[102]], [sa[66], sa[138]]]],
           [[[sa[10], sa[82]], [sa[46], sa[118]]], [[sa[22],
                                                     sa[94]], [sa[58], sa[130]]],
            [[sa[34], sa[106]], [sa[70], sa[142]]]]]],
         [[[[[sa[1],
              sa[73]], [sa[37], sa[109]]], [[sa[13], sa[85]], [sa[49], sa[121]]], [[sa[25],
                                                                                    sa[97]], [sa[61], sa[133]]]],
           [[[sa[5], sa[77]], [sa[41], sa[113]]], [[sa[17],
                                                    sa[89]], [sa[53], sa[125]]],
            [[sa[29], sa[101]], [sa[65], sa[137]]]],
           [[[sa[9],
              sa[81]], [sa[45], sa[117]]], [[sa[21], sa[93]], [sa[57], sa[129]]], [[sa[33],
                                                                                    sa[105]], [sa[69], sa[141]]]]],
          [[[[sa[3], sa[75]], [sa[39], sa[111]]], [[sa[15],
                                                    sa[87]], [sa[51], sa[123]]], [[sa[27], sa[99]], [sa[63], sa[135]]]],
           [[[sa[7],
              sa[79]], [sa[43], sa[115]]], [[sa[19], sa[91]], [sa[55], sa[127]]], [[sa[31],
                                                                                    sa[103]], [sa[67], sa[139]]]],
           [[[sa[11], sa[83]], [sa[47], sa[119]]], [[sa[23],
                                                     sa[95]], [sa[59], sa[131]]],
            [[sa[35], sa[107]], [sa[71], sa[143]]]]]]])

    assert permutedims(po, (1, 0, 2, 3, 4, 5)) == Array(
        [[[[[[sa[0], sa[1]], [sa[2], sa[3]]], [[sa[4], sa[5]], [sa[6], sa[7]]], [[sa[8], sa[9]], [sa[10],
                                                                                                  sa[11]]]],
           [[[sa[12], sa[13]], [sa[14], sa[15]]], [[sa[16], sa[17]], [sa[18],
                                                                      sa[19]]], [[sa[20], sa[21]], [sa[22], sa[23]]]],
           [[[sa[24], sa[25]], [sa[26],
                                sa[27]]], [[sa[28], sa[29]], [sa[30], sa[31]]], [[sa[32], sa[33]], [sa[34],
                                                                                                    sa[35]]]]],
          [[[[sa[72], sa[73]], [sa[74], sa[75]]], [[sa[76], sa[77]], [sa[78],
                                                                      sa[79]]], [[sa[80], sa[81]], [sa[82], sa[83]]]],
           [[[sa[84], sa[85]], [sa[86],
                                sa[87]]], [[sa[88], sa[89]], [sa[90], sa[91]]], [[sa[92], sa[93]], [sa[94],
                                                                                                    sa[95]]]],
           [[[sa[96], sa[97]], [sa[98], sa[99]]], [[sa[100], sa[101]], [sa[102],
                                                                        sa[103]]],
            [[sa[104], sa[105]], [sa[106], sa[107]]]]]], [[[[[sa[36], sa[37]], [sa[38],
                                                                                sa[39]]],
                                                            [[sa[40], sa[41]], [sa[42], sa[43]]],
                                                            [[sa[44], sa[45]], [sa[46],
                                                                                sa[47]]]],
                                                           [[[sa[48], sa[49]], [sa[50], sa[51]]],
                                                            [[sa[52], sa[53]], [sa[54],
                                                                                sa[55]]],
                                                            [[sa[56], sa[57]], [sa[58], sa[59]]]],
                                                           [[[sa[60], sa[61]], [sa[62],
                                                                                sa[63]]],
                                                            [[sa[64], sa[65]], [sa[66], sa[67]]],
                                                            [[sa[68], sa[69]], [sa[70],
                                                                                sa[71]]]]], [
                                                              [[[sa[108], sa[109]], [sa[110], sa[111]]],
                                                               [[sa[112], sa[113]], [sa[114],
                                                                                     sa[115]]],
                                                               [[sa[116], sa[117]], [sa[118], sa[119]]]],
                                                              [[[sa[120], sa[121]], [sa[122],
                                                                                     sa[123]]],
                                                               [[sa[124], sa[125]], [sa[126], sa[127]]],
                                                               [[sa[128], sa[129]], [sa[130],
                                                                                     sa[131]]]],
                                                              [[[sa[132], sa[133]], [sa[134], sa[135]]],
                                                               [[sa[136], sa[137]], [sa[138],
                                                                                     sa[139]]],
                                                               [[sa[140], sa[141]], [sa[142], sa[143]]]]]]])

    assert permutedims(po, (0, 2, 1, 4, 3, 5)) == Array(
        [[[[[[sa[0], sa[1]], [sa[4], sa[5]], [sa[8], sa[9]]], [[sa[2], sa[3]], [sa[6], sa[7]], [sa[10],
                                                                                                sa[11]]]],
           [[[sa[36], sa[37]], [sa[40], sa[41]], [sa[44], sa[45]]], [[sa[38],
                                                                      sa[39]], [sa[42], sa[43]], [sa[46], sa[47]]]]],
          [[[[sa[12], sa[13]], [sa[16],
                                sa[17]], [sa[20], sa[21]]], [[sa[14], sa[15]], [sa[18], sa[19]], [sa[22],
                                                                                                  sa[23]]]],
           [[[sa[48], sa[49]], [sa[52], sa[53]], [sa[56], sa[57]]], [[sa[50],
                                                                      sa[51]], [sa[54], sa[55]], [sa[58], sa[59]]]]],
          [[[[sa[24], sa[25]], [sa[28],
                                sa[29]], [sa[32], sa[33]]], [[sa[26], sa[27]], [sa[30], sa[31]], [sa[34],
                                                                                                  sa[35]]]],
           [[[sa[60], sa[61]], [sa[64], sa[65]], [sa[68], sa[69]]], [[sa[62],
                                                                      sa[63]], [sa[66], sa[67]], [sa[70], sa[71]]]]]],
         [[[[[sa[72], sa[73]], [sa[76],
                                sa[77]], [sa[80], sa[81]]], [[sa[74], sa[75]], [sa[78], sa[79]], [sa[82],
                                                                                                  sa[83]]]],
           [[[sa[108], sa[109]], [sa[112], sa[113]], [sa[116], sa[117]]], [[sa[110],
                                                                            sa[111]], [sa[114], sa[115]],
                                                                           [sa[118], sa[119]]]]],
          [[[[sa[84], sa[85]], [sa[88],
                                sa[89]], [sa[92], sa[93]]], [[sa[86], sa[87]], [sa[90], sa[91]], [sa[94],
                                                                                                  sa[95]]]],
           [[[sa[120], sa[121]], [sa[124], sa[125]], [sa[128], sa[129]]], [[sa[122],
                                                                            sa[123]], [sa[126], sa[127]],
                                                                           [sa[130], sa[131]]]]],
          [[[[sa[96], sa[97]], [sa[100],
                                sa[101]], [sa[104], sa[105]]], [[sa[98], sa[99]], [sa[102], sa[103]], [sa[106],
                                                                                                       sa[107]]]],
           [[[sa[132], sa[133]], [sa[136], sa[137]], [sa[140], sa[141]]], [[sa[134],
                                                                            sa[135]], [sa[138], sa[139]],
                                                                           [sa[142], sa[143]]]]]]])

    po2 = po.reshape(4, 9, 2, 2)
    assert po2 == Array([[[[sa[0], sa[1]], [sa[2], sa[3]]], [[sa[4], sa[5]], [sa[6], sa[7]]], [[sa[8], sa[9]], [sa[10], sa[11]]], [[sa[12], sa[13]], [sa[14], sa[15]]], [[sa[16], sa[17]], [sa[18], sa[19]]], [[sa[20], sa[21]], [sa[22], sa[23]]], [[sa[24], sa[25]], [sa[26], sa[27]]], [[sa[28], sa[29]], [sa[30], sa[31]]], [[sa[32], sa[33]], [sa[34], sa[35]]]], [[[sa[36], sa[37]], [sa[38], sa[39]]], [[sa[40], sa[41]], [sa[42], sa[43]]], [[sa[44], sa[45]], [sa[46], sa[47]]], [[sa[48], sa[49]], [sa[50], sa[51]]], [[sa[52], sa[53]], [sa[54], sa[55]]], [[sa[56], sa[57]], [sa[58], sa[59]]], [[sa[60], sa[61]], [sa[62], sa[63]]], [[sa[64], sa[65]], [sa[66], sa[67]]], [[sa[68], sa[69]], [sa[70], sa[71]]]], [[[sa[72], sa[73]], [sa[74], sa[75]]], [[sa[76], sa[77]], [sa[78], sa[79]]], [[sa[80], sa[81]], [sa[82], sa[83]]], [[sa[84], sa[85]], [sa[86], sa[87]]], [[sa[88], sa[89]], [sa[90], sa[91]]], [[sa[92], sa[93]], [sa[94], sa[95]]], [[sa[96], sa[97]], [sa[98], sa[99]]], [[sa[100], sa[101]], [sa[102], sa[103]]], [[sa[104], sa[105]], [sa[106], sa[107]]]], [[[sa[108], sa[109]], [sa[110], sa[111]]], [[sa[112], sa[113]], [sa[114], sa[115]]], [[sa[116], sa[117]], [sa[118], sa[119]]], [[sa[120], sa[121]], [sa[122], sa[123]]], [[sa[124], sa[125]], [sa[126], sa[127]]], [[sa[128], sa[129]], [sa[130], sa[131]]], [[sa[132], sa[133]], [sa[134], sa[135]]], [[sa[136], sa[137]], [sa[138], sa[139]]], [[sa[140], sa[141]], [sa[142], sa[143]]]]])

    assert permutedims(po2, (3, 2, 0, 1)) == Array([[[[sa[0], sa[4], sa[8], sa[12], sa[16], sa[20], sa[24], sa[28], sa[32]], [sa[36], sa[40], sa[44], sa[48], sa[52], sa[56], sa[60], sa[64], sa[68]], [sa[72], sa[76], sa[80], sa[84], sa[88], sa[92], sa[96], sa[100], sa[104]], [sa[108], sa[112], sa[116], sa[120], sa[124], sa[128], sa[132], sa[136], sa[140]]], [[sa[2], sa[6], sa[10], sa[14], sa[18], sa[22], sa[26], sa[30], sa[34]], [sa[38], sa[42], sa[46], sa[50], sa[54], sa[58], sa[62], sa[66], sa[70]], [sa[74], sa[78], sa[82], sa[86], sa[90], sa[94], sa[98], sa[102], sa[106]], [sa[110], sa[114], sa[118], sa[122], sa[126], sa[130], sa[134], sa[138], sa[142]]]], [[[sa[1], sa[5], sa[9], sa[13], sa[17], sa[21], sa[25], sa[29], sa[33]], [sa[37], sa[41], sa[45], sa[49], sa[53], sa[57], sa[61], sa[65], sa[69]], [sa[73], sa[77], sa[81], sa[85], sa[89], sa[93], sa[97], sa[101], sa[105]], [sa[109], sa[113], sa[117], sa[121], sa[125], sa[129], sa[133], sa[137], sa[141]]], [[sa[3], sa[7], sa[11], sa[15], sa[19], sa[23], sa[27], sa[31], sa[35]], [sa[39], sa[43], sa[47], sa[51], sa[55], sa[59], sa[63], sa[67], sa[71]], [sa[75], sa[79], sa[83], sa[87], sa[91], sa[95], sa[99], sa[103], sa[107]], [sa[111], sa[115], sa[119], sa[123], sa[127], sa[131], sa[135], sa[139], sa[143]]]]])