def equilibrium_stability_check(equilibrium_points, input_matrix):
    s = sp.symbols('s')
    t = sp.symbols('t')
    x = deltax_deltat(s, t, input_matrix)
    y = deltay_deltat(s, t, input_matrix)

    dx_ds = sp.Lambda([s, t], sp.diff(x, s))
    dy_ds = sp.Lambda([s, t], sp.diff(y, s))
    dx_dt = sp.Lambda([s, t], sp.diff(x, t))
    dy_dt = sp.Lambda([s, t], sp.diff(y, t))

    stable_list = []
    for i in equilibrium_points:
        s = i[0]
        t = i[1]
        J00 = float(dx_ds(s, t))
        J01 = float(dx_dt(s, t))
        J10 = float(dy_ds(s, t))
        J11 = float(dy_dt(s, t))
        Jacobian_matrix = np.matrix([[J00, J01], [J10, J11]])
        print(Jacobian_matrix)
        Jacobian_eigvals, Jacobian_eigvecs = np.linalg.eig(Jacobian_matrix)
        Jacobian_real_eig = np.real(Jacobian_eigvals)
        stable = True
        for j in Jacobian_real_eig:
            if j > 0:
                stable = False
                break
        stable_list.append(stable)

    return stable_list
示例#2
0
def Rot_AngAx(n, theta):
    """
    Rotation matrix
    Rodrigues formula
    angle-axis parametrization
    INPUT: n - vector [nx,ny,nz]
           0 <= theta <= pi
    OUTPUT: Rot - matrix(3x3)
    nx,ny,nz = symbols('nx,ny,nz')
    n = [nx,ny,nz]
    """

    dimens = 3
    """
    R = sp.MatrixSymbol('R', dimens, dimens)
    """
    i, j = sp.symbols('i,j')
    R = sp.FunctionMatrix(dimens, dimens,
                          sp.Lambda((i, j),
                                    cos(theta) * KroneckerDelta(i, j)))
    for k in range(dimens):
        R -= sp.FunctionMatrix(
            dimens, dimens, sp.Lambda((i, j),
                                      sin(theta) * Eijk(i, j, k) * n[k]))

    Rot = sp.Matrix(R)

    R2 = sp.zeros(dimens)
    for i in range(dimens):
        R2.row_op(i, lambda v, j: (1 - cos(theta)) * n[i] * n[j])
    Rot += R2
    Rot = sp.N(Rot, 4)
    #Rot = sp.matrix2numpy(Rot)
    return Rot
示例#3
0
文件: sets.py 项目: o2edu/MathsExams
def transform_set(x, expr, sympy_set):
    """ Transform a sympy_set by an expression

    >>> x = sympy.Symbol('x')
    >>> domain = sympy.Interval(-sympy.pi / 4, -sympy.pi / 6, False, True) | sympy.Interval(sympy.pi / 6, sympy.pi / 4, True, False)
    >>> transform_set(x, -2 * x, domain)
    [-pi/2, -pi/3) U (pi/3, pi/2]
    """

    if isinstance(sympy_set, sympy.Union):
        return sympy.Union(
            transform_set(x, expr, arg) for arg in sympy_set.args)
    if isinstance(sympy_set, sympy.Intersection):
        return sympy.Intersection(
            transform_set(x, expr, arg) for arg in sympy_set.args)

    f = sympy.Lambda(x, expr)
    if isinstance(sympy_set, sympy.Interval):
        left, right = f(sympy_set.left), f(sympy_set.right)

        if left < right:
            new_left_open = sympy_set.left_open
            new_right_open = sympy_set.right_open
        else:
            new_left_open = sympy_set.right_open
            new_right_open = sympy_set.left_open

        return sympy.Interval(sympy.Min(left, right), sympy.Max(left, right),
                              new_left_open, new_right_open)

    if isinstance(sympy_set, sympy.FiniteSet):
        return sympy.FiniteSet(list(map(f, sympy_set)))
示例#4
0
    def make_float_function(x):
        """ Returns a sympy Function that constructs a Float.

            Args:
                x: Float

            Returns:
                sympy Function
        """
        return sy.Lambda((), x)
