Beispiel #1
0
]

sum_substitution_cases = [
    (a * b + Sum(c * k, (k, 0, n)), {
        'a': b,
        'b': 2,
        'k': 1,
        'n': 2
    }, b * 2 + c * (1 + 2)),
]

indexed_substitution_cases = [(a_[i] * b, {
    'b': 3
}, a_[i] * 3),
                              (a_[i] * b, {
                                  'a': sympy.Array([1, 2, 3])
                              }, sympy.Array([1, 2, 3])[i] * b),
                              (sympy.Array([1, 2, 3])[i] * b, {
                                  'i': 1
                              }, 2 * b)]

vector_valued_cases = [
    (a * b, {
        'a': sympy.Array([1, 2, 3])
    }, sympy.Array([1, 2, 3]) * b),
    (a * b, {
        'a': sympy.Array([1, 2, 3]),
        'b': sympy.Array([4, 5, 6])
    }, sympy.Array([4, 10, 18])),
]
inp1, inp2, inp3, inp4, f = sp.symbols('inp1 inp2 inp3 inp4 f')

#_Weights_definitions_________________________________________________________

neuronsByLayer = [4, 4, 4, 2, 1]
W = []
for k in range(len(neuronsByLayer) - 1):
    auxLis = []
    for i in range(neuronsByLayer[k]):
        for j in range(neuronsByLayer[k + 1]):
            exec('w' + str(k + 1) + str(i + 1) + str(j + 1) +
                 ' = sp.symbols("w' + str(k + 1) + str(i + 1) + str(j + 1) +
                 '")')
            exec('auxLis.append(w' + str(k + 1) + str(i + 1) + str(j + 1) +
                 ')')
    W.append(
        sp.Array(auxLis).reshape(neuronsByLayer[k], neuronsByLayer[k + 1]))
#______________________________________________________________________________

#_function_definition_and_input__________
f = lambda x: 1 / (1 + sp.exp(-x))
input = sp.Array([inp1, inp2, inp3, inp4])
#_________________________________________

#_Outputs_____________________________________________________________________
o_l1 = [f(input[0]), f(input[1]), f(input[2]), f(input[3])]
o_l2 = tenCon(tenProd(o_l1, W[0]).applyfunc(f), (0, 1))
o_l3 = tenCon(tenProd(o_l2, W[1]).applyfunc(f), (0, 1))
o_l4 = tenCon(tenProd(o_l3, W[2]).applyfunc(f), (0, 1))
o_l5 = tenCon(tenProd(o_l4, W[3]).applyfunc(f), (0, 1))
#______________________________________________________________________________
Beispiel #3
0
 def Z(self, value):
     self.validation.Zsetter(self, value)
     if value is None:
         self._Z = None
     else:
         self._Z = sp.Array(value)
    W = W.reshape(outputNeurons, inputNeurons)
    return (W)

#_weights_between_layers_1_and_2____
W_l1tol2 = weights(1, 4, 4)
#_weights_between_layers_2_and_3____
W_l2tol3 = weights(2, 4, 4)
#_weights_between_layers_3_and_4____
W_l3tol4 = weights(3, 4, 2)
#_weights_between_layers_4_and_5____
W_l4tol5 = weights(4, 2, 1)
#______________________________________________________________________________

#_function_definition_and_input______________
f = lambda x: 1 / (1 + sp.exp(-x))
input = sp.Array([inp1, inp2, inp3, inp4])
#_____________________________________________

