def generateSystemSteadyState(self, replacements, full_output = False):
        # taking the RHS of the steady state equations in order to add the
        # constraint Tr(ρ) = 1, needed to solve the system of equations
        eqns_rhs = self.equations_steady_state.rhs.subs(replacements)
        eqns_rhs = flatten(eqns_rhs.tolist())
        eqns_rhs[0] += self.density_matrix_steady_state.trace()-1

        for i in range(self.levels):
            for j in range(i,self.levels):
                tmp = Symbol(u'\u03C1{0}{1}'.format(chr(0x2080+i), 
                                                        chr(0x2080+j)))
                tmp1 = Symbol(u'\u03C1{0}{1}'.format(chr(0x2080+j), 
                                                        chr(0x2080+i)))
                for idx in range(len(eqns_rhs)):
                    eqns_rhs[idx] = eqns_rhs[idx].subs(conjugate(tmp), tmp1)
        syms = []
        for i in range(self.levels):
            for j in range(self.levels):
                syms.append(Symbol(u'\u03C1{0}{1}'.format(chr(0x2080+i), 
                                                            chr(0x2080+j))))
        matrix_eq = linear_eq_to_matrix(eqns_rhs, syms)       
        if full_output:
            return matrix_eq, syms
        else:
            return matrix_eq
Пример #2
0
def rewrite_odes_as_linear_combination_in_parameters(odes_sym,state_symbols,ode_param_symbols,ext_input_symbols): 

    '''Rewrites each ODE as a Linear Combination in all ODE Parameters'''
    
    # number of hidden states
    numb_hidden_states = len(state_symbols)
    
    # append state symbols with constant vector
    symbols_all = [lst for sublist in [state_symbols,ext_input_symbols,sym.symbols(['one_vector'])] for lst in sublist]
    
    # initialize vectors B and b
    B=[[] for k in range(numb_hidden_states)]
    b=[[] for k in range(numb_hidden_states)]
    
    # rewrite ODEs as linear combinations in parameters (locally w.r.t. individual ODE)
    for k in range(numb_hidden_states):
        expr_B,expr_b = sym.linear_eq_to_matrix([odes_sym[k].expand()],ode_param_symbols)
        expr_b = -expr_b  # see the documentation of the function "sympy.linear_eq_to_matrix"
        
        # replace scalar constant by vector populated by the same constant
        for i in range(len(expr_B)):
            if len(expr_B[i].free_symbols) == 0: expr_B[i] = sym.symbols('one_vector')
        for i in range(len(expr_b)):
            if len(expr_b[i].free_symbols) == 0: expr_b[i] = sym.symbols('one_vector')
           
        # transform symbolic expressions for B and b into functions
        B[k] = sym.lambdify(symbols_all,expr_B)
        b[k] = sym.lambdify(symbols_all,expr_b)
    
    return B,b
Пример #3
0
def linalg_test():
    system = equations()
    M, c = sp.linear_eq_to_matrix(system, [x1, x2, x3])
    M, c = np.asarray(M, dtype=np.float32), np.asarray(c, dtype=np.float32)
    y = np.linalg.solve(M, c)
    print('\nsolutions')
    print(y)
Пример #4
0
    def _analyse(self):

        if self.kind == 'time':
            raise ValueError(
                'Cannot put time domain equations into matrix form')

        subsdict = {}
        for node, v in self._unknowns.items():
            if v == 0:
                continue
            subsdict[v.expr] = 'X_X' + node

        exprs = []
        for node, (lhs, rhs) in self._equations.items():
            lhs = lhs.subs(subsdict).expr.expand()
            rhs = rhs.subs(subsdict).expr.expand()
            exprs.append(lhs - rhs)

        y = []
        for y1 in self._y:
            y.append(y1.subs(subsdict).expr)

        A, b = sym.linear_eq_to_matrix(exprs, *y)
        y = [y1.expr for y1 in self._y]
        return SystemEquations(A, b, y)
def equations_to_matrices(equations: list):
    """Equations to Matrix:
    Transform a list of equations into two matrices A(the coefficients matrix)
    and b(the r.h.s matrix).

    Keyword arguments:
    equations: list -- A list of containing the string representation of the equations.

    return:
    1) The matrix A containing the coefficients of the equation
       sorted according to the alphabetical order of their symbols.
    2) The vector b containing the r.h.s of the equations
    3) The symbols sorted in alphabetical order.
    """
    print(equations)
    parsed_equations = []
    symbols = set()
    for eq in equations:
        parts = eq.replace('==', '=').split('=')
        assert len(parts) == 2
        lhs, rhs = parts
        parsed_eqn = sympy.Eq(sympy.sympify(lhs), sympy.sympify(rhs))
        symbols |= parsed_eqn.free_symbols
        parsed_equations.append(parsed_eqn)
    symbol_list = sorted(list(symbols), key=str)
    A, b = sympy.linear_eq_to_matrix(parsed_equations, symbol_list)

    # asserts that both matrices do not contain any symbols
    # since bool(empty_set) returns False and bool(non_empty_set) returns true
    assert not bool(A.free_symbols) and not bool(b.free_symbols)
    return A, b, symbol_list
def rewrite_odes_as_linear_combination_in_states(odes,state_symbols,ode_param_symbols,observed_states,\
                                                 state_couplings,clamp_states_to_observation_fit=1):
    '''Rewrite each ODE as a Linear Combination in an Individual State'''

    # number of hidden states
    numb_hidden_states = len(state_symbols)

    # number of ODEs
    numb_odes = len(odes(*state_symbols, *ode_param_symbols))

    # unpack state and parameter symbols
    symbols_all = [
        lst for sublist in
        [ode_param_symbols, state_symbols,
         sym.symbols(['one_vector'])] for lst in sublist
    ]

    # determine set of hidden states to infer
    if clamp_states_to_observation_fit == 1:
        # indices of observed states
        hidden_states_to_infer = [
            u for u in range(len(state_symbols))
            if state_symbols[u] not in observed_states
        ]
    else:
        hidden_states_to_infer = range(len(state_symbols))

    # initialize matrices R and r