示例#5
0
    def exact_diff(self, xn, f):
        f = sp.Lambda(x, f)
        f1 = sp.Lambda(x, sp.diff(f(x), x))

        nxt_x = xn - (f(xn) / f1(xn))

        if nxt_x < xn:
            diff = (xn + abs(nxt_x - xn))
            if diff > 20:
                diff = 20
        else:
            diff = (xn - abs(nxt_x - xn))
            if diff < 0:
                diff = 0

        tangent = f1(xn) * diff + f(xn) - (f1(xn) * xn)

        self.l.append([nxt_x, tangent, diff, f(xn)])
        return self.l
 def _get_initial_equality(node_object):
     if isinstance(node_object, sm.MatrixSymbol):
         return sm.Eq(node_object,
                      sm.zeros(*node_object.shape),
                      evaluate=False)
     elif isinstance(node_object, sm.Symbol):
         return sm.Eq(node_object, 1.0, evaluate=False)
     elif issubclass(node_object, sm.Function):
         t = sm.symbols('t')
         return sm.Eq(node_object, sm.Lambda(t, 0.0), evaluate=False)
示例#7
0
    def diff_func(self, xn, f, dp):
        f = sp.Lambda(x, f)
        f1 = sp.Lambda(
            x, sp.differentiate_finite(f(x), x, points=[x - dp, x + dp]))

        nxt_x = xn - (f(xn) / f1(xn))

        if nxt_x < xn:
            diff = (xn + abs(nxt_x - xn))
            if diff > 20:
                diff = 20
        else:
            diff = (xn - abs(nxt_x - xn))
            if diff < 0:
                diff = 0

        b = f(xn) - f1(xn) * xn

        tangent = f1(xn) * diff + b
        func = f(xn)

        self.l.append([nxt_x, tangent, diff, func])
        #print(self.l[0])
        return self.l
示例#8
0
 def __init__(self, expr):
     # преобразования для парсера sympy
     transformations = standard_transformations + (implicit_multiplication, # умножение без знака умножения
                                                   implicit_application,  # применение скалярных ф-ий без скобок
                                                   convert_xor) # каретка как символ возведения в степень
     # замены для парсера
     replacers = {'e' : e,
                  'tg' : sympy.functions.tan,
                  'ctg' : sympy.functions.cot,
                  'lg' : sympy.Lambda(x, sympy.functions.log(x) / sympy.functions.log(10))}
     
     expr = expr.lower()
     
     self.fun = parse_expr(expr,
                           transformations = transformations,
                           local_dict=replacers)
     if self.fun.free_symbols - {x} != set():
         raise ValueError('Выражение содержит переменные кроме x')
示例#9
0
    def __init__(self, y_shift: float = 0):
        """
        This Class is representing the a dummy potential. 
        It returns a constant value equalling the y_shift parameter.
        
        :param y_shift: This will be the constant return value, defaults to 0
        :type y_shift: float, optional
        """

        self.V_orig = sp.Lambda(self.position, self.y_shift)

        self.constants = {self.y_shift: y_shift}
        self.V = self.V_orig.subs(self.constants)
        self.dVdpos = sp.diff(self.V, self.position)
        super().__init__()

        self._calculate_energies = lambda positions: np.squeeze(
            np.full(len(positions), y_shift))
        self.dVdpos = self._calculate_dVdpos = lambda positions: np.squeeze(
            np.zeros(len(positions)))
示例#10
0
    def testToCalchas(self):
        x_ = sympy.symbols('x')
        f = sympy.symbols('f', cls=sympy.Function)
        test_list = [(sympy.Symbol('a'), Id('a')), (sympy.pi, pi), (1, Int(1)),
                     (sympy.Rational(47, 10), Float(4.7)), (6, Int(6)),
                     (30, Int(30)), (15, Int(15)),
                     (f(12, 18), Call(Id('f'), [Int(12), Int(18)])),
                     ({
                         2: 1,
                         3: 2
                     }, DictFunctionExpression({
                         Int(2): Int(1),
                         Int(3): Int(2)
                     })), (18, Int(18)), (sympy.pi, pi),
                     (sympy.Lambda(x_, x_), Fun(Id('x'), Id('x')))]

        for (tree, res) in test_list:
            builder = Translator()
            calchas_tree = builder.to_calchas_tree(tree)
            self.assertEqual(calchas_tree, res)
示例#11
0
    def testToSympy(self):
        _x = sympy.symbols('x_')
        f = sympy.symbols('f', cls=sympy.Function)
        test_list = [(Id('a'), sympy.Symbol('a')),
                     (Id('pi'), sympy.Symbol('pi')), (pi, sympy.pi),
                     (Int(1), 1), (Float(4.7), sympy.Rational(47, 10)),
                     (Gcd([Int(12), Int(18)]), 6), (Sum([Int(12),
                                                         Int(18)]), 30),
                     (Sum([Int(12), Int(1), Int(2)]), 15),
                     (Call(Id('f'), [Int(12), Int(18)]), f(12, 18)),
                     (FactorInt([Int(18)]), {
                         2: 1,
                         3: 2
                     }), (Gcd([Sum([Int(18), Int(18)]),
                               Int(18)]), 18), (pi, sympy.pi),
                     (Fun(Id('x'), Id('x')), sympy.Lambda(_x, _x))]

        for (tree, res) in test_list:
            builder = Translator()
            sympy_tree = builder.to_sympy_tree(tree)
            self.assertEqual(sympy_tree, res)