#_Outputs_____________________________________________________________________
o_l1 = sp.Array([[f(input[0]), f(input[1]), f(input[2]), f(input[3])]])
o_l2 = sp.Array([
    sp.tensorcontraction(
        sp.tensorproduct(o_l1, W_l1tol2)[0, :, :, :].applyfunc(f), (0, 1))
])
o_l3 = sp.Array([
    sp.tensorcontraction(
        sp.tensorproduct(o_l2, W_l2tol3)[0, :, :, :].applyfunc(f), (0, 1))
])
o_l4 = sp.Array([
    sp.tensorcontraction(
        sp.tensorproduct(o_l3, W_l3tol4)[0, :, :, :].applyfunc(f), (0, 1))
Beispiel #5
0
import matplotlib.pyplot as plt
import numpy as np
import sympy
from sympy.parsing import sympy_parser

import lmfit

###############################################################################
# Instead of creating the SymPy symbols explicitly and building an expression
# with them, we will use the SymPy parser.

gauss_peak1 = sympy_parser.parse_expr('A1*exp(-(x-xc1)**2/(2*sigma1**2))')
gauss_peak2 = sympy_parser.parse_expr('A2*exp(-(x-xc2)**2/(2*sigma2**2))')
exp_back = sympy_parser.parse_expr('B*exp(-x/xw)')

model_list = sympy.Array((gauss_peak1, gauss_peak2, exp_back))
model = sum(model_list)
print(model)

###############################################################################
# We are using SymPy's lambdify function to make a function from the model
# expressions. We then use these functions to generate some fake data.

model_list_func = sympy.lambdify(list(model_list.free_symbols), model_list)
model_func = sympy.lambdify(list(model.free_symbols), model)

###############################################################################
# Generate synthetic data with noise and plot the data.
np.random.seed(1)
x = np.linspace(0, 10, 40)
param_values = dict(x=x,
Beispiel #6
0
    def test_array_broadcast(self):
        expected = sympy.Array([1, 2, a, b])

        self.assertEqual(expected, Broadcast(list(expected), (4,)))
        self.assertEqual(expected, Broadcast(tuple(expected), (4,)))
        self.assertEqual(expected, Broadcast(expected, (4,)))
Beispiel #7
0
import numpy as np
import sympy as sp
import math
import matplotlib.pyplot as plt

xp = sp.Array([-1.5, -1, -0.5, 0, 0.5, 1, 1.5])


def func_np(x):
    y = 8 * np.sin(1 / np.tan(3)) + (np.sin(5 * x))**2 / (5 * np.cos(10 * x))
    return y


def func(x):
    y = 8 * sp.sin(1 / sp.tan(3)) + (sp.sin(5 * x))**2 / (5 * sp.cos(10 * x))
    return y


def func_six():
    x = sp.Symbol('x')
    r = sp.diff(func(x), x, xp.shape[0])
    return sp.lambdify(x, r, 'numpy')


def newton_up():
    n = xp.shape[0]
    x = sp.Symbol('x')
    res = 0
    div = func(x)
    for i in range(0, n, 1):
        temp = div.evalf(subs={x: xp[i]})
Beispiel #8
0
from sympy import tensorcontraction as tenCon
from sympy import tensorproduct as tenProd
inp1, inp2, inp3, inp4, f = sp.symbols('inp1 inp2 inp3 inp4 f')
    

 #_Weights_definitions_________________________________________________________
neuronsByLayer = [5,10,10,5,1]
W = []
for k in range(len(neuronsByLayer) - 1):
    auxLis = []
    for i in range(neuronsByLayer[k]):
        for j in range(neuronsByLayer[k + 1]):
            exec('w' + str(k+1) + str(i+1) + str(j+1) +
                 ' = sp.symbols("w' + str(k+1) + str(i+1) + str(j+1) + '")')
            exec('auxLis.append(w' + str(k+1) + str(i+1) + str(j+1) + ')')
    W.append(sp.Array(auxLis).reshape(neuronsByLayer[k],
             neuronsByLayer[k + 1]))
#______________________________________________________________________________


 #_input_________________________________________________________
input = []
for i in range(neuronsByLayer[0]):
    exec('inp' + str(i+1) + ' = sp.symbols("inp' + str(i+1) + '")')
    exec('input.append(inp' + str(i+1) + ')')
#________________________________________________________________
    
    
 #_function_definition_and_input__________
f = lambda x: 1 / (1 + sp.exp(-x))
#_________________________________________
Beispiel #9
0
 def f(self, x, u, p, *, s):
     """ODE function."""
     u0  = 44.5695
     wd = s.zw*s.w + (u0 + s.zq)*s.q + s.zeta*s.eta
     qd = s.mw*s.w + s.mq*s.q + s.meta*s.eta
     return sympy.Array([wd, qd])
Beispiel #10
0
 def get_wind_ned_sym2(self, _x, _y, _z, _t):
     wd = self.strength*sym.exp(-((_x-self.center[0])**2 + (_y-self.center[1])**2)/self.radius**2)
     ret = sym.Array([self.cst[0], self.cst[1], self.cst[2]+wd])
     #ret = sym.Array(self.cst)+[0, 0, wd] # nope
     return ret
Beispiel #11
0
 def get_wind_ned_sym2(self, _x, _y, _z, _t):
     ret =  sym.Array([0, 0, 0])
     for atm in self.atms:
         ret += atm.get_wind_ned_sym2(_x, _y, _z, _t)
     return ret
Beispiel #12
0
 def get_wind_ned_sym2(self, _n, _e, _d, _t):
     wd = self.strength*sym.exp(-((_n-self.center[0])**2 + self.foo*(_e-self.center[1])**2)/self.radius**2)
     ret = sym.Array([self.cst[0], self.cst[1], self.cst[2]+wd])
     return ret
Beispiel #13
0
 def get_wind_ned_sym2(self, _n, _e, _d, _t):
     return sym.Array([0, self.s*sym.cos(_n/25.), 0]) 
Beispiel #14
0
def SARIMACorrelation(trendparams: tuple = (0, 0, 0),
                      seasonalparams: tuple = (0, 0, 0, 1),
                      trendAR=None,
                      trendMA=None,
                      seasonAR=None,
                      seasonMA=None):
    p, d, q = trendparams
    P, D, Q, m = seasonalparams
    print(f'SARIMA({p},{d},{q})({P},{D},{Q},{m})')

    assert type(p) is int, 'Input parameter "p" is not an integer type.'
    assert type(d) is int, 'Input parameter "d" is not an integer type.'
    assert type(q) is int, 'Input parameter "q" is not an integer type.'
    assert type(P) is int, 'Input parameter "P" is not an integer type.'
    assert type(D) is int, 'Input parameter "D" is not an integer type.'
    assert type(Q) is int, 'Input parameter "Q" is not an integer type.'
    assert type(m) is int, 'Input parameter "m" is not an integer type.'

    if trendAR:
        assert len(
            trendAR
        ) == p, f'The len(trendAR) must be {p}. Reset the parameters.'
    else:
        trendAR = [0] * p
    if trendMA:
        assert len(
            trendMA
        ) == q, f'The len(trendMA) must be {q}. Reset the parameters.'
    else:
        trendMA = [0] * q
    if seasonAR:
        assert len(
            seasonAR
        ) == P, f'The len(seasonAR) must be {P}. Reset the parameters.'
    else:
        seasonAR = [0] * P
    if seasonMA:
        assert len(
            seasonMA
        ) == Q, f'The len(seasonMA) must be {Q}. Reset the parameters.'
    else:
        seasonMA = [0] * Q

    Y_order = p + P * m + d + D * m
    e_order = q + Q * m

    # define Y, e
    Y, e = sympy.symbols('Y_t, e_t')
    I, J = sympy.symbols('i, j')
    Y_ = {}
    e_ = {}
    Y_['t'] = Y
    Y__ = [[Y_['t']]]
    e_['t'] = e
    e__ = [[e_['t']]]
    for i in range(1, Y_order + 1):
        Y_[f't-{i}'] = sympy.symbols(f'Y_t-{i}')
        Y__.append([
            Y_[f't-{i}'] * (I**i)
        ])  # Y__ = [ [Y_['t']], [Y_['t-1']], ..., [Y_['t-(p+P*m+q+Q*m)']] ]
    for i in range(1, e_order + 1):
        e_[f't-{i}'] = sympy.symbols(f'e_t-{i}')
        e__.append([
            e_[f't-{i}'] * (J**i)
        ])  # e__ = [ [e_['t']], [e_['t-1']], ..., [e_['t-(q+Q*m)']] ]

    # define L
    L = sympy.symbols('L')
    S_Lag = L**m
    T_Lag = L
    S_Lag_Diff = (1 - L**m)**D
    T_Lag_Diff = (1 - L)**d

    # define coefficients : phis(T), Phis(S), thetas(T), Thetas(S)
    T_phi = {}
    T_phis = []
    L_byT_phi = []
    S_phi = {}
    S_phis = []
    L_byS_phi = []
    T_theta = {}
    T_thetas = []
    L_byT_theta = []
    S_theta = {}
    S_thetas = []
    L_byS_theta = []

    for p_ in range(0, p + 1):
        T_phi[p_] = sympy.symbols(f'phi_{p_}')
        T_phis.append(
            -T_phi[p_])  # T_phis      = [T_phi[0], T_phi[1], ..., T_phi[p]]
        L_byT_phi.append([T_Lag**p_
                          ])  # L_byT_phi   = [[L**0], [L**1], ..., [L**p]]
    for P_ in range(0, P + 1):
        S_phi[P_] = sympy.symbols(f'Phi_{P_}')
        S_phis.append(
            -S_phi[P_])  # S_phis      = [S_phi[0], S_phi[1], ..., S_phi[P]]
        L_byS_phi.append([
            S_Lag**P_
        ])  # L_byS_phi   = [[(L**m)**0], [(L**m)**1], ..., [(L**m)**P]]
    for q_ in range(0, q + 1):
        T_theta[q_] = sympy.symbols(f'theta_{q_}')
        T_thetas.append(
            T_theta[q_]
        )  # T_thetas    = [T_theta[0], T_theta[1], ..., T_theta[q]]
        L_byT_theta.append([T_Lag**q_
                            ])  # L_byT_theta = [[L**0], [L**1], ..., [L**q]]
    for Q_ in range(0, Q + 1):
        S_theta[Q_] = sympy.symbols(f'Theta_{Q_}')
        S_thetas.append(
            S_theta[Q_]
        )  # S_thetas    = [T_theta[0], T_theta[1], ..., T_theta[Q]]
        L_byS_theta.append([
            S_Lag**Q_
        ])  # L_byS_theta = [[(L**m)**0], [(L**m)**1], ..., [(L**m)**Q]]

    T_phi_Lag = sympy.Matrix([T_phis]) * sympy.Matrix(L_byT_phi)
    S_phi_Lag = sympy.Matrix([S_phis]) * sympy.Matrix(L_byS_phi)
    T_theta_Lag = sympy.Matrix([T_thetas]) * sympy.Matrix(L_byT_theta)
    S_theta_Lag = sympy.Matrix([S_thetas]) * sympy.Matrix(L_byS_theta)

    Y_operator = (T_phi_Lag * S_phi_Lag * T_Lag_Diff * S_Lag_Diff).subs(
        T_phi[0], -1).subs(S_phi[0], -1)[0]
    e_operator = (T_theta_Lag * S_theta_Lag).subs(T_theta[0],
                                                  1).subs(S_theta[0], 1)[0]

    Y_operation = sympy.collect(Y_operator.expand(), L)
    e_operation = sympy.collect(e_operator.expand(), L)

    Y_coeff = sympy.Poly(Y_operation, L).all_coeffs()[::-1]
    e_coeff = sympy.Poly(e_operation, L).all_coeffs()[::-1]

    Y_term = sympy.Matrix([Y_coeff]) * sympy.Matrix(Y__)  # left-side
    e_term = sympy.Matrix([e_coeff]) * sympy.Matrix(e__)  # right-side

    Time_Series = {}
    Time_Series['Y_t(i,j)'] = sympy.Poly(Y - Y_term[0] + e_term[0], (I, J))
    Time_Series['Y_t'] = Time_Series['Y_t(i,j)'].subs(I, 1).subs(J, 1)
    for i in range(1, int(p + P * m + d + D * m) + 1):
        Time_Series['Y_t'] = sympy.collect(Time_Series['Y_t'],
                                           Y_[f't-{i}']).simplify()
    for i in range(1, int(q + Q * m) + 1):
        Time_Series['Y_t'] = sympy.collect(Time_Series['Y_t'],
                                           e_[f't-{i}']).simplify()
    print('* Time Series Equation(Analytic Form)')
    sympy.pprint(Time_Series['Y_t'])
    print()

    Time_Series['Analytic_Coeff_of_Y'] = Time_Series['Y_t(i,j)'].subs(
        J, 0).all_coeffs()[::-1]
    Time_Series['Analytic_Coeff_of_e'] = Time_Series['Y_t(i,j)'].subs(
        I, 0).all_coeffs()[::-1]

    Time_Series['Numeric_Coeff_of_Y'] = Time_Series['Y_t(i,j)'].subs(
        J, 0) - e_['t']
    Time_Series['Numeric_Coeff_of_e'] = Time_Series['Y_t(i,j)'].subs(I, 0)
    for i, (phi, Np) in enumerate(zip(list(T_phi.values())[1:], trendAR)):
        Time_Series['Numeric_Coeff_of_Y'] = Time_Series[
            'Numeric_Coeff_of_Y'].subs(phi, Np)
    for i, (Phi, NP) in enumerate(zip(list(S_phi.values())[1:], seasonAR)):
        Time_Series['Numeric_Coeff_of_Y'] = Time_Series[
            'Numeric_Coeff_of_Y'].subs(Phi, NP)
    for i, (theta, Nt) in enumerate(zip(list(T_theta.values())[1:], trendMA)):
        Time_Series['Numeric_Coeff_of_e'] = Time_Series[
            'Numeric_Coeff_of_e'].subs(theta, Nt)
    for i, (Theta, NT) in enumerate(zip(list(S_theta.values())[1:], seasonMA)):
        Time_Series['Numeric_Coeff_of_e'] = Time_Series[
            'Numeric_Coeff_of_e'].subs(Theta, NT)
    print('* Time Series Equation(Numeric Form)')
    sympy.pprint((Time_Series['Numeric_Coeff_of_Y'] +
                  Time_Series['Numeric_Coeff_of_e']).subs(I, 1).subs(J, 1))
    Time_Series['Numeric_Coeff_of_Y'] = sympy.Poly(
        Time_Series['Numeric_Coeff_of_Y'], I).all_coeffs()[::-1]
    Time_Series['Numeric_Coeff_of_e'] = sympy.Poly(
        Time_Series['Numeric_Coeff_of_e'], J).all_coeffs()[::-1]

    final_coeffs = [[], []]
    print('\n* Y params')
    print(f'- TAR({trendparams[0]}) phi : {trendAR}')
    print(f'- TMA({trendparams[2]}) theta : {trendMA}')
    for i, (A_coeff_Y, N_coeff_Y) in enumerate(
            zip(Time_Series['Analytic_Coeff_of_Y'],
                Time_Series['Numeric_Coeff_of_Y'])):
        if i == 0:
            pass
        elif i != 0:
            A_coeff_Y = A_coeff_Y.subs(Y_[f"t-{i}"], 1)
            N_coeff_Y = N_coeff_Y.subs(Y_[f"t-{i}"], 1)
            print(f't-{i} : {A_coeff_Y} > {round(N_coeff_Y, 5)}')
            final_coeffs[0].append(N_coeff_Y)

    print('\n* e params')
    print(f'- SAR({seasonalparams[0]}) Phi : {seasonAR}')
    print(f'- SMA({seasonalparams[2]}) Theta : {seasonMA}')
    for i, (A_coeff_e, N_coeff_e) in enumerate(
            zip(Time_Series['Analytic_Coeff_of_e'],
                Time_Series['Numeric_Coeff_of_e'])):
        if i == 0:
            A_coeff_e = A_coeff_e.subs(e_[f"t"], 1)
            N_coeff_e = N_coeff_e.subs(e_[f"t"], 1)
            print(f't-{i} : {A_coeff_e} > {1}')

        elif i != 0:
            A_coeff_e = A_coeff_e.subs(e_[f"t-{i}"], 1)
            N_coeff_e = N_coeff_e.subs(e_[f"t-{i}"], 1)
            print(f't-{i} : {A_coeff_e} > {round(N_coeff_e, 5)}')
            final_coeffs[1].append(N_coeff_e)

    print('\n* Quasi-Convergence Factor')
    try:
        print(
            'Y :',
            sympy.tensorcontraction(
                sympy.Array(final_coeffs[0]).applyfunc(lambda x: x**2), (0, )))
        print(
            'e :',
            sympy.tensorcontraction(
                sympy.Array(final_coeffs[1]).applyfunc(lambda x: x**2), (0, )))
    except:
        pass

    _, axes = plt.subplots(5, 1, figsize=(12, 15))
    ar_params = np.array(final_coeffs[0])
    ma_params = np.array(final_coeffs[1])
    ar, ma = np.r_[1, -ar_params], np.r_[1, ma_params]
    y = smt.ArmaProcess(ar, ma).generate_sample(300, burnin=50)

    axes[0].plot(y, 'o-')
    axes[0].grid(True)

    axes[1].stem(smt.ArmaProcess(ar, ma).acf(lags=40))
    axes[1].set_xlim(-1, 41)
    axes[1].set_ylim(-1.1, 1.1)
    axes[1].set_title(
        "Theoretical autocorrelation function of an SARIMA process")
    axes[1].grid(True)

    axes[2].stem(smt.ArmaProcess(ar, ma).pacf(lags=40))
    axes[2].set_xlim(-1, 41)
    axes[2].set_ylim(-1.1, 1.1)
    axes[2].set_title(
        "Theoretical partial autocorrelation function of an SARIMA process")
    axes[2].grid(True)

    smt.graphics.plot_acf(y, lags=40, ax=axes[3])
    axes[3].set_xlim(-1, 41)
    axes[3].set_ylim(-1.1, 1.1)
    axes[3].set_title(
        "Experimental autocorrelation function of an SARIMA process")
    axes[3].grid(True)

    smt.graphics.plot_pacf(y, lags=40, ax=axes[4])
    axes[4].set_xlim(-1, 41)
    axes[4].set_ylim(-1.1, 1.1)
    axes[4].set_title(
        "Experimental partial autocorrelation function of an SARIMA process")
    axes[4].grid(True)

    plt.tight_layout()
    plt.show()
Beispiel #15
0
 def to_equation(self):
     """Returns the value returned by the node when evaluated."""
     entries_list = self.entries.tolist()
     return sympy.Array(entries_list)
Beispiel #16
0
 def g(self, x, u, p, *, s):
     """Measurement log likelihood."""
     az = s.zw*s.w + s.zq*s.q + s.zeta*s.eta
     return sympy.Array([s.w, s.q, az])
Beispiel #17
0
    (a*b, {'a': c}, b*c),
    (a*b, {'a': b, 'b': a}, a*b),
    (a*b, {'a': 1, 'b': 2}, 2),
]

elem_func_substitution_cases = [
    (a*b + sin(c), {'a': b, 'c': sympy.pi/2}, b**2 + 1),
]

sum_substitution_cases = [
    (a*b + Sum(c * k, (k, 0, n)), {'a': b, 'b': 2, 'k': 1, 'n': 2}, b*2 + c*(1 + 2)),
]

indexed_substitution_cases = [
    (a_[i]*b, {'b': 3}, a_[i]*3),
    (a_[i]*b, {'a': sympy.Array([1, 2, 3])}, sympy.Array([1, 2, 3])[i]*b),
    (sympy.Array([1, 2, 3])[i]*b, {'i': 1}, 2*b)
]

vector_valued_cases = [
    (a*b, {'a': sympy.Array([1, 2, 3])}, sympy.Array([1, 2, 3])*b),
    (a*b, {'a': sympy.Array([1, 2, 3]), 'b': sympy.Array([4, 5, 6])}, sympy.Array([4, 10, 18])),
]

full_featured_cases = [
    (Sum(a_[i], (i, 0, Len(a) - 1)), {'a': sympy.Array([1, 2, 3])}, 6),
]


##################################################### SYMPIFY ##########################################################
simple_sympify = [
Beispiel #18
0
]

sum_substitution_cases = [
    (a * b + Sum(c * k, (k, 0, n)), {
        'a': b,
        'b': 2,
        'k': 1,
        'n': 2
    }, b * 2 + c * (1 + 2)),
]

indexed_substitution_cases = [(a_[i] * b, {
    'b': 3
}, a_[i] * 3),
                              (a_[i] * b, {
                                  'a': sympy.Array([1, 2, 3])
                              }, sympy.Array([1, 2, 3])[i] * b),
                              (sympy.Array([1, 2, 3])[i] * b, {
                                  'i': 1
                              }, 2 * b)]

vector_valued_cases = [
    (a * b, {
        'a': sympy.Array([1, 2, 3])
    }, sympy.Array([1, 2, 3]) * b),
    (a * b, {
        'a': sympy.Array([1, 2, 3]),
        'b': sympy.Array([4, 5, 6])
    }, sympy.Array([4, 10, 18])),
    (a + b, {
        'a': sympy.Array([1, 2, 3])
import sympy as sp

neuronsByLayer = [4, 4, 4, 2, 1]
W = []
for k in range(len(neuronsByLayer) - 1):
    auxLis = []
    for i in range(neuronsByLayer[k]):
        for j in range(neuronsByLayer[k + 1]):
            exec('w' + str(k + 1) + str(i + 1) + str(j + 1) +
                 ' = sp.symbols("w' + str(k + 1) + str(i + 1) + str(j + 1) +
                 '")')
            exec('auxLis.append(w' + str(k + 1) + str(i + 1) + str(j + 1) +
                 ')')
    W.append(
        sp.Array(auxLis).reshape(neuronsByLayer[k], neuronsByLayer[k + 1]))
Beispiel #20
0
R[0, 1, 0, 0, 1] = rri
R[0, 1, 1, 0, 1] = rti
R[0, 1, 0, 1, 1] = rsi
R[0, 1, 1, 1, 1] = rpi

R[1, 1, 0, 0, 1] = rrj
R[1, 1, 0, 1, 1] = rtj
R[1, 1, 1, 0, 1] = rsj
R[1, 1, 1, 1, 1] = rpj

R[0, 0, :, :, :] = mi
R[0, :, :, :, 0] = mi
R[1, 0, :, :, :] = mj
R[1, :, :, :, 0] = mj

R = sp.Array(R)

# %% Benefit and Cost substitiutions
N = sp.symbols("N")
Nd = sp.symbols("N_D")
b, c = sp.symbols("b c")
f = sp.symbols("f")

bc_reward_subs = {
    rri: (N - Nd) * b - c,
    rti: (N - Nd - 1) * b,
    rsi: b - c,
    rpi: 0,
    rrj: (N - Nd) * b - c,
    rsj: (N - Nd - 1) * b - c,
    rtj: b,
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.widgets import Slider, Button
import matplotlib.animation as animation
import sympy as sp
from sympy.abc import u, v
from sympy.utilities.lambdify import lambdify

N = 300

X = (1 + v * sp.cos(u / 2)) * sp.cos(u)
Y = (1 + v * sp.cos(u / 2)) * sp.sin(u)
Z = v * sp.sin(u / 2)

sigma_sym = sp.Array([X, Y, Z])

sigma_u = lambdify((u, v), sigma_sym.diff(u), "numpy")
sigma_v = lambdify((u, v), sigma_sym.diff(v), "numpy")

f = 0.5

sigma = lambda u, v: (
    (1 + w * v / 2 * np.cos(u / f)) * np.cos(u),
    (1 + w * v / 2 * np.cos(u / f)) * np.sin(u), w * v / 2 * np.sin(u / f))


def generate_data(nbr_iterations):
    dims = (3, 1)
    start_positions = np.array(np.sigma(0, 0.5))
Beispiel #22
0
 def dX(self):
     if self.X is None:
         return None
     return sp.Array([x.dt for x in self.X])
def simplify_sympy_array(arr):
    flattened_list = _flatten_list(arr.tolist())
    simplified_flattened_list = [sympy.simplify(e) for e in flattened_list]
    return sympy.Array(simplified_flattened_list, arr.shape)
Beispiel #24
0
def getPhaseStateVector(dim):
    state = []
    for i in xrange(dim):
        state.append(sp.Symbol('x%s' % str(i + 1).zfill(2)))
    return sp.Array(state)
Beispiel #25
0
 def test_to_equation(self):
     self.assertEqual(
         pybamm.Array([1, 2]).to_equation(), sympy.Array([[1.0], [2.0]]))
Beispiel #26
0
    def __init__(
        self,
        expression: ExpressionType,
        signature: Optional[Sequence[Union[str, List[str]]]] = None,
        *,
        user_funcs: Optional[Dict[str, Callable]] = None,
        consts: Optional[Dict[str, NumberOrArray]] = None,
        explicit_symbols: Sequence[str] = None,
    ):
        """
        Warning:
            {WARNING_EXEC}

        Args:
            expression (str or float):
                The expression, which is either a number or a string that sympy
                can parse
            signature (list of str):
                The signature defines which variables are expected in the
                expression. This is typically a list of strings identifying
                the variable names. Individual names can be specified as list,
                in which case any of these names can be used. The first item in
                such a list is the definite name and if another name of the list
                is used, the associated variable is renamed to the definite
                name. If signature is `None`, all variables in `expressions`
                are allowed.
            user_funcs (dict, optional):
                A dictionary with user defined functions that can be used in the
                expression.
            consts (dict, optional):
                A dictionary with user defined constants that can be used in the
                expression. The values of these constants should either be numbers or
                :class:`~numpy.ndarray`.
            explicit_symbols (list of str):
                List of symbols that need to be interpreted as general sympy symbols
        """
        from sympy.tensor.array.ndim_array import ImmutableNDimArray

        # parse the expression
        if isinstance(expression, TensorExpression):
            # copy constructor
            sympy_expr = copy.copy(expression._sympy_expr)
            if user_funcs is None:
                user_funcs = expression.user_funcs
            else:
                user_funcs.update(expression.user_funcs)

        elif isinstance(expression, (np.ndarray, list, tuple)):
            # expression is a constant array
            sympy_expr = sympy.Array(sympy.sympify(expression))

        elif isinstance(expression, ImmutableNDimArray):
            # expression is an array of sympy expressions
            sympy_expr = expression

        else:
            # parse expression as a string
            sympy_expr_raw = parse_expr_guarded(
                str(expression),
                symbols=[signature, consts, explicit_symbols],
                functions=user_funcs,
            )
            sympy_expr = sympy.Array(sympy_expr_raw)

        super().__init__(
            expression=sympy_expr,
            signature=signature,
            user_funcs=user_funcs,
            consts=consts,
        )
Beispiel #27
0
    return sym.simplify(dv)


##================test metric derivatives (must = 0) ==============
#print('-----metric derivatives------')
#for i in range(dim):
#    for j in range(i+1):
#        for k in range(dim):
#            vd = tensor_up_derivative(gup, i, j, k)
#            if(not vd == 0):
#                print(i, j, k, vd)
##==================================================================

print("--------------vec down-------------------")
#covariant vector
vec = sym.Array([sym.sin(u[0]), sym.sin(u[1])])
for i in range(dim):
    print(vec[i])
print('-----vector derivatives------')
div = 0  #to save divergence
for i in range(dim):
    for j in range(dim):
        vd = vector_down_derivative(vec, i, j)
        if (vd != 0):
            print(i, j, vd)
            div += vd * gup[i, j]
print("divergence = " + str(div))
#print("divergence at (0, 0):"+str(div.subs(u[0],0).subs(u[1],0).evalf()))

print("--------------vec up-------------------")
#contravariant vector
Beispiel #28
0
def upscale_kernel(__method: str,  __kernel: np.ndarray, __coarse_scale: int, __fine_scale: int, __zero_padding=True,
                   P=None, R=None) -> np.ndarray:


    if P is None and R is None:
        __P = sp.Matrix(
            get_prolongation(__method, __coarse_scale, __fine_scale, __zero_padding=False, __kernel_size=len(__kernel)))
        __R = sp.Matrix(
            get_restriction(__method, __fine_scale, __coarse_scale, __zero_padding=False, __kernel_size=len(__kernel)))

    else:
        __P, __R = P, R


    # create a kernel with unknown variables
    __num_of_unknowns = len(__kernel)
    __unknowns = symbols('x0:%d' % __num_of_unknowns)
    __K_h = sp.Matrix(utils.get_toeplitz(np.array(sp.Array(__unknowns)), __fine_scale, zero_padding=True))

    __K_H = sp.Matrix(np.transpose(utils.get_toeplitz(__kernel, __coarse_scale, zero_padding=__zero_padding)))

    __B = __R * __K_h * __P

    if __method == 'linear':
        __K_H.col_del(0)
        __K_H.row_del(-1)
        __B.col_del(0)
        __B.row_del(-1)




    sp.pprint(round_expr(__K_H, 3))
    sp.pprint(round_expr(__B,3))
######################################
    # __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)

###############################################
    # define the matrix equation
    __eq = sp.Eq(__K_H, __B)

    __solution = sp.solve(__eq, __unknowns)

    __new_kernel = []

    try:
        # if there is a solution
        if __solution != []:
            i = 0
            for x in __unknowns:

                __new_kernel.append(np.float32(__solution[x]))
                i += 1
            return np.array(__new_kernel)
        else:
            print("We cannot upscale this kernel")

        __new_kernel = __solution
        return __new_kernel
    except KeyError:
        print('Not unique solution')
        return __solution
    except TypeError:
        print('Not unique solution')
        return __solution
Beispiel #29
0
 def Mvp(self, value):
     self.validation.Mvpsetter(self, value)
     if value is None:
         self._Mvp = None
     else:
         self._Mvp = sp.Array(value)
y1, y2 = sy.symbols('y_1 y_2', real=True)
v11 = sy.symbols('v_11', real=True)
v22 = sy.symbols('v_22', real=True)
x12 = 0
v12 = 0
v21 = 0
x21 = 0
v11 = 1
v22 = 1

r11 = y1 - x11
r12 = y2 - x12
r21 = y1 - x21
r22 = y2 - x22

r1 = sy.Array([r11, r12])
r2 = sy.Array([r21, r22])
rr1 = sy.Matrix([r11, r12])
rr2 = sy.Matrix([r21, r22])
v1 = sy.Matrix([v11, v12])
v2 = sy.Matrix([v21, v22])

r1r1 = sy.tensorproduct(r1, r1).tomatrix()
r2r2 = sy.tensorproduct(r2, r2).tomatrix()

G1 = 0.01 * (3 / 4) * (r1r1 / (rr1.norm()**3) + sy.eye(2) / (rr1.norm()))
G2 = 0.01 * (3 / 4) * (r2r2 / (rr2.norm()**3) + sy.eye(2) / (rr2.norm()))

u1 = G1 * v1
u2 = G2 * v2