#    R=[[[],[],[]] for k in range(numb_hidden_states)]
#    r=[[[],[],[]] for k in range(numb_hidden_states)]

    R = [[[] for k in range(numb_odes)] for u in range(numb_hidden_states)]
    r = [[[] for k in range(numb_odes)] for u in range(numb_hidden_states)]

    # rewrite ODEs as linear combinations in individual states (locally w.r.t. individual ODE)
    for u in range(numb_hidden_states):
        for k in state_couplings[u]:
            expr_R, expr_r = sym.linear_eq_to_matrix(
                [odes(*state_symbols, *ode_param_symbols)[k].expand()],
                state_symbols[u])
            expr_r = -expr_r  # see the documentation of the function "sympy.linear_eq_to_matrix"

            # replace scalar by vector populated by the same scalar
            for i in range(len(expr_R)):
                if len(expr_R[i].free_symbols) == 0:
                    expr_R[i] *= sym.symbols('one_vector')
            for i in range(len(expr_r)):
                if len(expr_r[i].free_symbols) == 0:
                    expr_r[i] *= sym.symbols('one_vector')

            # transform symbolic expressions for R and r into functions
            R[u][k] = sym.lambdify(symbols_all, expr_R)
            r[u][k] = sym.lambdify(symbols_all, expr_r)

#            R[u][k] = sym.lambdify(*(ode_param_symbols,state_symbols),expr_R)
#            r[u][k] = sym.lambdify(*[ode_param_symbols,state_symbols],expr_r)

    return R, r
    def _calc_regressor(self):
        print("Calculating regressor...")
        A, b = sympy.linear_eq_to_matrix(self.tau, self.rbt_def.bary_params)

        self.H = A

        input_vars = tuple(self.rbt_def.coordinates + self.rbt_def.d_coordinates + self.rbt_def.dd_coordinates)
        # print('input_vars', input_vars)
        self.H_func = sympy.lambdify(input_vars, self.H)
Пример #8
0
def linear_to_matrix(equs, coeff):
    A, b = linear_eq_to_matrix(equs, coeff)
    A = np.array(A).astype(np.float64)
    b = np.array(b).astype(np.float64)
    # np.savetxt("A.csv", A, delimiter=",")
    # np.savetxt("b.csv", b, delimiter=",")
    #print(A, b)
    s = np.linalg.solve(A, b)
    return s
Пример #9
0
def linear_to_matrix(equs, coeff):
    #print(equs)
    x, y = linear_eq_to_matrix(equs, coeff)
    x = np.array(x).astype(np.float64)
    y = np.array(y).astype(np.float64)
    #print(x, '',y)
    #print(y)
    s = np.linalg.solve(x, y)
    return s
def equations_to_matrix(equations):
    symbols = set()
    system = []
    for equation in equations:
        sides = equation.split("=")
        LHS, RHS = sides
        expression = sympy.Eq(sympy.simplify(LHS), sympy.simplify(RHS))
        system.append(expression)
        add_symbols_to_set(symbols, expression.free_symbols)
    symbols = sorted(list(symbols), key=str)
    coeffs, b = sympy.linear_eq_to_matrix(system, symbols)
    return coeffs, b, symbols, system
def get_Sv(A, J, N1, N2, Ut):
    """
    Solve for Sv
    
    Input
    =========
    (The inputs are obtained from solve_habit_persistence)
    A: stable dynamic matrix A
    J: matrix J
    N1, N2: stable dynamics for costates
    Ut: the utility function
    
    Output
    =========
    Su: The row vector (Su)'
    
    """
    ##== Calculate Su ==##
    ## Express Ut in terms of Z_{t} and Z_{t+1}
    MKt, MHt, Kt, Ht, X1t, X2t, X2tL1 = symbols('MKt MHt Kt Ht X1t X2t X2tL1')
    MKt1, MHt1, Kt1, Ht1, X1t1, X2t1 = symbols('MKt1 MHt1 Kt1 Ht1 X1t1 X2t1')
    
    TT,_ = linear_eq_to_matrix([Ut],
                               MKt, MHt, Kt, Ht, X1t, X2t, X2tL1,
                               MKt1, MHt1, Kt1, Ht1, X1t1, X2t1)
    #t1: Ut's coefficient under Z_t
    t1 = TT[:7]
    t1 = np.array([t1]).astype(float)
    #t2: Ut's coefficient under Z_{t+1}
    t2 = TT[7:]
    t2.append(0)    #X2t is 0 in t2 entry
    t2 = np.array([t2]).astype(float)
    
    ## Get Su
    K = np.vstack([np.hstack([N1,N2]),np.identity(5)])
    JK = np.matmul(J, K)
    
    T1 = np.matmul(t1, K)
    T2 = np.matmul(t2, JK)
    
    Su = T1 + T2
    
    
    ##== Calculate Sv ==##
    """
    We rearranged the equation from the note to get: (Sv)' * A_Sv = b_Sv
    """
    b_Sv = (1 - np.exp(-δ)) * Su + np.exp(-δ) * np.hstack([0,0,Sy])
    A_Sv = (np.identity(5) - np.exp(-δ) * A)
    Sv = np.matmul(b_Sv, np.linalg.inv(A_Sv))
    
    return Sv
Пример #12
0
def sc_ode_to_matrix(sc_ode, op_func_map, t):
    """
    Convert a set of semiclassical equations of motion to matrix form.
    """
    ops = operator_sort_by_order(sc_ode.keys())
    A = Matrix([op_func_map[op] for op in ops])
    subs = [(op_func_map[op], Symbol(op_func_map[op].name)) for op in ops]
    eqns = [sc_ode[op].rhs.subs(subs) for op in ops]
    M, C = linear_eq_to_matrix(eqns, list(zip(*subs))[1])
    A_eq = Eq(-Derivative(A, t),
              Add(-C, MatMul(M, A), evaluate=False),
              evaluate=False)
    return A_eq, A, M, -C