示例#12
0
def _process_funcxy(args, testx, testy):
    isdy = False
    f = args.pop()

    if isinstance(
            f, (sp.Tuple, tuple, list)
    ):  # if (f1 (x, y), f2 (x, y)) functions or expressions present in args they are individual u and v functions
        c1, c2 = callable(f[0]), callable(f[1])

        if c1 and c2:  # two Lambdas
            f = __fxfy2fxy(f[0], f[1])

        elif not (c1 or c2):  # two expressions
            vars = tuple(
                sorted(sp.Tuple(f[0], f[1]).free_symbols,
                       key=lambda s: s.name))

            if len(vars) != 2:
                raise ValueError(
                    'expression must have exactly two free variables')

            return args, __fxfy2fxy(sp.Lambda(vars, f[0]),
                                    sp.Lambda(vars, f[1])), False

        else:
            raise ValueError(
                'field must be specified by two lambdas or two expressions, not a mix'
            )

    # one function or expression
    if not callable(f):  # convert expression to function
        if len(f.free_symbols) != 2:
            raise ValueError('expression must have exactly two free variables')

        f = sp.Lambda(tuple(sorted(f.free_symbols, key=lambda s: s.name)), f)

    for y in testy:  # check if returns 1 dy or 2 u and v values
        for x in testx:
            try:
                v = f(x, y)
            except (ValueError, ZeroDivisionError, FloatingPointError):
                continue

            try:
                _, _ = v
                f = __fxy2fxy(f)

                break

            except:
                f = __fdy2fxy(f)
                isdy = True

                break

        else:
            continue

        break

    return args, f, isdy
示例#13
0
def plotf(*args, fs=None, res=12, style=None, **kw):
    """Plot function(s), point(s) and / or line(s).

plotf ([+,] [limits,] *args, fs = None, res = 12, **kw)

limits  = set absolute axis bounds: (default x is (0, 1), y is automatic)
  x              -> (-x, x, y auto)
  x0, x1         -> (x0, x1, y auto)
  x, y0, y1      -> (-x, x, y0, y1)
  x0, x1, y0, y1 -> (x0, x1, y0, y1)

fs      = set figure figsize if present: (default is (6.4, 4.8))
  x      -> (x, x * 3 / 4)
  -x     -> (x, x)
  (x, y) -> (x, y)

res     = minimum target resolution points per 50 x pixels (more or less 1 figsize x unit),
          may be raised a little to align with grid
style   = optional matplotlib plot style

*args   = functions and their formatting: (func, ['fmt',] [{kw},] func, ['fmt',] [{kw},] ...)
  func                      -> callable function takes x and returns y
	(x, y)                    -> point at x, y
	(x0, y0, x1, y1, ...)     -> connected lines from x0, y1 to x1, y1 to etc...
	((x0, y0), (x1, y1), ...) -> same thing

	fmt                       = 'fmt[#color][=label]'
	"""

    if not _SPLOT:
        return None

    obj = plt
    legend = False

    args, xmin, xmax, ymin, ymax, kw = _process_head(obj,
                                                     args,
                                                     fs,
                                                     style,
                                                     ret_xrng=True,
                                                     kw=kw)

    while args:
        arg = args.pop()

        if isinstance(arg, (sp.Tuple, tuple, list)):  # list of x, y coords
            if isinstance(arg[0], (sp.Tuple, tuple, list)):
                arg = list(it.chain.from_iterable(arg))

            pargs = [arg[0::2], arg[1::2]]

        else:  # y = function (x)
            if not callable(arg):
                if len(arg.free_symbols) != 1:
                    raise ValueError(
                        'expression must have exactly one free variable')

                arg = sp.Lambda(arg.free_symbols.pop(), arg)

            win = _FIGURE.axes[-1].get_window_extent()
            xrs = (
                win.x1 - win.x0
            ) // 50  # scale resolution to roughly 'res' points every 50 pixels
            rng = res * xrs
            dx = dx2 = xmax - xmin

            while dx2 < (
                    res * xrs
            ) / 2:  # align sampling grid on integers and fractions of integers while rng stays small enough
                rng = int(rng + (dx2 - (rng % dx2)) % dx2)
                dx2 = dx2 * 2

            xs = [xmin + dx * i / rng for i in range(rng + 1)]
            ys = [None] * len(xs)

            for i in range(len(xs)):
                try:
                    ys[i] = _cast_num(arg(xs[i]))
                except (ValueError, ZeroDivisionError, FloatingPointError):
                    pass

            # remove lines crossing graph vertically due to poles (more or less)
            if ymin is not None:
                for i in range(1, len(xs)):
                    if ys[i] is not None and ys[i - 1] is not None:
                        if ys[i] < ymin and ys[i - 1] > ymax:
                            ys[i] = None
                        elif ys[i] > ymax and ys[i - 1] < ymin:
                            ys[i] = None

            pargs = [xs, ys]

        args, fargs, kwf = _process_fmt(args, kw)
        legend = legend or ('label' in kwf)

        obj.plot(*(pargs + fargs), **kwf)

    if legend or 'label' in kw:
        obj.legend()

    return _figure_to_image()
