コード例 #1
0
    def construct_backdoor_estimand(self, estimand_type, treatment_name,
                                    outcome_name, common_causes):
        # TODO: outputs string for now, but ideally should do symbolic
        # expressions Mon 19 Feb 2018 04:54:17 PM DST
        # TODO Better support for multivariate treatments

        expr = None
        if estimand_type == "nonparametric-ate":
            outcome_name = outcome_name[0]
            num_expr_str = outcome_name
            if len(common_causes)>0:
                num_expr_str += "|" + ",".join(common_causes)
            expr = "d(" + num_expr_str + ")/d" + ",".join(treatment_name)
            sym_mu = sp.Symbol("mu")
            sym_sigma = sp.Symbol("sigma", positive=True)
            sym_outcome = spstats.Normal(num_expr_str, sym_mu, sym_sigma)
            # sym_common_causes = [sp.stats.Normal(common_cause, sym_mu, sym_sigma) for common_cause in common_causes]
            sym_treatment_symbols = [sp.Symbol(t) for t in treatment_name]
            sym_treatment = sp.Array(sym_treatment_symbols)
            sym_conditional_outcome = spstats.Expectation(sym_outcome)
            sym_effect = sp.Derivative(sym_conditional_outcome, sym_treatment)

            sym_assumptions = {
                'Unconfoundedness': (
                    u"If U\N{RIGHTWARDS ARROW}{{{0}}} and U\N{RIGHTWARDS ARROW}{1}"
                    " then P({1}|{0},{2},U) = P({1}|{0},{2})"
                ).format(",".join(treatment_name), outcome_name, ",".join(common_causes))
            }
        else:
            raise ValueError("Estimand type not supported. Supported estimand types are 'non-parametric-ate'.")

        estimand = {
            'estimand': sym_effect,
            'assumptions': sym_assumptions
        }
        return estimand
コード例 #2
0
def Hessiana(f, y):
    fr = FunctionStandard(f)

    g1 = sp.Derivative(fr, 'x1')
    g1 = g1.doit()

    H1 = sp.Derivative(g1, 'x1')
    H2 = sp.Derivative(g1, 'x2')

    H1 = H1.doit()
    H2 = H2.doit()

    H1 = H1.subs('x1', y[0])
    H1 = H1.subs('x2', y[1])

    H2 = H2.subs('x1', y[0])
    H2 = H2.subs('x2', y[1])

    g2 = sp.Derivative(fr, 'x2')
    g2 = g2.doit()

    H3 = sp.Derivative(g2, 'x1')
    H4 = sp.Derivative(g2, 'x2')

    H3 = H3.doit()
    H4 = H4.doit()

    H3 = H3.subs('x1', y[0])
    H3 = H3.subs('x2', y[1])

    H4 = H4.subs('x1', y[0])
    H4 = H4.subs('x2', y[1])

    hess = sp.Matrix([[H1, H2], [H3, H4]])

    return hess
コード例 #3
0
    # numerical integral of function
    lf = lambdify_t(f)
    tt = np.arange(dt,t+dt,dt)
    return lf(tt).sum() * dt


_gexpr = gamma_expr(5.4, 5.2) - 0.35 * gamma_expr(10.8, 7.35)
_gexpr = _gexpr / _getint(_gexpr)
_glover = lambdify_t(_gexpr)
glover = implemented_function('glover', _glover)
glovert = lambdify_t(glover(T))

# Derivative of Glover HRF

_dgexpr = _gexpr.diff(T)
dpos = sympy.Derivative((T >= 0), T)
_dgexpr = _dgexpr.subs(dpos, 0)
_dgexpr = _dgexpr / _getint(sympy_abs(_dgexpr))
_dglover = lambdify_t(_dgexpr)
dglover = implemented_function('dglover', _dglover)
dglovert = lambdify_t(dglover(T))

del(_glover); del(_gexpr); del(dpos); del(_dgexpr); del(_dglover)

# AFNI's HRF

_aexpr = ((T >= 0) * T)**8.6 * sympy.exp(-T/0.547)
_aexpr = _aexpr / _getint(_aexpr)
_afni = lambdify_t(_aexpr)
afni = implemented_function('afni', _afni)
afnit = lambdify_t(afni(T))
コード例 #4
0
ファイル: equations.py プロジェクト: divyashivaram/brian2
 def _latex(self, *args):
     varname = sympy.Symbol(self.varname)
     t = sympy.Symbol('t')
     sympy_expr = sympy.Eq(sympy.Derivative(varname, t),
                           str_to_sympy(self.expr))
     return sympy.latex(sympy_expr)
コード例 #5
0
ファイル: Exercise3.py プロジェクト: fopdf/mipt-3sem-
t = np.arange(0, 10, 0.01)
y0 = [0, np.sqrt(2)]


#Solution scipy
def func(y, t):
    return -2 * y


y_sci = odeint(func, y0, t)[:, 1]

#Solution sympy
x = sp.symbols('x')
y = sp.Function('y')
eq = sp.Eq(sp.Derivative(y(x), x), -2 * y(x))
f = sp.dsolve(eq, ics={y(0): sp.sqrt(2)})
y_sym = np.zeros(t.size)
for i in range(t.size):
    y_sym[i] = (f.rhs).subs({x: t[i]}).n()

fig, (graph, dif) = plt.subplots(1, 2, figsize=(15, 15))

fig.subplots_adjust(hspace=0.2)
graph.plot(t, y_sci, label='sympy')
graph.plot(t, y_sym, label='scipy')
graph.set(title='Решения дифференциального уравнения')
graph.legend()
graph.grid()

dif.plot(t, y_sym - y_sci)
コード例 #6
0
    print(os.getcwd())
except:
    pass

#%%
from IPython.display import display, Markdown, Math
import sympy as sp
sp.init_printing()