Пример #13
0
def solve(equations_lst, unkn_lst):
    """solves the problem from list of equation and list of Unknown values
    :param equations_lst: ['x+y = 40', '2*x+4*y = 108'] -> list of strings
    :param unkn_lst:  ['x', 'y'] -> list of strings
    :return: {(26,14)}' -> list of float or ints
    """
    unkn_lst_s = unkn_lst[:]
    s_case = False
    if handle_unkn(unkn_lst_s):
        s_case = True
        unkn_lst = ['x']
    if len(equations_lst) < len(unkn_lst):
        return []
    A, b = sy.linear_eq_to_matrix(replace_equ(equations_lst), unkn_lst)
    sol = [eval(str(x)) for b in sy.linsolve((A, b), unkn_lst) for x in b]
    if not s_case:
        return sol
    return [eval(i.replace('x', str(sol[0]))) for i in unkn_lst_s]
    def generateSystem(self, replacements, full_output = False):
        eqns_rhs = self.equations.rhs.subs(replacements)

        # converting the symbolic functions ρ(t) to ρ in order to create the
        # matrix representing the linear equations (Ax=b)
        t = Symbol('t', real = True)
        for i in range(self.levels):
            for j in range(i,self.levels):
                tmp = Function(u'\u03C1{0}{1}'.format(chr(0x2080+i), 
                                                            chr(0x2080+j)))
                tmp1 = Symbol(u'\u03C1{0}{1}'.format(chr(0x2080+j), 
                                                            chr(0x2080+i)))
                eqns_rhs = eqns_rhs.subs(conjugate(tmp(t)), tmp1)

        for i in range(self.levels):
            for j in range(i,self.levels):
                tmp = Function(u'\u03C1{0}{1}'.format(chr(0x2080+i), 
                                                            chr(0x2080+j)))
                tmp1 = Symbol(u'\u03C1{0}{1}'.format(chr(0x2080+i), 
                                                            chr(0x2080+j)))
                eqns_rhs = eqns_rhs.subs(tmp(t), tmp1)

        syms = []
        for i in range(self.levels):
            for j in range(self.levels):
                syms.append(Symbol(u'\u03C1{0}{1}'.format(chr(0x2080+i), 
                                                                chr(0x2080+j))))

        # creating the matrix A (from Ax = b) for the ODE system
        matrix_eq = linear_eq_to_matrix(eqns_rhs, syms)[0]

        # check if there is still time dependence inside the matrix, return
        # a lambdified function if yes, else return a numpy array
        if t in matrix_eq.free_symbols:
            t_dependent = True
            matrix_eq = lambdify(t, matrix_eq, 'numpy')
        else:
            t_dependent = False
            matrix_eq = np.array(matrix_eq).astype(complex)

        if full_output:
            return matrix_eq, t_dependent, syms
        else:
            return matrix_eq, t_dependent
Пример #15
0
def test_equations2():
    equations = [
        "x = a*x(-1) + e",
        "y = b*y(-1) + c*x(-1) + d*p(-1)",
        "p = p(-1) + f",
    ]

    structural = ["a", "b", "c", "d"]
    shocks = ["e", "f"]

    print(sympify("f(1)"))
    print(dotprint(sympify("f(1)")))

    lhs, rhs = [], []
    for equation in equations:
        s_lhs, s_rhs = equation.split("=")

        p_lhs = sympify(s_lhs)
        p_rhs = sympify(s_rhs)

        print(dotprint(p_rhs))

        lhs.append(p_lhs)
        rhs.append(p_rhs)

    print(lhs)
    print(rhs)

    x, y, p = symbols('x y z')

    left, right = linear_eq_to_matrix(rhs, [x, y, p])

    print(left)
    print(right)

    transition, shock = DsgeModelBuilder.prepare_state_matrices(equations, ['e', 'f'], ['x', 'y', 'p'])

    print("State matrices")

    print(transition)
    print(shock)
Пример #16
0
    def _svd_solve(self, eqs_list, var_list, eps=1e-5):
        M, rhs = [
            np.array(i).astype(np.float64)
            for i in linear_eq_to_matrix(eqs_list, var_list)
        ]
        M_NS = null(M, eps=eps)
        some_solution, resid, rank, sigma = linalg.lstsq(M, rhs)

        self.aux_symbols = [
            Symbol('a_{}'.format(i)) for i in range(M_NS.shape[1])
        ]
        aux_vector = Matrix(self.aux_symbols)
        self._verbose_print('Nullspace shape: {}'.format(M_NS.shape))
        answer = {
            var: (Matrix(some_solution) + Matrix(M_NS) * aux_vector)[i, 0]
            for i, var in enumerate(var_list)
        }
        self.I_lr = self.I_lr.subs(answer).applyfunc(round_expression)
        self.I_rl = self.I_rl.subs(answer).applyfunc(round_expression)

        free_symbols = self.I_lr.free_symbols
        return M_NS.shape[1] != 0, free_symbols
    def _obj_func(self, x):
        # objective
        q, dq, ddq = self.fourier_traj.fourier_base_x2q(x)
        # print('q:', q)
        # print('dq: ', dq)
        # print('ddq: ', ddq)

        for n in range(self.sample_num):
            vars_input = q[n, :].tolist() + dq[n, :].tolist() + ddq[
                n, :].tolist()
            self.H[n * self._dyn.dof:(n + 1) *
                   self._dyn.dof, :] = self._dyn.H_b_func(*vars_input)

        #print('H: ', self.H[n*self._dyn.dof:(n+1)*self._dyn.dof, :])
        self.H /= np.subtract(self.H.max(axis=0), self.H.min(axis=0))

        f = np.linalg.cond(self.H)

        if self._obj_cnt % (self._joint_coef_num * self._dyn.dof) == 0:
            print("Condition number: {}".format(f))
        self._obj_cnt += 1
        # y = self.H
        # xmax, xmin = y.max(), y.min()
        # y = (y - xmin) / (xmax - xmin)
        # #print(y[0,:])
        #
        # f = np.linalg.cond(y)
        # print('f: ', f)

        # constraint
        g = [0.0] * (self._const_num * self.sample_num)
        g_cnt = 0

        # Joint constraints (old)
        # for j_c in self._joint_constraints:
        #     q_s, q_l, q_u, dq_l, dq_u = j_c
        #     co_num = self._dyn.coordinates.index(q_s)
        #
        #     for qt, dqt in zip(q[:, co_num], dq[:, co_num]):
        #         g[g_cnt] = qt - q_u
        #         g_cnt += 1
        #         g[g_cnt] = q_l - qt
        #         g_cnt += 1
        #         g[g_cnt] = dqt - dq_u
        #         g_cnt += 1
        #         g[g_cnt] = dq_l - dqt
        #         g_cnt += 1

        # Joint constraints (with composite joint angle considered)
        q_ss = [c[0] for c in self._joint_constraints]

        A, _ = sympy.linear_eq_to_matrix(q_ss, self._dyn.coordinates)
        A_T = np.matrix(A).astype(np.float).transpose()

        q_c = np.matmul(q, A_T)
        dq_c = np.matmul(dq, A_T)

        for j, j_c in enumerate(self._joint_constraints):
            _, q_l, q_u, dq_l, dq_u = j_c

            for qt, dqt in zip(q_c[:, j], dq_c[:, j]):
                g[g_cnt] = qt - q_u
                g_cnt += 1
                g[g_cnt] = q_l - qt
                g_cnt += 1
                g[g_cnt] = dqt - dq_u
                g_cnt += 1
                g[g_cnt] = dq_l - dqt
                g_cnt += 1

        # Cartesian Constraints
        # print(q.shape[0])
        for c_c in self._cartesian_constraints:
            frame_num, bool_max, c_x, c_y, c_z = c_c

            for num in range(q.shape[0]):
                vars_input = q[num, :].tolist()
                p_num = self._dyn.p_n_func[frame_num](*vars_input)

                self.frame_pos[num, 0] = p_num[0, 0]
                self.frame_pos[num, 1] = p_num[1, 0]
                self.frame_pos[num, 2] = p_num[2, 0]

                if bool_max == 'max':
                    g[g_cnt] = p_num[0, 0] - c_x
                    g_cnt += 1
                    g[g_cnt] = p_num[1, 0] - c_y
                    g_cnt += 1
                    g[g_cnt] = p_num[2, 0] - c_z
                    g_cnt += 1
                elif bool_max == 'min':
                    g[g_cnt] = -p_num[0, 0] + c_x
                    g_cnt += 1
                    g[g_cnt] = -p_num[1, 0] + c_y
                    g_cnt += 1
                    g[g_cnt] = -p_num[2, 0] + c_z
                    g_cnt += 1

        fail = 0
        return f, g, fail
        eq = eq.subs({y[int(x1_ab)]: int(y_ab1)})
        eq = eq.subs({y[int(x2_ab)]: int(y_ab2)})
        equations = np.append(equations, eq)
        print(equations[i - 2])