示例#14
0
'''
函数
'''
import sympy
sympy.init_printing()
from sympy import I, pi, oo

x, y, z = sympy.symbols("x, y, z")
# 创建函数符号
f = sympy.Function('f')
fx = f(x)
print(fx)
g = sympy.Function('g')(x,y,z)
print(g)
print(g.free_symbols)

# 常用函数符号
sinx = sympy.sin(x)
print(sinx)
# 函数简单计算
print(sympy.sin(1.5 * pi))

# 指定函数变量的数据类型
n = sympy.Symbol('n',integer=True)
print(sympy.sin(n * pi))

# Lambda
h = sympy.Lambda(x, x**2)
print(h)
print(h(5))
print(h(1 + x))
示例#15
0
 def _visit_fun(self, tree: FunctionExpression, *args) -> sympy.Expr:
     if isinstance(tree, FormulaFunctionExpression):
         return sympy.Lambda(self.visit(tree.var, *args),
                             self.visit(tree.expr, *args))
示例#16
0
 def __eval_bind(self):
     parser = Parser.get_instance()
     xyz = parser.get_symbols(self.__raw_args, Parser.FILTER_XYZ)
     tuv = parser.get_symbols(self.__raw_args, Parser.FILTER_TUV)
     if len(xyz) > 0 and len(tuv) > 0:
         raise ParsingError("Parsed.eval_bind",
                            "(x, y, z) and (t, u, v) shouldn't be mixed.")
     if self.__is_parametric:
         if len(self.__raw_args) == 2:
             if len(tuv) == 0:
                 raise ParsingError("Parsed.eval_bind",
                                    "Too few parametric variables.")
             elif len(tuv) < 2:
                 self.__bind(tuple(tuv), tuple(self.__raw_args),
                             PlotType.PARAMETRIC_2D)
             else:
                 raise ParsingError("Parsed.eval_bind",
                                    "Too many parametric variables.")
         elif len(self.__raw_args) == 3:
             if len(tuv) == 0:
                 raise ParsingError("Parsed.eval_bind",
                                    "Too few parametric variables.")
             elif len(tuv) < 2:
                 self.__bind(tuple(tuv), tuple(self.__raw_args),
                             PlotType.PARAMETRIC_3D)
             elif len(tuv) == 2:
                 self.__bind(tuple(tuv), tuple(self.__raw_args),
                             PlotType.PARAMETRIC_SURFACE)
             else:
                 raise ParsingError("Parsed.eval_bind",
                                    "Too many parametric variables.")
         else:
             raise ParsingError("Parsed.eval_bind",
                                "Unexpected parametric size.")
     elif len(self.__raw_args) == 1:
         arg = self.__raw_args[0]
         if len(xyz) == 0:
             self.__bind(Parser.Y, arg.evalf(), PlotType.LINE_2D)
         elif len(xyz) == 1:
             if Parser.X in xyz:
                 self.__bind(Parser.Y, arg, PlotType.LINE_2D)
             else:
                 raise ParsingError(
                     "Parsed.eval_bind",
                     "Couldn't evaluate univariate statement.")
         elif len(xyz) == 2:
             if not Parser.Z in xyz:
                 self.__bind(Parser.Z, arg, PlotType.SURFACE)
             else:
                 raise ParsingError(
                     "Parsed.eval_bind",
                     "Couldn't evaluate bivariate statement.")
     elif len(self.__raw_args) == 2:
         larg = self.__raw_args[0]
         rarg = self.__raw_args[1]
         larg_name = getattr(larg, 'name', None)
         if self.__raw_relation in Parser.LT + Parser.GT:
             if Parser.Z in xyz:
                 raise ParsingError("Parsed.eval_bind",
                                    "3D implicit plots are not supported.")
             else:
                 self.__bind(None, self.__raw_relation(larg, rarg),
                             PlotType.IMPLICIT_2D)
         elif isinstance(larg, Parser.FUNC_TYPES):
             if larg_name is None or parser.is_defined(larg_name):
                 raise ParsingError(
                     "Parsed.eval_bind",
                     "Function name already defined or reserved.")
             args = larg.args
             if any([not isinstance(a, Parser.VAR_TYPES) for a in args]):
                 raise ParsingError("Parsed.eval_bind",
                                    "Function arguments must be symbols.")
             elif len(args) != len(set(args)):
                 raise ParsingError("Parsed.eval_bind",
                                    "Duplicate parameters.")
             func = sy.Lambda(args, rarg)
             self.__bind(sy.Function(larg_name), func, None)
         elif isinstance(larg,
                         Parser.VAR_TYPES) and not parser.is_reserved(larg):
             if parser.is_defined(larg_name):
                 raise ParsingError("Parsed.eval_bind",
                                    "Variable name already defined.")
             if len(parser.get_symbols(rarg, Parser.FILTER_RESERVED)) > 0:
                 raise ParsingError("Parsed.eval_bind",
                                    "Cannot map to reserved variables.")
             self.__bind(larg, rarg, None)
         elif Parser.Z in xyz:
             sol = sy.solve(sy.Eq(larg, rarg), Parser.Z, domain=sy.S.Reals)
             if isinstance(sol, (list, tuple, Tuple)):
                 if len(sol) == 0:
                     raise ParsingError("Parsed.eval_bind", "No solutions.")
                 elif len(sol) == 1:
                     self.__bind(Parser.Z, sol[0], PlotType.SURFACE)
                 else:
                     self.__bind(Parser.Z, sol, PlotType.SURFACE)
             else:
                 self.__bind(Parser.Z, sol, PlotType.SURFACE)
         elif Parser.Y in xyz:
             sol = sy.solve(sy.Eq(larg, rarg), Parser.Y, domain=sy.S.Reals)
             if isinstance(sol, (list, tuple, Tuple)):
                 if len(sol) == 1:
                     self.__bind(Parser.Y, sol[0], PlotType.LINE_2D)
                 else:
                     self.__bind(None, sy.Eq(larg, rarg),
                                 PlotType.IMPLICIT_2D)
             else:
                 self.__bind(Parser.Y, sol, PlotType.LINE_2D)
         elif Parser.X in xyz:
             self.__bind(Parser.X,
                         parser.solve_for(Parser.X, sy.Eq(larg, rarg)),
                         None)
         else:
             self.__bind(None, sy.Eq(larg, rarg), None)
     else:
         raise ParsingError("Parsed.eval_bind",
                            "Unexpected argument structure.")