#%%
s_t = sp.Symbol("t")
s_i = sp.Symbol("i", integer=True)
s_z = sp.IndexedBase("z")
s_N = sp.Symbol("N", integer=True)
f_r = sp.IndexedBase(sp.Function("r")(s_t))
eq_27_1 = sp.Eq(sp.Derivative(f_r[s_i], s_t),
                (sp.Rational(1, 2) * (s_z[s_i - 1] + s_z[s_i]) * (1 - s_t)**2 +
                 s_z[s_i] * 2 * (1 - s_t) * s_t + sp.Rational(1, 2) *
                 (s_z[s_i] + s_z[s_i + 1]) * s_t**2)**2,
                evaluate=False)
display(eq_27_1)


#%%
def disabled():
    s_j = sp.Symbol("j", integer=True)
    r2 = sp.IndexedBase(sp.Function("r")(s_j / 4))
    eq_27_1_bernstein = sp.Sum(
        sp.binomial(4, s_j) * s_t**s_j * (1 - s_t)**(4 - s_j) * r2[s_i],
        (s_j, 0, 4))
    display(eq_27_1_bernstein)
コード例 #7
0
ファイル: sym.py プロジェクト: nsaura/ML
der_g = g.diff(x, y)
der_g_suc = g.diff(x, 3, y, 4)

## Utilisation
expr = x**4 + x**3 + x**2 + x + 1
# expr.diff(x)  ↦  4x**3 + 3*x**2 + 2*x + 1

### Matrix
# Jacobian
# To specify a Jacobian for optimize.fsolve to use we need to define a function that evaluates the Jacobian for a given input vector
x, y = sy.symbols("x, y")
f_mat = sy.Matrix([y - x**3 - 2 * x**2 + 1, y + x**2 - 1])
#f_mat.jacobian(sympy.Matrix([x, y]))

## Autre
d = sy.Derivative(sy.exp(sy.cos(x)), x)
ddd = d.doit()

#### Faire une figure avec un zoom
#figure = True
#if figure == True :
#    import matplotlib as mpl
#    import matplotlib.pyplot as plt
#    from mpl_toolkits.mplot3d.axes3d import Axes3D

#    fig = plt.figure(figsize=(8, 4))
#    def f(x):
#        return 1/(1 + x**2) + 0.1/(1 + ((3 - x)/0.1)**2)

#    def plot_and_format_axes(ax, x, f, fontsize):
#        ax.plot(x, f(x), linewidth=2)
コード例 #8
0
ファイル: test_aesaracode.py プロジェクト: dagidagi1/Matrix
def test_Derivative():
    simp = lambda expr: aesara_simplify(fgraph_of(expr))
    assert theq(
        simp(aesara_code_(sy.Derivative(sy.sin(x), x, evaluate=False))),
        simp(aesara.grad(aet.sin(xt), xt)))
コード例 #9
0
 def diff(self, order):
     self.k = 0
     for var in self.vars:
         self.k = self.k + sympy.Derivative(var, (var, self.order))
     return self.k
コード例 #10
0
from sympy import lambdify
from sympy.abc import a,b,c,d
import sys
t,r,theta,phi,tau = gravipy.symbols('t r \\theta \phi \\tau')
c = gravipy.Coordinates('\chi', [t, r, theta, phi])

m = 5

Metric2D = gravipy.diag(-(1-2*m/r), 1/(1-2*m/r), r**2, r**2)

g = gravipy.MetricTensor('g', c, Metric2D)

w = gravipy.Geodesic('w', g, tau)


d2t = sympy.solve(w(1),sympy.Derivative(t(tau),tau,tau))[0].subs({sympy.Derivative(t(tau),tau):a,sympy.Derivative(r(tau),tau):b,sympy.Derivative(phi(tau),tau):c,sympy.Derivative(theta(tau),tau):d})
d2r = sympy.solve(w(2),sympy.Derivative(r(tau),tau,tau))[0].subs({sympy.Derivative(t(tau),tau):a,sympy.Derivative(r(tau),tau):b,sympy.Derivative(phi(tau),tau):c,sympy.Derivative(theta(tau),tau):d})
d2theta = sympy.solve(w(3),sympy.Derivative(theta(tau),tau,tau))[0].subs({sympy.Derivative(t(tau),tau):a,sympy.Derivative(r(tau),tau):b,sympy.Derivative(phi(tau),tau):c,sympy.Derivative(theta(tau),tau):d})
d2phi = sympy.solve(w(4),sympy.Derivative(phi(tau),tau,tau))[0].subs({sympy.Derivative(t(tau),tau):a,sympy.Derivative(r(tau),tau):b,sympy.Derivative(phi(tau),tau):c,sympy.Derivative(theta(tau),tau):d})

d2tf = lambdify((a,b,c,d,t(tau),r(tau),theta(tau),phi(tau)),d2t,modules="numpy")
d2rf = lambdify((a,b,c,d,t(tau),r(tau),theta(tau),phi(tau)),d2r,modules="numpy")
d2thetaf = lambdify((a,b,c,d,t(tau),r(tau),theta(tau),phi(tau)),d2theta,modules="numpy")
d2phif = lambdify((a,b,c,d,t(tau),r(tau),theta(tau),phi(tau)),d2phi,modules="numpy")