eq_Deriv_CC2 = Eq(
    (((y[3] - y[1]) / (2 * t)) - 0.5 * VA * (x[2]**2) + 4 * VA * (x[2])),
    ((-5 * (x[2]**3) + 240 * (x[2])) * M1EI))
eq_Deriv_CC2 = eq_Deriv_CC2.subs({y[int(x3_ab)]: int(dy_ab)})
eq_Deriv_CC2 = eq_Deriv_CC2.subs({y[int(x1_ab)]: int(y_ab1)})
eq_Deriv_CC2 = eq_Deriv_CC2.subs({y[int(x2_ab)]: int(y_ab2)})
equations = np.append(equations, eq_Deriv_CC2)
print(equations[i - 2])

system, equality = sp.linear_eq_to_matrix(
    equations, y_1[2:31]
)  ## ALTERAR aqui também, sempre nodes+1 ## Sempre a quantidade desejada de variaveis + 1 !!!
system_array = np.array(system).astype(np.float64)
##system_array2 = np.delete(system_array, 2, 1)
system_equality = np.array(equality).astype(np.float64)

print("\nCoefficient Matrix")
print(system_array)
print("\nEquality Matrix")
print(system_equality)

ans = np.linalg.solve(system_array, system_equality)
ans2 = np.insert(ans, 0, y_ab1)
ans3 = np.insert(ans2, (int(nodes) - 1),
                 y_ab2)  ## O valor de VA está sendo subst. pela cond contorno.
print("\nVA valor Teste")
Пример #19
0
            phi_subs_y = sym.N(
                phi_diff_y.subs(x0,
                                x_min).subs(x1, x_max).subs(y0, y_min).subs(
                                    y1,
                                    y_max).subs(phi0,
                                                z_0).subs(phix,
                                                          z_x).subs(phiy, z_y),
                2)

            solution_list.append(phi_subs_0)
            solution_list.append(phi_subs_x)
            solution_list.append(phi_subs_y)
            var_list.append([z_0, z_x, z_y])

            solution_matrices.append(
                sym.linear_eq_to_matrix(solution_list, [z_0, z_x, z_y]))
            solution_equations.append(solution_list)

        else:
            zero_vals.append(z_matrix[ycounter][xcounter])

z_vars = [
    z_matrix[countery][counterx] for countery in range(len(z_matrix))
    for counterx in range(len(z_matrix[0]))
]
equation_system = [
    0 for countery in range(len(z_matrix))
    for counterx in range(len(z_matrix[0]))
]