import sympy as sy

sy.init_printing()
x, y = sy.var('x, y')

# declaração de função
f = sy.Lambda(x, (x**2))
g = sy.Lambda(x, (x**3 - 3 * x + 2) * sy.exp(-x / 4) - 1)

# resultado derivada
result1 = sy.diff(f(x), x)
sy.print_rcode(result1)

# Para avaliar a derivada em um ponto, por exemplo, para calcular  f′(1) , digitamos:
result2 = sy.diff(g(x), x).subs(x, 1)
sy.print_rcode(result2)

## Reta Tangente
fl = sy.Lambda(x, sy.diff(f(x), x))

x0 = -1 / 2
r = sy.Lambda(x, fl(x0) * (x - x0) + f(x0))
r

# sy.plot(f(x), (x,-2,2))
示例#18
0
while (True):
    validando = False
    print(
        "\nInforme os dados necessarios para realizacao dos metodos iterativos, sendo ele a funcao, intervalo [a, b] e sua precisao."
    )
    print("\nExemplo:",
          "(2*ln(x**2))/(sqrt(x)-5*e^(-x))",
          "a:3",
          "b:5",
          "precisao: 0.0005\n",
          sep="\n")
    f = (input("Digite a sua funcao: "))
    f = f.replace("e", "2.718281828")
    print(f)
    f = sympy.Lambda(x, sympy.sympify(f))
    a = int(input("Digite a: "))
    b = int(input("Digite b: "))
    precisao = float(input("Digite precisao: "))

    if (teorema.bolzano(f, a, b) == False):
        print(
            "\nNao e possivel afirma a existencia de uma solucao no intervalo [{},{}], pois pois f({})*f({}) > 0."
            .format(a, b, a, b))
    else:
        print(
            "\nIntervalo contem pelo menos uma solucao, pois f({})*f({}) < 0.".
            format(a, b))
        validando = True

    if (validando == True):