def geo(x, tau):
    '''
    x[0] = t
    x[1] = r
    x[2] = phi
コード例 #11
0
def curvesketch(jarvis, s):
    """
    Prints useful information about a graph of a function.
    * Limit
    * Intersection x/y axis
    * Derivative and Integral
    * Minima / Maxima / Turning point
    -- Example:
        curve sketch y=x**2+10x-5
        curve sketch y=sqrt((x+1)(x-1))
        curve sketch y=1/3x**3-2x**2+3x
    """
    if len(s) == 0:
        jarvis.say(
            "Missing parameter: function (e.g. call 'curve sketch y=x**2+10x-5')")
        return

    def section(jarvis, headline):
        jarvis.say("\n{:#^50}".format(" {} ".format(headline)), Fore.MAGENTA)

    term = remove_equals(jarvis, s)
    term = format_expression(term)
    term = solve_y(term)

    def get_y(x_val, func=term):
        x = sympy.Symbol('x')
        return func.evalf(subs={x: x_val})

    section(jarvis, s)

    section(jarvis, "Graph")
    jarvis.eval('plot {}'.format(s))

    section(jarvis, "Limit")
    jarvis.eval('limit {}'.format(term))

    section(jarvis, "Intersection x-axis")
    jarvis.eval('solve {}'.format(term))

    section(jarvis, "Intersection y-axis")
    jarvis.say(str(get_y(0).round(9)), Fore.BLUE)

    section(jarvis, "Factor")
    jarvis.eval('factor {}'.format(term))

    section(jarvis, "Derivative")
    x = sympy.Symbol('x')
    derivative_1 = sympy.Derivative(term, x).doit()
    derivative_2 = sympy.Derivative(derivative_1, x).doit()
    derivative_3 = sympy.Derivative(derivative_2, x).doit()
    jarvis.say("1. Derivative: {}".format(derivative_1), Fore.BLUE)
    jarvis.say("2. Derivative: {}".format(derivative_2), Fore.BLUE)
    jarvis.say("3. Derivative: {}".format(derivative_3), Fore.BLUE)

    section(jarvis, "Integral")
    jarvis.say("F(x) = {} + t".format(sympy.Integral(term, x).doit()), Fore.BLUE)

    section(jarvis, "Maxima / Minima")
    try:
        critical_points = sympy.solve(derivative_1)
    except NotImplementedError:
        jarvis.say("Sorry, cannot solve...", Fore.RED)
        critical_points = []

    for x in critical_points:
        y = str(get_y(x).round(9))

        try:
            isminmax = float(get_y(x, func=derivative_2))
        except ValueError:
            isminmax = None
        except TypeError:
            # probably complex number
            isminmax = None

        if isminmax is None:
            minmax = "unknown"
        elif isminmax > 0:
            minmax = "Minima"
        elif isminmax < 0:
            minmax = "Maxima"
        else:
            minmax = "/"

        jarvis.say("({}/{}) : {}".format(x, y, minmax), Fore.BLUE)

    section(jarvis, "Turning Point")
    try:
        critical_points = sympy.solve(derivative_2)
    except NotImplementedError:
        jarvis.say("Sorry, cannot solve...", Fore.RED)
        critical_points = []

    for x in critical_points:
        y = get_y(x)

        try:
            is_turning_point = float(get_y(x, func=derivative_3))
        except ValueError:
            is_turning_point = -1

        if is_turning_point != 0:
            jarvis.say("({}/{})".format(x, y.round(9)), Fore.BLUE)

    section(jarvis, "")
コード例 #12
0
    def __call__(self, equations, variables=None):
        if equations.is_stochastic:
            raise UnsupportedEquationsException('Cannot solve stochastic '
                                                'equations with this state '
                                                'updater')
        if variables is None:
            variables = {}

        diff_eqs = equations.get_substituted_expressions(variables)

        t = Symbol('t', real=True, positive=True)
        dt = Symbol('dt', real=True, positive=True)
        t0 = Symbol('t0', real=True, positive=True)
        f0 = Symbol('f0', real=True)
        # TODO: Shortcut for simple linear equations? Is all this effort really
        #       worth it?

        code = []
        for name, expression in diff_eqs:
            rhs = str_to_sympy(expression.code, variables)

            # We have to be careful and use the real=True assumption as well,
            # otherwise sympy doesn't consider the symbol a match to the content
            # of the equation
            var = Symbol(name, real=True)
            f = sp.Function(name)
            rhs = rhs.subs(var, f(t))
            derivative = sp.Derivative(f(t), t)
            diff_eq = sp.Eq(derivative, rhs)
            # TODO: simplify=True sometimes fails with 0.7.4, see:
            # https://github.com/sympy/sympy/issues/2666
            try:
                general_solution = sp.dsolve(diff_eq, f(t), simplify=True)
            except RuntimeError:
                general_solution = sp.dsolve(diff_eq, f(t), simplify=False)
            # Check whether this is an explicit solution
            if not getattr(general_solution, 'lhs', None) == f(t):
                raise UnsupportedEquationsException(
                    'Cannot explicitly solve: ' + str(diff_eq))
            # Solve for C1 (assuming "var" as the initial value and "t0" as time)
            if general_solution.has(Symbol('C1')):
                if general_solution.has(Symbol('C2')):
                    raise UnsupportedEquationsException(
                        'Too many constants in solution: %s' %
                        str(general_solution))
                constant_solution = sp.solve(general_solution, Symbol('C1'))
                if len(constant_solution) != 1:
                    raise UnsupportedEquationsException(
                        ("Couldn't solve for the constant "
                         "C1 in : %s ") % str(general_solution))
                constant = constant_solution[0].subs(t, t0).subs(f(t0), var)
                solution = general_solution.rhs.subs('C1', constant)
            else:
                solution = general_solution.rhs.subs(t, t0).subs(f(t0), var)
            # Evaluate the expression for one timestep
            solution = solution.subs(t, t + dt).subs(t0, t)
            # only try symplifying it -- it sometimes raises an error
            try:
                solution = solution.simplify()
            except ValueError:
                pass

            code.append(name + ' = ' + sympy_to_str(solution))

        return '\n'.join(code)
コード例 #13
0
def test_Derivative():
    simp = lambda expr: theano_simplify(fgraph_of(expr))
    assert theq(simp(theano_code_(sy.Derivative(sy.sin(x), x, evaluate=False))),
                simp(theano.grad(tt.sin(xt), xt)))
コード例 #14
0
# 测试配置未知数符号

# from sympy import *

# var('x, y, z')
# print()

# 测试将sympy 求极限函数转换为latex语句

# from sympy import *
# x = symbols('x')
# expr = S('limit(x**2 - 6*x + 10, x, 2)')
# print(latex(expr, mode='inline'))

# 测试计算嵌套语句

# from sympy import *
# import sympy
# x = sympy.var('x')
# expr = sympy.Derivative((sympy.log((1-x)/(1+x), sympy.E)), x, 1).doit()
# print(sympy.simplify(expr))

# 测试字符串公式

import sympy
# from sympy import log, E
x = sympy.var('x')
expr = 'sympy.log((1-x)/(1+x), E)'
result = sympy.Derivative(sympy.sympify(expr), x, 1).doit()
print(sympy.simplify(result))
コード例 #15
0
ファイル: equivalent_equation.py プロジェクト: paugier/pylbm
    def __init__(self, scheme):
        # TODO: add source terms

        t, x, y, z = sp.symbols("t x y z", type='real')
        consm = list(scheme.consm.keys())
        nconsm = len(scheme.consm)

        self.consm = sp.Matrix(consm)
        self.dim = scheme.dim

        space = [x, y, z]

        LA = scheme.symb_la
        if not LA:
            LA = scheme.la

        func = []
        for i in range(nconsm):
            func.append(sp.Function('f{}'.format(i))(t, x, y, z))  #pylint: disable=not-callable
        func = sp.Matrix(func)

        sublist = [(i, j) for i, j in zip(consm, func)]
        sublist_inv = [(j, i) for i, j in zip(consm, func)]

        eq_func = sp.Matrix(scheme.EQ[nconsm:]).subs(sublist)
        s = sp.Matrix(scheme.s[nconsm:])

        all_vel = scheme.stencil.get_all_velocities()

        Lambda = []
        for i in range(all_vel.shape[1]):
            vd = LA * sp.diag(*all_vel[:, i])
            Lambda.append(scheme.M * vd * scheme.invM)

        phi1 = sp.zeros(s.shape[0], 1)  #pylint: disable=unsubscriptable-object
        sigma = sp.diag(*s).inv() - sp.eye(len(s)) / 2
        gamma_1 = sp.zeros(nconsm, 1)

        self.coeff_order1 = []
        for dim, lambda_ in enumerate(Lambda):
            A, B = sp.Matrix([lambda_[:nconsm, :nconsm]
                              ]), sp.Matrix([lambda_[:nconsm, nconsm:]])
            C, D = sp.Matrix([lambda_[nconsm:, :nconsm]
                              ]), sp.Matrix([lambda_[nconsm:, nconsm:]])

            self.coeff_order1.append(A * func + B * eq_func)
            alltogether(self.coeff_order1[-1], nsimplify=True)
            for i in range(nconsm):
                gamma_1[i] += sp.Derivative(self.coeff_order1[-1][i],
                                            space[dim])

            dummy = -C * func - D * eq_func
            alltogether(dummy, nsimplify=True)
            for i in range(dummy.shape[0]):
                phi1[i] += sp.Derivative(dummy[i], space[dim])

        self.coeff_order2 = [[sp.zeros(nconsm) for _ in range(scheme.dim)]
                             for _ in range(scheme.dim)]

        for dim, lambda_ in enumerate(Lambda):
            A, B = sp.Matrix([lambda_[:nconsm, :nconsm]
                              ]), sp.Matrix([lambda_[:nconsm, nconsm:]])

            meq = sp.Matrix(scheme.EQ[nconsm:])
            jac = meq.jacobian(consm)
            jac = jac.subs(sublist)
            delta1 = jac * gamma_1

            phi1_ = phi1 + delta1
            sphi1 = B * sigma * phi1_
            sphi1 = sphi1.doit()
            alltogether(sphi1, nsimplify=True)

            for i in range(scheme.dim):
                for jc in range(nconsm):
                    for ic in range(nconsm):
                        self.coeff_order2[dim][i][
                            ic, jc] += sphi1[ic].expand().coeff(
                                sp.Derivative(func[jc], space[i]))

        for ic, c in enumerate(self.coeff_order1):
            self.coeff_order1[ic] = c.subs(sublist_inv).doit()

        for ic, c in enumerate(self.coeff_order2):
            for jc, cc in enumerate(c):
                self.coeff_order2[ic][jc] = cc.subs(sublist_inv).doit()
コード例 #16
0
 def derivative(self):
     derivative = sympy.Derivative(self.function, self.x, self.n)
     return sympy.Eq(derivative, derivative.doit())
コード例 #17
0
def eval_derivativerule(integrand, symbol):
    # isinstance(integrand, Derivative) should be True
    if len(integrand.args) == 2:
        return integrand.args[0]
    else:
        return sympy.Derivative(integrand.args[0], *integrand.args[1:-1])
コード例 #18
0
ファイル: sympy_test.py プロジェクト: Krystelarekt/python
import sympy as sym
from sympy.matrices import Matrix

x, y = sym.symbols('x y')
expr1 = input("enter 1st function:")
sym.sympify(expr1)
expr2 = input("enter 2nd function:")
sym.sympify(expr2)
expr3 = input("enter 3rd function:")
sym.sympify(expr3)
print("1st Expression : {} ".format(expr1))
print("2nd Expression : {} ".format(expr2))
print("3rd Expression : {} ".format(expr3))

xexpr1_diff1 = sym.Derivative(expr1, x)
xexpr2_diff1 = sym.Derivative(expr2, x)
xexpr3_diff1 = sym.Derivative(expr3, x)

xexpr1_diff2 = sym.Derivative(xexpr1_diff1, x)
xexpr2_diff2 = sym.Derivative(xexpr2_diff1, x)
xexpr3_diff2 = sym.Derivative(xexpr3_diff1, x)

yexpr1_diff1 = sym.Derivative(expr1, y)
yexpr2_diff1 = sym.Derivative(expr2, y)
yexpr3_diff1 = sym.Derivative(expr3, y)

yexpr1_diff2 = sym.Derivative(yexpr1_diff1, y)
yexpr2_diff2 = sym.Derivative(yexpr2_diff1, y)
yexpr3_diff2 = sym.Derivative(yexpr3_diff1, y)

m = sym.Matrix([[expr1, expr2, expr3],
コード例 #19
0
ファイル: exact.py プロジェクト: brian-team/brian2
    def __call__(self, equations, variables=None, method_options=None):
        logger.warn(
            "The 'independent' state updater is deprecated and might be "
            "removed in future versions of Brian.",
            'deprecated_independent',
            once=True)
        extract_method_options(method_options, {})
        if equations.is_stochastic:
            raise UnsupportedEquationsException("Cannot solve stochastic "
                                                "equations with this state "
                                                "updater")
        if variables is None:
            variables = {}

        diff_eqs = equations.get_substituted_expressions(variables)

        t = Symbol('t', real=True, positive=True)
        dt = Symbol('dt', real=True, positive=True)
        t0 = Symbol('t0', real=True, positive=True)

        code = []
        for name, expression in diff_eqs:
            rhs = str_to_sympy(expression.code, variables)

            # We have to be careful and use the real=True assumption as well,
            # otherwise sympy doesn't consider the symbol a match to the content
            # of the equation
            var = Symbol(name, real=True)
            f = sp.Function(name)
            rhs = rhs.subs(var, f(t))
            derivative = sp.Derivative(f(t), t)
            diff_eq = sp.Eq(derivative, rhs)
            # TODO: simplify=True sometimes fails with 0.7.4, see:
            # https://github.com/sympy/sympy/issues/2666
            try:
                general_solution = sp.dsolve(diff_eq, f(t), simplify=True)
            except RuntimeError:
                general_solution = sp.dsolve(diff_eq, f(t), simplify=False)
            # Check whether this is an explicit solution
            if not getattr(general_solution, 'lhs', None) == f(t):
                raise UnsupportedEquationsException(
                    f"Cannot explicitly solve: {str(diff_eq)}")
            # Solve for C1 (assuming "var" as the initial value and "t0" as time)
            if general_solution.has(Symbol('C1')):
                if general_solution.has(Symbol('C2')):
                    raise UnsupportedEquationsException(
                        f'Too many constants in solution: {str(general_solution)}'
                    )
                constant_solution = sp.solve(general_solution, Symbol('C1'))
                if len(constant_solution) != 1:
                    raise UnsupportedEquationsException(
                        ("Couldn't solve for the constant "
                         "C1 in : %s ") % str(general_solution))
                constant = constant_solution[0].subs(t, t0).subs(f(t0), var)
                solution = general_solution.rhs.subs('C1', constant)
            else:
                solution = general_solution.rhs.subs(t, t0).subs(f(t0), var)
            # Evaluate the expression for one timestep
            solution = solution.subs(t, t + dt).subs(t0, t)
            # only try symplifying it -- it sometimes raises an error
            try:
                solution = solution.simplify()
            except ValueError:
                pass

            code.append(f"{name} = {sympy_to_str(solution)}")

        return '\n'.join(code)
コード例 #20
0
ファイル: dif1.py プロジェクト: Juzquiza99/MNAF_Uniovi_3
"""
Created on Mon Nov 11 12:27:52 2019


@author: UO264982
"""
import matplotlib.pyplot as plt
import sympy as S


S.init_printing(use_unicode=True)
x,y,z = S.symbols('x y z',real=True)
funcion = (x+y)**z
a = S.diff(funcion,z,3)
b = funcion.diff(x,1,y,2)
c = S.Derivative(funcion,z,3)
c.doit()


import numpy as N
import scipy.misc as SM

#Número de puntos ha de ser impar
x = S.symbols('x',real=True)
funsym = S.exp(-x**2)
funnum = S.lambdify(x,funsym,"numpy")
z= 2
solsym = funsym.diff(x,1).subs(x,z).evalf()
solnum = SM.derivative(funnum,z, dx=1e-6)
pesos = SM.central_diff_weights(3)
print(solnum,pesos)
コード例 #21
0
 def print_Function(self, rule):
     with self.new_step():
         self.append("Trivial:")
         self.append(self.format_math_display(
             sympy.Eq(sympy.Derivative(rule.context, rule.symbol),
                    diff(rule))))
コード例 #22
0
    
    derivDictMi[aDerivInt]['evalNP'] = sy.lambdify((x,y,z),derivDictMi[aDerivInt]['eval'],modules=[{'ImmutableDenseMatrix':np.matrix},'numpy'])

Mf = sy.Function('M',commutative=False)(x,y,z)
Mfi = sy.Function('Mi',commutative=False)(x,y,z)

dxMfe = sy.Function('dxM',commutative=False)
dyMfe = sy.Function('dyM',commutative=False)
dzMfe = sy.Function('dzM',commutative=False)

dydxMfe = sy.Function('dydxM',commutative=False)
dzdxMfe = sy.Function('dzdxM',commutative=False)

dzdydxMfe = sy.Function('dzdydxM',commutative=False)

subsDict1 = dict([(sy.Derivative(Mfi,ax),-(Mfi*sy.diff(Mf,ax)*Mfi)) for ax in [x,y,z]])

subsList2 = ((sy.Derivative(Mf,x,y,z),"dzdydxM"),(sy.Derivative(Mf,x,z,y),"dzdydxM"),(sy.Derivative(Mf,y,x,z),"dzdydxM"),(sy.Derivative(Mf,y,z,x),"dzdydxM"),(sy.Derivative(Mf,z,x,y),"dzdydxM"),(sy.Derivative(Mf,z,y,x),"dzdydxM"),
             (sy.Derivative(Mf,x,y),"dydxM"),(sy.Derivative(Mf,y,x),"dydxM"),
             (sy.Derivative(Mf,x,z),"dzdxM"),(sy.Derivative(Mf,z,x),"dzdxM"),
             (sy.Derivative(Mf,y,z),"dzdxM"),(sy.Derivative(Mf,z,y),"dzdyM"),
             (sy.Derivative(Mf,x),"dxM"),(sy.Derivative(Mf,y),"dyM"),(sy.Derivative(Mf,z),"dzM"),
             (Mfi,"Mi"),(Mf,"M"))

subsList2 = tuple((str(a),b) for (a,b) in subsList2)

dxMfi = sy.diff(Mfi,x)
dxMfi_s = dxMfi.subs(subsDict1)

print(dxMfi_s)
print(sy.simplify(dxMfi_s))
コード例 #23
0
def calculate_line():
    # We have a line going from s_q[s_i-1] to s_q[s_i]
    # So let's fix the endpoints
    eq_line1 = sp.Eq(f_r[s_i].subs(s_t, 0), s_q[s_i - 1])
    eq_line2 = sp.Eq(f_r[s_i].subs(s_t, 1), s_q[s_i])
    display(eq_line1)
    display(eq_line2)

    # Then the first derivative
    eq_line3 = sp.Eq(
        sp.Derivative(f_r[s_i], s_t).subs(s_t, 0), s_q[s_i] - s_q[s_i - 1])
    eq_line4 = sp.Eq(
        sp.Derivative(f_r[s_i], s_t).subs(s_t, 1), s_q[s_i] - s_q[s_i - 1])
    display(eq_line3)
    display(eq_line4)

    # Finally the second derivatives should be zero at the endpoints
    eq_line5 = sp.Eq(sp.Derivative(f_r[s_i], s_t, 2).subs(s_t, 0), 0)
    eq_line6 = sp.Eq(sp.Derivative(f_r[s_i], s_t, 2).subs(s_t, 1), 0)
    display(eq_line5)
    display(eq_line6)

    expanded_curve = eq_r_bezier.rhs.subs(s_K, 5).doit()
    expanded_curve = expanded_curve.subs(eq_p5.lhs, eq_p5.rhs)
    expanded_curve = expanded_curve.subs(eq_p4.lhs, eq_p4.rhs)
    expanded_curve = expanded_curve.subs(eq_p3.lhs, eq_p3.rhs)
    expanded_curve = expanded_curve.subs(eq_p2.lhs, eq_p2.rhs)
    expanded_curve = expanded_curve.subs(eq_p1.lhs, eq_p1.rhs)
    expanded_curve = expanded_curve.subs(eq_p0.lhs, eq_p0.rhs)
    expanded_curve = expanded_curve.simplify()
    eq_expanded_r = sp.Eq(f_r[s_i], expanded_curve)
    eq_expanded_r_d1 = sp.Eq(sp.Derivative(eq_expanded_r.lhs, s_t),
                             eq_expanded_r.rhs.diff(s_t)).simplify()
    eq_expanded_r_d2 = sp.Eq(sp.Derivative(eq_expanded_r_d1.lhs, s_t),
                             eq_expanded_r_d1.rhs.diff(s_t)).simplify()

    display(eq_expanded_r)
    display(eq_expanded_r_d1)
    display(eq_expanded_r_d2)

    eq_line1 = sp.Eq(eq_expanded_r.rhs.subs(s_t, 0), eq_line1.rhs)
    eq_line2 = sp.Eq(eq_expanded_r.rhs.subs(s_t, 1), eq_line2.rhs)
    eq_line3 = sp.Eq(eq_expanded_r_d1.rhs.subs(s_t, 0), eq_line3.rhs)
    eq_line4 = sp.Eq(eq_expanded_r_d1.rhs.subs(s_t, 1), eq_line4.rhs)
    eq_line5 = sp.Eq(eq_expanded_r_d2.rhs.subs(s_t, 0), eq_line5.rhs)
    eq_line6 = sp.Eq(eq_expanded_r_d2.rhs.subs(s_t, 1), eq_line6.rhs)

    display("eq 1", eq_line1)  # Always true
    display("eq 2", eq_line2)
    display("eq 3", eq_line3)
    display("eq 4", eq_line4)
    display("eq 5", eq_line5)
    display("eq 6", eq_line6)

    #If we arrange and simplify a bit
    eq_line7 = sp.Eq(s_w[s_i, 0]**2, sp.solve(eq_line5, s_w[s_i, 0]**2)[0])
    display("eq 7", eq_line7)

    eq_line8 = sp.Eq(s_w[s_i, 2]**2, sp.solve(eq_line6, s_w[s_i, 2]**2)[0])
    display("eq 8", eq_line8)

    #It's easy to see that
    eq_line9 = sp.Eq(sp.Eq(s_w[s_i, 0], s_w[s_i, 1]),
                     s_w[s_i, 2],
                     evaluate=False)
    display("eq 9", eq_line9)

    #So let's use substitute
    eq_p0_line = eq_p0.subs(s_w[s_i, 1], s_w[s_i,
                                             0]).subs(s_w[s_i, 2], s_w[s_i, 0])
    eq_p1_line = eq_p1.subs(s_w[s_i, 1], s_w[s_i,
                                             0]).subs(s_w[s_i, 2], s_w[s_i, 0])
    eq_p2_line = eq_p2.subs(s_w[s_i, 1], s_w[s_i,
                                             0]).subs(s_w[s_i, 2], s_w[s_i, 0])
    eq_p3_line = eq_p3.subs(s_w[s_i, 1], s_w[s_i,
                                             0]).subs(s_w[s_i, 2], s_w[s_i, 0])
    eq_p4_line = eq_p4.subs(s_w[s_i, 1], s_w[s_i,
                                             0]).subs(s_w[s_i, 2], s_w[s_i, 0])
    eq_p5_line = eq_p5.subs(s_w[s_i, 1], s_w[s_i,
                                             0]).subs(s_w[s_i, 2], s_w[s_i, 0])

    display(eq_p0_line)
    display(eq_p1_line)
    display(eq_p2_line)
    display(eq_p3_line)
    display(eq_p4_line)
    display(eq_p5_line)

    # And the final form

    eq_p0_line = eq_p0_line.subs(eq_line3.lhs, eq_line3.rhs)
    eq_p1_line = eq_p1_line.subs(eq_line3.lhs, eq_line3.rhs)
    eq_p2_line = eq_p2_line.subs(eq_line3.lhs, eq_line3.rhs)
    eq_p3_line = eq_p3_line.subs(eq_line3.lhs, eq_line3.rhs)
    eq_p4_line = eq_p4_line.subs(eq_line3.lhs, eq_line3.rhs)
    eq_p5_line = eq_p5_line.subs(eq_line3.lhs, eq_line3.rhs)

    display(eq_p0_line)
    display(eq_p1_line)
    display(eq_p2_line)
    display(eq_p3_line)
    display(eq_p4_line)
    display(eq_p5_line)

    return eq_p0_line, eq_p1_line, eq_p3_line, eq_p4_line, eq_p5_line
コード例 #24
0
ファイル: learn_advection.py プロジェクト: MiroK/sl-pde
u_exact = sp.lambdify((t, x), u_exact, 'numpy')

# All data
t_domain = np.linspace(0, T_end, n_samples)
x_domain = np.linspace(-0.5, 0.5, n_samples)
T, X = np.meshgrid(t_domain, x_domain, indexing='ij')
u_data = u_exact(T, X)

# To build the model we sample the data (in interior indices) to get
# the derivative right. For the rhs we keep it simple
u_grid = GridFunction([t_domain, x_domain], u_data)

x_grid = Coordinate([t_domain, x_domain], 1)

lhs_stream = compile_stream((sp.Derivative(u, t), ), {u: u_grid})

foos = polynomials([u], 3)
derivatives = Dx(u, 1, [3])[1:]  # Don't include 0;th
# Combine these guys
columns = [(1./sp.cos(x))*sp.Derivative(u, x)] + \
          list(foos) + \
          list(derivatives) + \
          [reduce(operator.mul, cs) for cs in itertools.product(foos, derivatives)]

rhs_stream = compile_stream(columns, {u: u_grid})

# A subset of this data is now used for training; where we can eval deriv
# safely
train_indices = map(
    tuple, np.random.choice(np.arange(5, n_samples - 5), (n_train, 2)))
コード例 #25
0
def inverse_laplace_product(expr, s, t, **assumptions):

    # Handle expressions with a function of s, e.g., V(s) * Y(s), V(s)
    # / s etc.

    if assumptions.get('causal', False):
        # Assume that all functions are causal in the expression.
        t1 = sym.S.Zero
        t2 = t
    else:
        t1 = -sym.oo
        t2 = sym.oo

    const, expr = factor_const(expr, s)

    factors = expr.as_ordered_factors()
    if len(factors) < 2:
        raise ValueError('Expression does not have multiple factors: %s' %
                         expr)

    if (len(factors) > 2 and not
        # Help s * 1 / (s + R * C) * I(s)
        isinstance(factors[1], AppliedUndef) and
        isinstance(factors[2], AppliedUndef)):
        factors = [factors[0], factors[2], factors[1]] + factors[3:]

    if isinstance(factors[1], AppliedUndef):
        # Try to expose more simple cases, e.g. (R + s * L) * V(s)
        terms = factors[0].as_ordered_terms()
        if len(terms) >= 2:
            result = sym.S.Zero
            for term in terms:
                result += inverse_laplace_product(factors[1] * term, s, t)
            return result * const

    cresult, uresult = inverse_laplace_term1(factors[0], s, t)
    result = cresult + uresult

    intnum = 0
    for m in range(len(factors) - 1):
        if m == 0 and isinstance(factors[1], AppliedUndef):
            # Note, as_ordered_factors puts powers of s before the functions.
            if factors[0] == s:
                # Handle differentiation
                # Convert s * V(s) to d v(t) / dt
                result = laplace_func(factors[1], s, t, True)
                result = sym.Derivative(result, t)
                continue
            elif factors[0].is_Pow and factors[0].args[
                    0] == s and factors[0].args[1] > 0:
                # Handle higher order differentiation
                # Convert s ** 2 * V(s) to d^2 v(t) / dt^2
                result = laplace_func(factors[1], s, t, True)
                result = sym.Derivative(result, t, factors[0].args[1])
                continue
            elif factors[0].is_Pow and factors[0].args[0] == s and factors[
                    0].args[1] == -1:
                # Handle integration  1 / s * V(s)
                tau = dummyvar(intnum, 'tau')
                intnum += 1
                result = laplace_func(factors[1], s, tau, True)
                result = sym.Integral(result, (tau, t1, t))
                continue
        # Convert product to convolution
        tau = dummyvar(intnum, 'tau')
        intnum += 1
        cresult, uresult = inverse_laplace_term1(factors[m + 1], s, t)
        expr2 = cresult + uresult
        result = sym.Integral(
            result.subs(t, t - tau) * expr2.subs(t, tau), (tau, t1, t2))

    return result * const
コード例 #26
0
ファイル: exact.py プロジェクト: divyashivaram/brian2
    def __call__(self, equations, variables=None):
        if variables is None:
            variables = {}

        if equations.is_stochastic:
            raise ValueError(
                'Cannot solve stochastic equations with this state updater')

        diff_eqs = equations.substituted_expressions

        t = Symbol('t', real=True, positive=True)
        dt = Symbol('dt', real=True, positive=True)
        t0 = Symbol('t0', real=True, positive=True)
        f0 = Symbol('f0', real=True)
        # TODO: Shortcut for simple linear equations? Is all this effort really
        #       worth it?

        code = []
        for name, expression in diff_eqs:
            rhs = expression.sympy_expr
            non_constant = _non_constant_symbols(rhs.atoms(), variables) - set(
                [name])
            if len(non_constant):
                raise ValueError(('Equation for %s referred to non-constant '
                                  'variables %s') % (name, str(non_constant)))
            # We have to be careful and use the real=True assumption as well,
            # otherwise sympy doesn't consider the symbol a match to the content
            # of the equation
            var = Symbol(name, real=True)
            f = sp.Function(name)
            rhs = rhs.subs(var, f(t))
            derivative = sp.Derivative(f(t), t)
            diff_eq = sp.Eq(derivative, rhs)
            general_solution = sp.dsolve(diff_eq, f(t))
            # Check whether this is an explicit solution
            if not getattr(general_solution, 'lhs', None) == f(t):
                raise ValueError('Cannot explicitly solve: ' + str(diff_eq))
            # Solve for C1 (assuming "var" as the initial value and "t0" as time)
            if Symbol('C1') in general_solution:
                if Symbol('C2') in general_solution:
                    raise ValueError('Too many constants in solution: %s' %
                                     str(general_solution))
                constant_solution = sp.solve(general_solution, Symbol('C1'))
                if len(constant_solution) != 1:
                    raise ValueError(("Couldn't solve for the constant "
                                      "C1 in : %s ") % str(general_solution))
                constant = constant_solution[0].subs(t, t0).subs(f(t0), var)
                solution = general_solution.rhs.subs('C1', constant)
            else:
                solution = general_solution.rhs.subs(t, t0).subs(f(t0), var)
            # Evaluate the expression for one timestep
            solution = solution.subs(t, t + dt).subs(t0, t)
            # only try symplifying it -- it sometimes raises an error
            try:
                solution = solution.simplify()
            except ValueError:
                pass

            code.append(name + ' = ' + sympy_to_str(solution))

        return '\n'.join(code)
コード例 #27
0
ファイル: test_convert.py プロジェクト: weakit/Mathics
 def testDerivative(self):
     self.compare(
         mathics.Expression('D', mathics.Symbol('Global`x'),
                            mathics.Symbol('Global`y')),
         sympy.Derivative(sympy.Symbol('_Mathics_User_Global`x'),
                          sympy.Symbol('_Mathics_User_Global`y')))
コード例 #28
0
def main(dh_params=None):
    if not dh_params:
        # TODO connect this with the GUI
        dh_params = input(
            'Please input all the DH parameters separated by commas and ; to separate rows:\n'
        )
        rows = dh_params.split(';')

        dh_params = np.zeros([len(rows), 4])
        dh_params = [[0 for j in range(4)] for i in range(len(rows))]

        #dh_params = sym.Matrix(dh_params)
        for i, row in enumerate(rows):
            cols = row.split(',')
            cols = [remove_whitespace(item) for item in cols]
            for j, col in enumerate(cols):
                try:
                    col = float(col)
                    dh_params[i][j] = col
                    #dh_params[i,j] = col

                except:
                    # recognizes that the cell isn't numerical
                    #print(col)
                    non_sympy = remove_sympy(col)
                    # need to trim whitespace, NOT remove
                    non_sympy = remove_punctuation(
                        remove_numericals(non_sympy)).strip()
                    non_sympy = non_sympy.split()
                    #lcl = locals() # TODO maybe need to define this as global to preventb
                    #lcl = globals()
                    # TODO python from confusing two 'locally' named same name variables?
                    for var in non_sympy:
                        #if not lcl.__contains__(var):
                        #    lcl[var] = sym.Symbol(var)
                        define_sympy_vars(var)
                    # at this point, all non-sympy vars have been defined, can now directly evaluate!
                    dh_params[i][j] = eval(col)
                    #dh_params[i, j] = eval(col)

        #print(dh_params)
        for item in dh_params:
            print(type(item))
        T_matrices = [dh_transformer(joint) for joint in dh_params]
        print(T_matrices[0])
        T_forward = 1
        for T in T_matrices:
            T_forward *= T
            print(T_forward)

        T_inverse = create_transformation_matrix(
            find_rotation_matrix(yaw='psi').T, ['x', 'y', 'z'])

        omegas = []
        vels = []
        omega = sym.Matrix([0, 0, 0])
        vel = sym.Matrix([0, 0, 0])
        for i, joint in enumerate(dh_params):
            alpha, a, d, theta = joint

            if theta == 0:
                pass
                # this is a prismatic joint

                #omegas.append()
                #vels.append()
            else:
                # this is revolute
                R = T_matrices[
                    0][:3, :
                       3].T  # need to transpose, because we are going in the opposite direction!
                t = sym.Symbol('t')
                # TODO does not work programmatically! Unless you can be sure of the coordinates and axes
                # and where they belong!
                # looks like you're blocked atm!
                vel = R * (vel + omega.cross())
                vels.append()

                omega = R * omega + sym.Matrix(
                    [0, 0, sym.Derivative(theta, t)])
                omegas.append(omega)

        # TODO this part does not work at all, so skipped for now!
        eqns = [
            sym.simplify(exp1 - exp2)
            for exp1, exp2 in zip(T_forward, T_inverse)
            if sym.simplify(exp1 - exp2) != 0
        ]
        vars = ['theta1', 'd2', 'theta3']

        # TODO add object oriented approach where solution first seen, then user can specify  next calculations

        # TODO not very smart!
        # TODO need to think of a smart method to do this!

        # TODO need to save var that is being saved!
        # THEN use simultaneous! SHOULD not be TOO hard!
        #print(sym.solve(eqns, (theta1, d2, theta3)))
        # rule based solver? maybe you need simultaneous equations??
        # given joint variables, needs to solve the equations?
        # maybe can isolate joint variables to find the simplest ones? starting

        # TODO need to add an input for this too, currently has no input feature!

        # TODO do this again, this is not correct! We want sympy for the definitions of the transformation matrices!
        # TODO needs to recognize: symbols, numbers, and sympy sumbols (i.e. cos or pi)
    """ Given dh parameters for a robot, calculates the forward kinematics """
コード例 #29
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)
コード例 #30
0
 def dotx(self):
     """Time derivative of state variable vector."""
     return TimeDomainMatrix([sym.Derivative(x1, t) for x1 in self.x])