# print(sym.latex(sym.Matrix(equation_system)))
Пример #20
0
    def __init__(self, cct, node_voltages=True, branch_currents=False):

        if not node_voltages and not branch_currents:
            raise ValueError('No outputs')

        inductors = []
        capacitors = []
        independent_sources = []

        # Determine state variables (current through inductors and
        # voltage across acapacitors) and replace inductors with
        # current sources and capacitors with voltage sources.
        sscct = cct._new()
        cpt_map = {}

        for key, elt in cct.elements.items():
            ssnet = elt._ss_model()
            sselt = sscct._add(ssnet)
            name = elt.name
            cpt_map[name] = sselt.name

            if elt.is_inductor:
                if sselt.name in cct.elements:
                    raise ValueError(
                        'Name conflict %s, either rename the component or improve the code!'
                        % sselt.name)

                inductors.append(elt)
            elif elt.is_capacitor:
                if sselt.name in cct.elements:
                    raise ValueError(
                        'Name conflict %s, either rename the component or improve the code!'
                        % sselt.name)

                capacitors.append(elt)
            elif isinstance(elt, (I, V)):
                independent_sources.append(elt)

        self.cct = cct
        self.sscct = sscct
        # sscct can be analysed in the time domain since it has no
        # reactive components.  However, for large circuits
        # this can take a long time due to inversion of the MNA matrix.

        dotx_exprs = []
        statevars = []
        statenames = []
        initialvalues = []
        for elt in inductors + capacitors:
            name = cpt_map[elt.name]

            if isinstance(elt, L):
                # Inductors  v = L di/dt  so need v across the L
                expr = sscct[name].v / elt.cpt.L
                var = -sscct[name].isc
                x0 = elt.cpt.i0
            else:
                # Capacitors  i = C dv/dt  so need i through the C
                # The current is negated since it is from a source V_Cx
                expr = -sscct[name].i / elt.cpt.C
                var = sscct[name].voc
                x0 = elt.cpt.v0

            dotx_exprs.append(expr)
            statevars.append(var)
            statenames.append(name)
            initialvalues.append(x0)

        statesyms = sympify(statenames)

        # Determine independent sources.
        sources = []
        sourcevars = []
        sourcenames = []
        for elt in independent_sources:
            name = cpt_map[elt.name]

            if isinstance(elt, V):
                expr = elt.cpt.voc
                var = sscct[name].voc
            else:
                expr = elt.cpt.isc
                var = sscct[name].isc

            sources.append(expr)
            sourcevars.append(var)
            sourcenames.append(name)

        sourcesyms = sympify(sourcenames)

        # linear_eq_to_matrix expects only Symbols and not AppliedUndefs,
        # so substitute.
        subsdict = {}
        for var, sym1 in zip(statevars, statesyms):
            subsdict[var.expr] = sym1
        for var, sym1 in zip(sourcevars, sourcesyms):
            subsdict[var.expr] = sym1

        for m, expr in enumerate(dotx_exprs):
            dotx_exprs[m] = expr.subs(subsdict).expr.expand()

        A, b = sym.linear_eq_to_matrix(dotx_exprs, *statesyms)
        if sourcesyms != []:
            B, b = sym.linear_eq_to_matrix(dotx_exprs, *sourcesyms)
        else:
            B = []

        # Determine output variables.
        yexprs = []
        y = []

        if node_voltages:
            for node in cct.node_list:
                if node == '0':
                    continue
                yexprs.append(self.sscct[node].v.subs(subsdict).expand().expr)
                # Note, this can introduce a name conflict
                y.append(Vt('v_%s(t)' % node))

        if branch_currents:
            for name in cct.branch_list:
                # Perhaps ignore L since the current through it is a
                # state variable?
                name2 = cpt_map[name]
                yexprs.append(self.sscct[name2].i.subs(subsdict).expand().expr)
                y.append(It('i_%s(t)' % name))

        Cmat, b = sym.linear_eq_to_matrix(yexprs, *statesyms)
        if sourcesyms != []:
            D, b = sym.linear_eq_to_matrix(yexprs, *sourcesyms)
        else:
            D = []

        # Rewrite vCanon1(t) as vC(t) etc if appropriate.
        _hack_vars(statevars)
        _hack_vars(sources)

        # Note, Matrix strips the class from each element...
        self.x = tMatrix(statevars)

        self.x0 = Matrix(initialvalues)

        self.dotx = tMatrix([sym.Derivative(x1, t) for x1 in self.x])

        self.u = tMatrix(sources)

        self.A = Matrix(A)
        self.B = Matrix(B)

        # Perhaps could use v_R1(t) etc. as the output voltages?
        self.y = Matrix(y)

        self.C = Matrix(Cmat)
        self.D = Matrix(D)
Пример #21
0
    ret = {}
    # symbols = [x if type(x) == Symbol else None for x in symbols]
    for sym in symbols:
        if sym in knowledge_base:
            ret[sym] = knowledge_base[sym]
    return ret

def add_to_knowledge_base(expr):
    symbols = expr.free_symbols
    for sym in symbols:
        # won't add duplicatese because its a set
        all_symbols.add(sym) 
    knowledge_base.append(expr)

# some expressions
add_to_knowledge_base(tiles[0,0])
add_to_knowledge_base(tiles[1,0]-1)
#add_to_knowledge_base(tiles[1,1])
add_to_knowledge_base(tiles[0,1] + tiles[1,0] + tiles[1,1] - 2)

print(tiles[1,0])

print(all_symbols)
A,b = linear_eq_to_matrix(knowledge_base, all_symbols)
print(A,b)

# use array of exprs
print(all_symbols)
t = linsolve((A,b), all_symbols)
print(t)
Пример #22
0
    def _calc_M(self):
        A, b = sympy.linear_eq_to_matrix(self.tau, self.rbt_def.dd_coordinates)

        self.M = A
    def optimizeParametersNumeric(self, replacements, tspan, y0, level,
                                    parameters, bounds, max_step = 1e-1,
                                    method = 'RK45', optimize = "minimum"):
        """
        Use a differential evolution optimizer to find the parameters that get
        the minimum or maximum population in the specified level (ii) after 
        solving the system of ODEsdρ(t)/dt = -i[H,ρ]+L.

        Parameters:
        replacements    :   list of tuples, each tuple contains a symbolic
                            variable and the numeric replacement value for that
                            variable
        tspan           :   start and stop time for ODE solver
        y0              :   initial conditions of ODE system
        level           :   level (ii) to minimize or maximize
        parameters      :   list of parameters to optimize
        bounds          :   which range to search in
        max_step        :   maximum timestep of ODE solver
        method          :   method of ODE solver
        optimize        :   specify to find minimum or maximum

        Returns:
        solution        :   solution of the differential evolution optimizer
        """
        eqns_rhs = self.equations.rhs.subs(replacements)

        # converting the symbolic functions ρ(t) to ρ in order to create the
        # matrix representing the linear equations (Ax=b)
        t = Symbol('t', real = True)
        for i in range(self.levels):
            for j in range(i,self.levels):
                tmp = Function(u'\u03C1{0}{1}'.format(chr(0x2080+i), 
                                                        chr(0x2080+j)))
                tmp1 = Symbol(u'\u03C1{0}{1}'.format(chr(0x2080+j), 
                                                        chr(0x2080+i)))
                eqns_rhs = eqns_rhs.subs(conjugate(tmp(t)), tmp1)

        for i in range(self.levels):
            for j in range(i,self.levels):
                tmp = Function(u'\u03C1{0}{1}'.format(chr(0x2080+i), 
                                                                chr(0x2080+j)))
                tmp1 = Symbol(u'\u03C1{0}{1}'.format(chr(0x2080+i), 
                                                                chr(0x2080+j)))
                eqns_rhs = eqns_rhs.subs(tmp(t), tmp1)

        syms = []
        for i in range(self.levels):
            for j in range(self.levels):
                syms.append(Symbol(u'\u03C1{0}{1}'.format(chr(0x2080+i), 
                                                            chr(0x2080+j))))

        # creating the matrix A (from Ax = b) for the ODE system, has symbolic
        # variables specified in parameters in matrix
        matrix_eq = linear_eq_to_matrix(eqns_rhs, syms)[0]

        # turning matrix into a function with variables parameters
        a = lambdify(parameters, matrix_eq, 'numpy')

        # Set-up ODE solver function for differential evolution
        ode = lambda t, rho, param_values: a(*param_values)@rho
        if optimize == "minimum":
            funEvo = lambda x: solve_ivp(ode, tspan, y0, method, args = (x,),
                                    vectorized = True, max_step = max_step) \
                                        .y[self.levels*level + level,-1].real
        elif optimize == "maximum":
            funEvo = lambda x: -solve_ivp(ode, tspan, y0, method, args = (x,),
                                        vectorized = True, max_step = max_step)\
                                        .y[self.levels*level + level,-1].real
        else:
            raise ValueError('Specify optimize either as minimum or maximum.')

        sol = differential_evolution(funEvo, bounds = bounds, tol = 1e-4)
        return sol