示例#19
0
# coding: utf-8

#---- ch08/import
import numpy as np
from scipy.optimize import fsolve
import matplotlib.pyplot as plt
import sympy as sp

sp.init_printing()

#---- ch08/define-symbols
k1, k0, c1, c0, g, n = sp.symbols("k1 k0 c1 c0 g n")
alpha, beta, delta, theta = sp.symbols("alpha beta delta theta")

#---- ch08/production
f = sp.Lambda(k0, k0**alpha)
f(k0)

#---- ch08/dynamics-k
EK = k1 - (f(k0) - c0 + (1 - delta) * k0) / (1 + g) / (1 + n)
EK

#---- ch08/dynamics-c
EC = c1 - c0 * (beta * (f(k0).diff(k0) + 1 - delta))**(1 / theta) / (1 + g)
EC

#---- ch08/steady-state
E = sp.Matrix([EK, EC]).subs({k1: k0, c1: c0})
E

#---- ch08/parameters
示例#20
0
 def _update_namespace(self, name, vars, expr):
     self.logger.debug('Adding to namespace {!r}: {}'.format(name, expr))
     func = sp.Lambda(sp.symbols(vars), expr)
     self._sympy_ns[name] = func
示例#21
0
w = [sy.symbols("w_%d" % i) for i in range(len(x))]  # pesos

# In[10]:

q = sum([w[i] * f(x[i]) for i in range(len(x))])
q

# Para calcular valores aproximados dos pesos $w_i$, escolhemos a base polinomial
#
# $$\{ \phi_n(x) = x^n \}_{n=0}^2$$
#
# para a interpolação de $f(x)$ e um objeto simbólico para representar cada uma dessas funções.

# In[11]:

phi = [sy.Lambda(X, X**n) for n in range(len(x))]
phi

# Agora temos que descobrir os valores dos pesos. A integral $\int_a^b \phi_n(x) \, dx$ pode ser calculada analiticamente para cada função de base. Isto nos ajuda a resolver o seguinte sistema:
#
# $$\sum\limits_{i=0}^2 w_i \phi_n(x_i) = \int_a^b \phi_n(x) \, dx$$

# O sistema pode ser construído no `sympy` da seguinte forma:

# In[12]:

eqs = [
    q.subs(f, phi[n]) - sy.integrate(phi[n](X), (X, a, b))
    for n in range(len(phi))
]
eqs
示例#22
0
# Xs
C1 = sp.Symbol('C1')
C2 = sp.Symbol('C2')
C0 = sp.Symbol('C0')

# Ys
N1 = sp.Symbol('N1')
N2 = sp.Symbol('N2')

x_i = [C1, C2, C0]

y_i = [N1, N2]

# define functions
mu1 = sp.Lambda((C0, C1), mu1_max * C0 * C1 / ((K_10 + C0) * (K_11 + C1)))
mu2 = sp.Lambda((C0, C2), mu2_max * C0 * C2 / ((K_20 + C0) * (K_22 + C2)))

func_dict = {'mu1': mu1, 'mu2': mu2}

# define differential equations
dN1 = sp.sympify('N1*(mu1(C0, C1) + a_11*N1 + a_12*N2 - q)', locals=func_dict)
dN2 = sp.sympify('N2*(mu2(C0, C2) + a_21*N1 + a_22*N2 - q)', locals=func_dict)
dC1 = sp.sympify('q*(C_1i - C1) - 1/y_11 * mu1(C0, C1) * N1', locals=func_dict)
dC2 = sp.sympify('q*(C_2i - C2) - 1/y_22 * mu2(C0, C2) * N2', locals=func_dict)
dC0 = sp.sympify(
    'q*(C_0i - C0) - 1/y_10*mu1(C0, C1)*N1 - 1/y_20*mu2(C0, C2)*N2',
    locals=func_dict)

equs = [dN1, dN2, dC1, dC2, dC0]
示例#23
0
def test_prob():
    def emit(name, iname, cdf, args, no_small=False):
        V = []
        for arg in sorted(args):
            y = cdf(*arg)
            if isinstance(y, mpf):
                e = sp.nsimplify(y, rational=True)
                if e.is_Rational and e.q <= 1000 and \
                        mp.almosteq(mp.mpf(e), y, 1e-25):
                    y = e
            else:
                y = N(y)
            V.append(arg + (y, ))
        for v in V:
            if name:
                test(name, *v)
        for v in V:
            if iname and (not no_small or 1 / 1000 <= v[-1] <= 999 / 1000):
                test(iname, *(v[:-2] + v[:-3:-1]))

    x = sp.Symbol("x")
    emit("ncdf", "nicdf", sp.Lambda(x,
                                    st.cdf(st.Normal("X", 0, 1))(x)),
         zip(exparg))
    # using cdf() for anything more complex is too slow

    df = FiniteSet(1, S(3) / 2, 2, S(5) / 2, 5, 25)
    emit("c2cdf",
         "c2icdf",
         lambda k, x: sp.lowergamma(k / 2, x / 2) / sp.gamma(k / 2),
         ProductSet(df, posarg),
         no_small=True)

    dfint = df & sp.fancysets.Naturals()

    def cdf(k, x):
        k, x = map(mpf, (k, x))
        return .5 + .5 * mp.sign(x) * mp.betainc(
            k / 2, .5, x1=1 / (1 + x**2 / k), regularized=True)

    emit("stcdf", "sticdf", cdf, ProductSet(dfint, exparg))

    def cdf(d1, d2, x):
        d1, d2, x = map(mpf, (d1, d2, x))
        return mp.betainc(d1 / 2,
                          d2 / 2,
                          x2=x / (x + d2 / d1),
                          regularized=True)

    emit("fcdf", "ficdf", cdf, ProductSet(dfint, dfint, posarg))

    kth = ProductSet(sp.ImageSet(lambda x: x / 5, df), posarg - FiniteSet(0))
    emit("gcdf",
         "gicdf",
         lambda k, th, x: sp.lowergamma(k, x / th) / sp.gamma(k),
         ProductSet(kth, posarg),
         no_small=True)

    karg = FiniteSet(0, 1, 2, 5, 10, 15, 40)
    knparg = [(k, n, p)
              for k, n, p in ProductSet(karg, karg, posarg
                                        & Interval(0, 1, True, True))
              if k <= n and n > 0]

    def cdf(k, n, p):
        return st.P(st.Binomial("X", n, p) <= k)

    emit("bncdf", "bnicdf", cdf, knparg, no_small=True)

    def cdf(k, lamda):
        return sp.uppergamma(k + 1, lamda) / sp.gamma(k + 1)

    emit("pscdf",
         "psicdf",
         cdf,
         ProductSet(karg, posarg + karg - FiniteSet(0)),
         no_small=True)

    x, i = sp.symbols("x i")

    def smcdf(n, e):
        return 1 - sp.Sum(
            sp.binomial(n, i) * e * (e + i / n)**(i - 1) *
            (1 - e - i / n)**(n - i), (i, 0, sp.floor(n * (1 - e)))).doit()

    kcdf = sp.Lambda(
        x,
        sp.sqrt(2 * pi) / x *
        sp.Sum(sp.exp(-pi**2 / 8 * (2 * i - 1)**2 / x**2), (i, 1, oo)))
    smarg = ProductSet(karg - FiniteSet(0),
                       posarg & Interval(0, 1, True, True))
    karg = FiniteSet(S(1) / 100,
                     S(1) / 10) + (posarg & Interval(S(1) / 4, oo, True))

    for n, e in sorted(smarg):
        test("smcdf", n, e, N(smcdf(n, e)))
    prec("1e-10")
    for x in sorted(karg):
        test("kcdf", x, N(kcdf(x)))
    prec("1e-9")
    for n, e in sorted(smarg):
        p = smcdf(n, e)
        if p < S(9) / 10:
            test("smicdf", n, N(p), e)
    prec("1e-6")
    for x in sorted(karg):
        p = kcdf(x)
        if N(p) > S(10)**-8:
            test("kicdf", N(p), x)
示例#24
0
from itertools import cycle, repeat, count, imap
from math import sin, cos
from constraint_solver import pywrapcp as cp


x, y, z, r, s, t  = sym.symbols('x y z r s t')
m, n, i, j, k     = sym.symbols('m n i j k', integer=True)
f, g, h           = sym.symbols('f g h', cls=sym.Function)

solver = cp.Solver('Counterpoint')

# <codecell>

# motive definition

shk    = sym.Lambda((x, y), x + y) #schenkerian

size= 6

motif_xp =  [(shk, 0), (shk, 3), (shk, 5), (shk, -1)]
rhythm_xp = [(shk, 0), (shk, 3), (shk, 5), (shk, -1)]

# Same Motif for notes and rhythms for a Fractal Result