Пример #24
0
    def _analyse(self):

        eqns = matrix(list(self.equations_dict.values()))

        return sym.linear_eq_to_matrix(eqns.expand(), *self.y)
Пример #25
0
    if xcounter < number_of_divisions - 1:
        solution_list = []
        x_high = x_range[xcounter]
        x_low = x_range[xcounter + 1]
        y_high = y_vars[xcounter]
        y_low = y_vars[xcounter + 1]
        eq0 = phi_diff_0.subs(xstart, x_high).subs(xend, x_low).subs(
            ystart, y_high).subs(yend, y_low)
        eq1 = phi_diff_x.subs(xstart, x_high).subs(xend, x_low).subs(
            ystart, y_high).subs(yend, y_low)
        solution_list.append(eq0)
        solution_list.append(eq1)
        var_list.append([y_high, y_low])
        solution_equations.append(solution_list)
        solution_matrices.append(
            sym.linear_eq_to_matrix(solution_list, [y_high, y_low]))

    else:
        zero_boundaries.append(y_high)

equation_system = [0 for derp in range(number_of_divisions)]

# print(sym.latex(solution_matrices))

for solution_counter in range(len(solution_equations)):
    for eq_counter in range(len(solution_equations[solution_counter])):

        equation_system[y_vars.index(
            var_list[solution_counter]
            [eq_counter])] += solution_equations[solution_counter][eq_counter]
Пример #26
0
        B.col_del(-1)

    M = K_H - B
    equations = []

    for r in range(M.shape[0]):
        for c in range(M.shape[1]):
            equation = sp.Eq(M[r, c])

            if equation not in equations and type(equation) == sp.Eq:
                equations.append(equation)

    solution = sp.solve(equations, low_kernel)

    ## coefficient matrix to find scaled up kernel
    coefficient_matrix = sp.linear_eq_to_matrix(equations, high_kernel)[0]


###################################################################



####################### find downscaled avg pooling #########################

    # method = 'linear'
    # coarse_scale = 10
    # fine_scale = 20
    #
    # P = get_prolongation(method, coarse_scale, fine_scale, __zero_padding=False)
    # R = get_restriction(method, fine_scale // 2, coarse_scale // 2, __zero_padding=False)
    #
Пример #27
0
    def from_circuit(cls, cct, node_voltages=None, branch_currents=None):
        """`node_voltages` is a list of node names to use as voltage outputs.
        If `None` use all the unique node names.  Use `()`
        if want no branch currents.

        `branch_currents` is a list of component names to use as
        current outputs.  If `None` use all the components.  Use `()`
        if want no branch currents."""

        if node_voltages is None:
            node_voltages = cct.node_list

        if branch_currents is None:
            branch_currents = cct.branch_list

        if node_voltages == [] and branch_currents == []:
            raise ValueError('State-space: no outputs')

        inductors = []
        capacitors = []
        independent_current_sources = []
        independent_voltage_sources = []

        # Determine state variables (current through inductors and
        # voltage across acapacitors) and replace inductors with
        # current sources and capacitors with voltage sources.
        sscct = cct._new()
        cpt_map = {}

        for key, elt in cct.elements.items():
            ssnet = elt._ss_model()
            sselt = sscct._add(ssnet)
            name = elt.name
            cpt_map[name] = sselt.name

            if elt.is_inductor:
                if sselt.name in cct.elements:
                    raise ValueError(
                        'Name conflict %s, either rename the component or improve the code!'
                        % sselt.name)

                inductors.append(elt)
            elif elt.is_capacitor:
                if sselt.name in cct.elements:
                    raise ValueError(
                        'Name conflict %s, either rename the component or improve the code!'
                        % sselt.name)
                capacitors.append(elt)
            elif elt.is_independent_current_source:
                independent_current_sources.append(elt)
            elif elt.is_independent_voltage_source:
                independent_voltage_sources.append(elt)

        independent_sources = independent_voltage_sources + independent_current_sources

        # Build circuit graph and check if have inductor in series with
        # current source.
        if independent_current_sources != [] and inductors != []:
            cg = CircuitGraph(cct)
            for elt in independent_current_sources:
                for name in cg.in_series(elt.name):
                    if cct[name].is_inductor:
                        raise ValueError(
                            'Cannot create state-space model since have inductor %s in series with independent current source %s'
                            % (name, elt.name))

        cct = cct
        sscct = sscct
        # sscct can be analysed in the time domain since it has no
        # reactive components.  However, for large circuits
        # this can take a long time due to inversion of the MNA matrix.

        try:
            # Analyse node voltages and branch currents.
            sscct[0].V
        except ValueError as e:
            reasons = []
            if len(inductors) > 0:
                reasons.append(
                    'Check for cut set consisting only of current sources and/or inductors.'
                )
            if len(capacitors) > 0:
                reasons.append(
                    'Check for a loop consisting of voltage sources and/or capacitors.'
                )

            raise ValueError("State-space analysis failed.\n%s\n     %s" %
                             (e, '\n    '.join(reasons)))

        dotx_exprs = []
        statevars = []
        statenames = []
        initialvalues = []
        for elt in inductors + capacitors:
            name = cpt_map[elt.name]

            if isinstance(elt, L):
                # Inductors  v = L di/dt  so need v across the L
                expr = sscct[name].v / elt.cpt.L
                var = -sscct[name].isc
                x0 = elt.cpt.i0
            else:
                # Capacitors  i = C dv/dt  so need i through the C
                # The current is negated since it is from a source V_Cx
                expr = -sscct[name].i / elt.cpt.C
                var = sscct[name].voc
                x0 = elt.cpt.v0

            dotx_exprs.append(expr)
            statevars.append(var)
            statenames.append(name)
            initialvalues.append(x0)

        statesyms = sympify(statenames)

        # Determine independent sources.
        sources = []
        sourcevars = []
        sourcenames = []
        for elt in independent_sources:
            name = cpt_map[elt.name]

            if isinstance(elt, V):
                expr = elt.cpt.voc
                var = sscct[name].voc
            else:
                expr = elt.cpt.isc
                var = sscct[name].isc

            sources.append(expr)
            sourcevars.append(var)
            sourcenames.append(name)

        sourcesyms = sympify(sourcenames)

        # linear_eq_to_matrix expects only Symbols and not AppliedUndefs,
        # so substitute.
        subsdict = {}
        for var, sym1 in zip(statevars, statesyms):
            subsdict[var.expr] = sym1
        for var, sym1 in zip(sourcevars, sourcesyms):
            subsdict[var.expr] = sym1

        for m, expr in enumerate(dotx_exprs):
            dotx_exprs[m] = expr.subs(subsdict).expr.expand()

        if dotx_exprs == []:
            warn('State-space: no state variables found')
        if sourcesyms == []:
            warn('State-space: no independent sources found')

        if dotx_exprs != []:
            A, b = sym.linear_eq_to_matrix(dotx_exprs, *statesyms)
        else:
            A = sym.zeros(len(dotx_exprs), len(dotx_exprs))

        if sourcesyms != [] and dotx_exprs != []:
            B, b = sym.linear_eq_to_matrix(dotx_exprs, *sourcesyms)
        else:
            B = sym.zeros(len(dotx_exprs), len(sources))

        # Determine output variables.
        yexprs = []
        y = []

        for node in node_voltages:
            if node == '0':
                continue
            yexprs.append(sscct[node].v.subs(subsdict).expand().expr)
            # Note, this can introduce a name conflict
            y.append(voltage('v_%s(t)' % node))

        for name in branch_currents:
            # Perhaps ignore L since the current through it is a
            # state variable?
            name2 = cpt_map[name]
            yexprs.append(sscct[name2].i.subs(subsdict).expand().expr)
            y.append(current('i_%s(t)' % name))

        if statesyms != [] and yexprs != []:
            C, b = sym.linear_eq_to_matrix(yexprs, *statesyms)
        else:
            C = sym.zeros(len(yexprs), len(statesyms))

        if sourcesyms != [] and yexprs != []:
            D, b = sym.linear_eq_to_matrix(yexprs, *sourcesyms)
        else:
            D = sym.zeros(len(yexprs), len(sourcesyms))

        # Rewrite vCanon1(t) as vC(t) etc if appropriate.
        _hack_vars(statevars)
        _hack_vars(sources)

        # Note, Matrix strips the class from each element...
        x = TimeDomainMatrix(statevars)

        x0 = Matrix(initialvalues)

        u = TimeDomainMatrix(sources)

        # Perhaps could use v_R1(t) etc. as the output voltages?
        y = TimeDomainMatrix(y)

        A = Matrix(A)
        B = Matrix(B)
        C = Matrix(C)
        D = Matrix(D)

        return StateSpace(A, B, C, D, u, y, x, x0)
Пример #28
0
# Se definen las variables
#sx, sy, sz, txy, txz, tyz = sp.symbols('sx, sy, sz, txy, txz, tyz')
sx, sy, sz = sp.symbols('sigma_x, sigma_y, sigma_z')
txy, txz, tyz = sp.symbols('tau_xy, tau_xz, tau_yz')
alpha1, alpha2, alpha3 = sp.symbols('alpha1:4')
beta1, beta2, beta3 = sp.symbols('beta1:4')
gamma1, gamma2, gamma3 = sp.symbols('gamma1:4')

# Se define la matriz de tensiones en coordenadas rectangulares sigma
sigma = sp.Matrix([[sx, txy, txz], [txy, sy, tyz], [txz, tyz, sz]])

# Se define la matriz de transformación T
T = sp.Matrix([[alpha1, alpha2, alpha3], [beta1, beta2, beta3],
               [gamma1, gamma2, gamma3]])

# Se calcula la matriz de tensiones sigmaP en el sistema de coordenadas
# especificado por los vectores definidos en la matriz T
sigmaP = T.T * sigma * T

# Se extraen los términos de la matriz de tensiones sigmaP
sxp = sp.expand(sigmaP[1 - 1, 1 - 1])  # elemento 1,1 de la matriz sigmaP
syp = sp.expand(sigmaP[2 - 1, 2 - 1])
szp = sp.expand(sigmaP[3 - 1, 3 - 1])
typzp = sp.expand(sigmaP[2 - 1, 3 - 1])  # elemento 2,3 de la matriz sigmaP
txpzp = sp.expand(sigmaP[1 - 1, 3 - 1])
txpyp = sp.expand(sigmaP[1 - 1, 2 - 1])

# Se organizan las ecuaciones anteriores en una matriz
T_sigma, _ = sp.linear_eq_to_matrix([sxp, syp, szp, typzp, txpzp, txpyp],
                                    [sx, sy, sz, tyz, txz, txy])
Пример #29
0
eqList = []
n = 0
for i in range(0, node):
    for j in range(0, node):
        value1 = symengine.sympify(nodeMatrix[i, j + 1])
        value2 = symengine.sympify(nodeMatrix[i + 1, j])
        value3 = symengine.sympify(nodeMatrix[i + 2, j + 1])
        value4 = symengine.sympify(nodeMatrix[i + 1, j + 2])
        equation = symengine.Eq(
            value1 + value2 + value3 + value4 -
            4 * symengine.sympify(nodeMatrixSymbolsList[i + j + n]), 0)
        eqList.append(equation)
    n += (node - 1)

symatA, symatB = sym.linear_eq_to_matrix(eqList, nodeMatrixSolving)
matA = np.array(symatA, dtype=float)
matB = np.array(symatB, dtype=float)