motif1  = [(shk, 0), (shk, 3), (shk, 0), (shk, 1), (shk, 0), (shk, 3), (shk, 5), (shk, -1), (shk, 0), (shk, -1), (shk, 5), (shk, -1)] * size
rhythm1 = [(shk, 0), (shk, 3), (shk, 0), (shk, 1), (shk, 0), (shk, 3), (shk, 5), (shk, -1), (shk, 0), (shk, -1), (shk, 5), (shk, -1)] * size

motif2  = [(shk, 0), (shk, 1), (shk, 0), (shk, 3), (shk, 5), (shk, -1), (shk, 0), (shk, -1)] * size
rhythm2 = [(shk, 0), (shk, 1), (shk, 0), (shk, 3), (shk, 5), (shk, -1), (shk, 0), (shk, -1)] * size

motif3  = [(shk, 0), (shk, 3), (shk, 5), (shk, -1)] * size
示例#25
0
文件: sym.py 项目: nsaura/ML
## Functions
x, y, z = sy.symbols("x, y, z")
#>>> symbols('x:10')
#    (x0, x1, x2, x3, x4, x5, x6, x7, x8, x9)
#>>> symbols('x(:c)')
#    (xa, xb, xc)
#>>> symbols('f,g,h', cls=Function)
#    (f, g, h)

f = sy.Function('f')(x)
g = sy.Function("g")(x, y, z)
g.free_symbols  #returns a set of unique symbols contained in a given expression
#l = sy.Function("l")(x)
#m = sy.function("m")(l)

h = sy.Lambda(x, x**2)
# h:            x   ↦   x²
# h(5) = 25
# h(1+x):       x   ↦   (x+1)²
# h(sy.sin(x))  x   ↦   sin²(x)

## Expressions
expr = 1 + 2 * x + 2 * x**2
# expr = 2x² + 2x + 1
print expr.args  # (1, 2*x, 2*x**2)
print expr.args[1].args[1]  # x
print expr.args[-1].args[1]  # x**2

#### Voir Numerical Python Robert Johansson books

polr = sy.apart(1 / (x**2 + 3 * x + 2),
    x = deltax_deltat(t, input_matrix)
    # The variable coeffs_list stores the coefficients of the polynomial of
    # variable x.
    coeffs_list = sp.poly(x)
    # This command is to ensure that all roots of x are included in variable
    # coeffs_list.
    coeffs_list = coeffs_list.all_coeffs()
    # The variable roots_list stores the roots of polynomial of x.
    roots_list = np.roots(coeffs_list)

    # The second step is to evaluate the stability of the equilibrium point by
    # evaluating the first derivative of the function.

    # This assigns dx_dt as a function of the first derivative of x with
    # respect to t.
    dx_dt = sp.Lambda([t], sp.diff(x))
    # This list stores the stability of the equilibrium in roots_list, in the
    # order of the latter list.
    stable_list = []
    for i in roots_list:
        if dx_dt(i) > 0:  # If the first derivative of x at i is positive
            # The equilibrium point is unstable, hence append 0.
            stable_list.append(0)
        # Else if the first derivative of x at i is negative
        elif dx_dt(i) < 0:
            stable_list.append(1)  # The equilibrium is stable, hence append 1.

    # The final step is to plot the equilibrium points using pyplot library,
    # along with the function x.

    # This sets t as a set of values between 0 and 1.
示例#27
0
import sympy as sy

##from sympy.printing import print_rcode
##from sympy.functions import sin, cos, Abs, sqrt
##from sympy import Lambda
## from sympy.abc import x

sy.init_printing()

## criando variavel simbolica
x = sy.var('x')

## definindo uma função
f = sy.Lambda(x, 2 - sy.sqrt(x**2 - 1))

## f de 1
sy.print_rcode(f(1))

## imprimindo o grafico da função f
sy.plot(f(x))


示例#28
0
import sympy as sy

sy.init_printing()

x, y = sy.var('x y')

## declaração de função
f = sy.Lambda(x, (x**3 - 3 * x + 2) * sy.exp(x / 4) - 1)

## limite da função com f(x), com o x tendendo a 1
ponto = 1
limit = sy.limit(f(x), x, ponto)

## print limit
sy.print_rcode(limit)

## limites laterais
z = sy.var('z')
g = sy.Lambda(z, (abs(z)) / z)

limiteDireita = sy.limit(g(z), z, 0, '+')
esquerda = sy.limit(g(z), z, 0, '-')

sy.print_rcode(limiteDireita)
sy.print_rcode(esquerda)

## limites ao infinito
## limit(f(x), x, oo)