solution = linalg.solve(matA, matB)
"""The fifth part of the code is to replace the variables in the original matrix into the result from the solved equations."""
n = 0
for i in range(0, node):
    for j in range(0, node):
        nodeMatrix[i + 1, j + 1] = solution[i + j + n]
    n += (node - 1)
"""The sixth part of the code is to plot the original matrix into a heatmap."""
result = np.array(nodeMatrix, dtype=float)
sns.heatmap(result[1:node + 1, 1:node + 1])
"""The seventh part of the code is to ask the user if they want to export the data to Excel."""
saveYes = str.lower(input('Save data to Excel? (y/n): '))
Пример #30
0
    replacement_eq.append(eq)

# print(sym.latex(sym.Matrix(replacement_eq)))
#Conditions where the equation already solves to zero are a problem, because 0 = 0 will not evaluate
#This replaces the boundary condition and sets a specific variable to 0 so it can be solved.
boundary_eq_with_result = []

for z_index, variable in enumerate(z_vars):
    if variable not in zero_vals:

        boundary_eq_with_result.append(replacement_eq[z_index])
    else:
        boundary_eq_with_result.append(sym.Eq(variable, 0))

# print(sym.latex(sym.Matrix(boundary_eq_with_result)))
a = sym.linear_eq_to_matrix(boundary_eq_with_result, z_vars)
print(sym.latex(a))
#6. Solve the System. Sympy linsolve makes short work of that.
resultset = sym.linsolve(boundary_eq_with_result, z_vars)
# print(sym.latex(sym.Matrix(boundary_eq_with_result)))
print(sym.latex(resultset))

#7 Use the computed results to determine desired results.
#In most FEA solutions, this would be stresses or fluid flow, but in this case, it's just the Z-Values.
result_vals = [resultset.args[0][counter] for counter in range(len(z_vars))]
# print(sym.latex(sym.Matrix(result_vals)))

result_grid = num.zeros([len(XGrid_expanded), len(XGrid_expanded[0])])

#Make a meshgrid with the Z-Values in it
# varcount = 0
Пример #31
0
    def __init__(self, cct, node_voltages=True, branch_currents=False):

        if not node_voltages and not branch_currents:
            raise ValueError('No outputs')
        
        inductors = []
        capacitors = []
        independent_sources = []

        # Determine state variables (current through inductors and
        # voltage across acapacitors) and replace inductors with
        # current sources and capacitors with voltage sources.
        sscct = cct._new()
        cpt_map = {}

        for key, elt in cct.elements.items():
            ssnet = elt.ss_model()
            sselt = sscct._add(ssnet)
            name = elt.name
            cpt_map[name] = sselt.name
            
            if isinstance(elt, L):
                if sselt.name in cct.elements:
                    raise ValueError('Name conflict %s, either rename the component or iprove the code!' % sselt.name)

                inductors.append(elt)
            elif isinstance(elt, C):
                if sselt.name in cct.elements:
                    raise ValueError('Name conflict %s, either rename the component or iprove the code!' % sselt.name)
                
                capacitors.append(elt)
            elif isinstance(elt, (I, V)):
                independent_sources.append(elt)                
                
        self.cct = cct
        self.sscct = sscct

        # sscct can be analysed in the time domain since it has not
        # reactive components.
        
        dotx_exprs = []
        statevars = []
        statenames = []
        initialvalues = []
        for elt in inductors + capacitors:
            name = cpt_map[elt.name]

            if isinstance(elt, L):
                # Inductors  v = L di/dt  so need v across the L
                expr = sscct[name].v / elt.cpt.L
                var = sscct[name].isc
                x0 = elt.cpt.i0
            else:
                # Capacitors  i = C dv/dt  so need i through the C
                expr = sscct[name].i / elt.cpt.C
                var = sscct[name].voc
                x0 = elt.cpt.v0

            dotx_exprs.append(expr)
            statevars.append(var)
            statenames.append(name)
            initialvalues.append(x0)

        statesyms = sympify(statenames)

        # Determine independent sources.
        sources = []
        sourcevars = []
        sourcenames = []
        for elt in independent_sources:
            name = cpt_map[elt.name]
            
            if isinstance(elt, V):
                expr = elt.cpt.voc
                var = sscct[name].voc                
            else:
                expr = elt.cpt.isc
                var = sscct[name].isc

            sources.append(expr)
            sourcevars.append(var)
            sourcenames.append(name)

        sourcesyms = sympify(sourcenames)            

        # linear_eq_to_matrix expects only Symbols and not AppliedUndefs,
        # so substitute.
        subsdict = {}
        for var, sym1 in zip(statevars, statesyms):
            subsdict[var.expr] = sym1
        for var, sym1 in zip(sourcevars, sourcesyms):
            subsdict[var.expr] = sym1       

        for m, expr in enumerate(dotx_exprs):
            dotx_exprs[m] = expr.subs(subsdict).expr.expand()

        A, b = sym.linear_eq_to_matrix(dotx_exprs, *statesyms)
        B, b = sym.linear_eq_to_matrix(dotx_exprs, *sourcesyms)

        # Determine output variables.
        yexprs = []
        y = []

        if node_voltages:
            for node in cct.node_list:
                if node == '0':
                    continue
                yexprs.append(self.sscct[node].v.subs(subsdict).expand())
                y.append(Vt('vn%s(t)' % node))

        if branch_currents:
            for name in cct.branch_list:
                # Perhaps ignore L since the current through it is a
                # state variable?
                name2 = cpt_map[name]                    
                yexprs.append(self.sscct[name2].i.subs(subsdict).expand())
                y.append(It('i%s(t)' % name))                    

        Cmat, b = sym.linear_eq_to_matrix(yexprs, *statesyms)
        D, b = sym.linear_eq_to_matrix(yexprs, *sourcesyms)

        # Rewrite vCanon1(t) as vC(t) etc if appropriate.
        _hack_vars(statevars)
        _hack_vars(sources)
        
        # Note, Matrix strips the class from each element...
        self.x = tMatrix(statevars)

        self.x0 = Matrix(initialvalues)
        
        self.dotx = tMatrix([sym.Derivative(x1, t) for x1 in self.x])

        self.u = tMatrix(sources)

        self.A = Matrix(A)
        self.B = Matrix(B)        
            
        # Perhaps could use v_R1(t) etc. as the output voltages?
        self.y = Matrix(y)

        self.C = Matrix(Cmat)
        self.D = Matrix(D)