Beispiel #1
0
 def expand_integer_powers(cls, expr):
     """
     Convert integer powers in an expression to Muls, e.g. a**3 => a*a*a.
     This is used when printing to C-style strings as it is more accurate.
     """
     if isinstance(expr, sympy.Basic):
         integer_pows = list(p for p in expr.atoms(sympy.Pow) if (
             p.as_base_exp()[1].is_Integer and abs(p.as_base_exp()[1]) > 1))
         to_replace = {}
         for int_pow in integer_pows:
             base, expn = int_pow.as_base_exp()
             repl = sympy.Mul(*([base] * abs(expn)), evaluate=False)
             if expn < 0:
                 repl = sympy.Pow(repl, -1)
             to_replace[int_pow] = repl
         if to_replace:
             expr = cls._non_eval_xreplace(expr, to_replace)
     return expr
Beispiel #2
0
    def timeconst(self):
        """Convert rational function to time constant form with unity
        lowest power of denominator.

        See also canonical, general, partfrac, standard, and ZPK"""

        N, D, delay, undef = self.as_ratfun_delay_undef()

        var = self.var
        Npoly = sym.Poly(N, var)
        Dpoly = sym.Poly(D, var)

        K = Dpoly.EC()

        D = D / K
        N = N / K
        return sym.Mul(N, sym.Pow(D, -1), evaluate=False) * sym.exp(
            self.var * delay) * undef
Beispiel #3
0
 def convert_sympy(expr):
     "converts top-level to sympy"
     leaves = expr.get_leaves()
     if isinstance(expr, Integer):
         return sympy.Integer(expr.get_int_value())
     if expr.has_form('Power', 2):
         # sympy won't expand `(a + b) / x` to `a / x + b / x` if denom is False
         # if denom is False we store negative powers to prevent this.
         n1 = leaves[1].get_int_value()
         if not denom and n1 is not None and n1 < 0:
             return store_sub_expr(expr)
         return sympy.Pow(*[convert_sympy(leaf) for leaf in leaves])
     elif expr.has_form('Times', 2, None):
         return sympy.Mul(*[convert_sympy(leaf) for leaf in leaves])
     elif expr.has_form('Plus', 2, None):
         return sympy.Add(*[convert_sympy(leaf) for leaf in leaves])
     else:
         return store_sub_expr(expr)
Beispiel #4
0
def calc(function, x0, eps):
    # firstly, check if it's polynome
    if is_polynome(function):
        return function.subs({x: x0})

    # then check if it's elementary
    if is_elementary(function):
        g = function.args[0]
        f_du = function.diff()
        _, b = estimate_abs(f_du, x0)
        u = calc(g, float(x0), eps / b)
        return calc_elem_func(function.func, u, eps)

    # at last, check top-level term
    if len(function.args) == 2:

        # f(x) = g(x) + h(x)
        if function.func == sp.Add:
            g, h = function.args

            u = calc(g, x0, eps / 2)
            v = calc(h, x0, eps / 2)

            return u + v

        # f(x) = g(x) ** k
        if function.func == sp.Pow:
            k = function.args[1]
            if isinstance(k, sp.Integer):
                g = function.args[0]
                derivative = k * sp.Pow(x, k - 1)
                b_u0, b_u1 = estimate_abs(derivative, x0)

                u = calc(g, x0, eps / b_u1)
                return u**k
            raise NotImplementedError(
                f'calculating f(x) ** {k} it too hard for me yet')

        # f(x) = g(x) * h(x)
        if function.func == sp.Mul:
            raise NotImplementedError(function.func)

        raise NotImplementedError(function.func)
Beispiel #5
0
def convert_frac(frac):
    diff_op = False
    partial_op = False
    lower_itv = frac.lower.getSourceInterval()
    lower_itv_len = lower_itv[1] - lower_itv[0] + 1
    if (frac.lower.start == frac.lower.stop
            and frac.lower.start.type == PSLexer.DIFFERENTIAL):
        wrt = get_differential_var_str(frac.lower.start.text)
        diff_op = True
    elif (lower_itv_len == 2 and frac.lower.start.type == PSLexer.SYMBOL
          and frac.lower.start.text == '\\partial'
          and (frac.lower.stop.type == PSLexer.LETTER
               or frac.lower.stop.type == PSLexer.SYMBOL)):
        partial_op = True
        wrt = frac.lower.stop.text
        if frac.lower.stop.type == PSLexer.SYMBOL:
            wrt = wrt[1:]

    if diff_op or partial_op:
        wrt = sympy.Symbol(wrt)
        if (diff_op and frac.upper.start == frac.upper.stop
                and frac.upper.start.type == PSLexer.LETTER
                and frac.upper.start.text == 'd'):
            return [wrt]
        elif (partial_op and frac.upper.start == frac.upper.stop
              and frac.upper.start.type == PSLexer.SYMBOL
              and frac.upper.start.text == '\\partial'):
            return [wrt]
        upper_text = rule2text(frac.upper)

        expr_top = None
        if diff_op and upper_text.startswith('d'):
            expr_top = process_sympy(upper_text[1:])
        elif partial_op and frac.upper.start.text == '\\partial':
            expr_top = process_sympy(upper_text[len('\\partial'):])
        if expr_top:
            return sympy.Derivative(expr_top, wrt)

    expr_top = convert_expr(frac.upper)
    expr_bot = convert_expr(frac.lower)
    return sympy.Mul(expr_top,
                     sympy.Pow(expr_bot, -1, evaluate=False),
                     evaluate=False)
    def __init__(self, given, prove):
        # Operators and modifiers of interest
        self.operators = [sympy.Mul, sympy.Add]  # , sympy.Pow]
        self.modifiers = [sympy.sin, sympy.cos]  # , sympy.exp]

        print('Proof Generator initialized...')

        # Parse into left and right expressions
        sGivenLeft, sGivenRight = given.split('=')
        self.givenLeft = parse_expr(sGivenLeft, evaluate=False)
        self.givenRight = parse_expr(sGivenRight, evaluate=False)
        print('Given: ', self.givenLeft, ' = ', self.givenRight)

        sProveLeft, sProveRight = prove.split('=')
        self.proveLeft = parse_expr(sProveLeft, evaluate=False)
        self.proveRight = parse_expr(sProveRight, evaluate=False)
        print('Prove: ', self.proveLeft, ' = ', self.proveRight)

        # Setup full set of possible symbols
        symbolsTemp = (self.givenLeft.free_symbols
                       | self.givenRight.free_symbols
                       | self.proveLeft.free_symbols
                       | self.proveRight.free_symbols)
        self.symbols = []
        self.symbols.extend(symbolsTemp)
        for m in self.modifiers:
            for s in symbolsTemp:
                self.symbols.append(m(s))

        symbolsTemp = self.symbols[:]

        for s in symbolsTemp:
            self.symbols.append(sympy.Pow(s, -1))
            self.symbols.append(sympy.Mul(
                -1,
                s,
            ))

        # Setup node handler
        self.handler = NodeHandler()
        tempDist = self.Distance(self.givenLeft, self.givenRight,
                                 self.proveLeft, self.proveRight)
        self.handler.Add(self.givenLeft, self.givenRight, tempDist, [])
Beispiel #7
0
def generate_Sa_Sb_Sn_operators(atom_list, Sp_list, Sm_list):
    """Generates Sa, Sb, Sn operators"""
    Sa_list = []
    Sb_list = []
    Sn_list = []
    N = len(atom_list)
    S = sp.Symbol('S', commutative=True)

    for i in range(N):
        Sa = ((1 / 2) * (Sp_list[i] + Sm_list[i])).expand()
        Sb = ((1 / 2) * (1 / I) * (Sp_list[i] - Sm_list[i])).expand()
        Sn = (S - sp.Pow(2 * S, -1) * Sm_list[i].expand() *
              Sp_list[i].expand()).expand()

        Sa_list.append(Sa)
        Sb_list.append(Sb)
        Sn_list.append(Sn)
    print "Operators Generated: Sa, Sb, Sn"
    return (Sa_list, Sb_list, Sn_list)
Beispiel #8
0
def _arg_func_from_proto(
    func: v2.program_pb2.ArgFunction,
    *,
    arg_function_language: str,
    required_arg_name: Optional[str] = None,
) -> Optional[ARG_RETURN_LIKE]:
    supported = SUPPORTED_FUNCTIONS_FOR_LANGUAGE.get(arg_function_language)
    if supported is None:
        raise ValueError(
            f'Unrecognized arg_function_language: {arg_function_language!r}')

    if func.type not in supported:
        raise ValueError(
            f'Unrecognized function type {func.type!r} '
            f'for arg_function_language={arg_function_language!r}')

    if func.type == 'add':
        return sympy.Add(*[
            arg_from_proto(
                a,
                arg_function_language=arg_function_language,
                required_arg_name='An addition argument',
            ) for a in func.args
        ])

    if func.type == 'mul':
        return sympy.Mul(*[
            arg_from_proto(
                a,
                arg_function_language=arg_function_language,
                required_arg_name='A multiplication argument',
            ) for a in func.args
        ])

    if func.type == 'pow':
        return sympy.Pow(*[
            arg_from_proto(
                a,
                arg_function_language=arg_function_language,
                required_arg_name='A power argument',
            ) for a in func.args
        ])
    return None
Beispiel #9
0
 def make_term_depth_three(**kwargs):
     if 'seed' in kwargs:
         seed = kwargs['seed']
     else:
         seed = random.random()
     random.seed(seed)
     out = ''
     if kwargs == {}:
         oper3 = random.choice(['prod', 'quot', 'power'])
         term1 = make_term_depth_two()
         term2 = make_term_depth_two()
     elif 'oper3' in kwargs:
         oper3 = kwargs['oper3']
     else:
         oper3 = random.choice(['prod', 'quot', 'power'])
     if 'oper1' in kwargs:
         kwargs['oper'] = kwargs['oper1']
         term1 = make_term_depth_two(**kwargs)
     else:
         term1 = make_term_depth_two(**kwargs)
     if 'oper2' in kwargs:
         kwargs['oper'] = kwargs['oper2']
         kwargs['seed'] = 1 - kwargs['seed']
         term2 = make_term_depth_two(**kwargs)
     else:
         kwargs['seed'] = 1 - kwargs['seed']
         term2 = make_term_depth_two(**kwargs)
     if oper3 == 'prod':
         out += '\\left(' + term1['fmt'] + '\\right)'
         out += '\\left(' + term2['fmt'] + '\\right)'
         term = term1['sym'] * term2['sym']
     if oper3 == 'quot':
         out += '\\frac{{{expr1}}}{{{expr2}}}'.format(
             expr1=term1['fmt'], expr2=term2['fmt'])
         term = term1['sym'] / term2['sym']
     if oper3 == 'power':
         random.seed(seed)
         power = random.randint(-5, 5)
         out += '\\left({expr}\\right)^{{{power}}}'.format(
             expr=term1['fmt'], power=power)
         term = sy.Pow(term1['sym'], power)
     return {'fmt': out, 'sym': term}
Beispiel #10
0
def convert_exp(exp):
    if hasattr(exp, 'exp'):
        exp_nested = exp.exp()
    else:
        exp_nested = exp.exp_nofunc()

    if exp_nested:
        base = convert_exp(exp_nested)
        if isinstance(base, list):
            raise LaTeXParsingError("Cannot raise derivative to power")
        if exp.atom():
            exponent = convert_atom(exp.atom())
        elif exp.expr():
            exponent = convert_expr(exp.expr())
        return sympy.Pow(base, exponent, evaluate=False)
    else:
        if hasattr(exp, 'comp'):
            return convert_comp(exp.comp())
        else:
            return convert_comp(exp.comp_nofunc())
Beispiel #11
0
def inverse_laplace_power(expr, s, t, **assumptions):

    # Handle expressions with a power of s.
    if not (expr.is_Pow and expr.args[0] == s):
        raise ValueError('Expression %s is not a power of s' % expr)
    exponent = expr.args[1]

    # Have many possible forms; the common ones are:
    # s**a, s**-a, s**(1+a), s**(1-a), s**-(1+a), s**(a-1)
    # Cannot tell if 1-a is positive.

    if exponent.is_positive:
        # Unfortunately, SymPy does not seem to support fractional
        # derivatives...
        return sym.Derivative(sym.DiracDelta(t), t, exponent, evaluate=False)

    if exponent.is_negative:
        return sym.Pow(t, -exponent - 1) / sym.Gamma(-exponent)

    raise ValueError('Cannot determine sign of exponent for %s' % expr)
def eval_default(*args):
    func, symbol = args[-2], args[-1]

    if isinstance(func, sympy.Symbol):
        func = sympy.Pow(func, 1, evaluate=False)

    # Automatically derive and apply the rule (don't use diff() directly as
    # chain rule is a separate step)
    substitutions = []
    mapping = {}
    constant_symbol = sympy.Dummy()
    for arg in func.args:
        if symbol in arg.free_symbols:
            mapping[symbol] = arg
            substitutions.append(symbol)
        else:
            mapping[constant_symbol] = arg
            substitutions.append(constant_symbol)

    rule = func.func(*substitutions).diff(symbol)
    return rule.subs(mapping)
Beispiel #13
0
def convert_mp(mp):
    if hasattr(mp, 'mp'):
        mp_left = mp.mp(0)
        mp_right = mp.mp(1)
    else:
        mp_left = mp.mp_nofunc(0)
        mp_right = mp.mp_nofunc(1)

    if mp.MUL() or mp.CMD_TIMES() or mp.CMD_CDOT():
        lh = convert_mp(mp_left)
        rh = convert_mp(mp_right)
        return sympy.Mul(lh, rh, evaluate=False)
    elif mp.DIV() or mp.CMD_DIV() or mp.COLON():
        lh = convert_mp(mp_left)
        rh = convert_mp(mp_right)
        return sympy.Mul(lh, sympy.Pow(rh, -1, evaluate=False), evaluate=False)
    else:
        if hasattr(mp, 'unary'):
            return convert_unary(mp.unary())
        else:
            return convert_unary(mp.unary_nofunc())
    def test_derivatives_wrt_t(self):
        ''' Compare the derivative w.r.t. t of the symbolic and the implemented
        Legendre Polynomials'''
        for item in range(0, 100):
            Bimpl = cBasis1000()
            tau_ = 10.0 * np.random.rand()
            s_ = np.random.rand() * 2.0 - 1.0
            ddeg = np.random.randint(1, 6)
            B = [
                Bi.diff(self.ssym_, ddeg) * sp.Pow(2 / self.tausym_, ddeg)
                for Bi in self.Bsym_
            ]
            B = [Bi.subs({self.tausym_: tau_}) for Bi in B]
            B = [sp.lambdify(self.ssym_, Bi) for Bi in B]
            B = np.array([Bi(s_) for Bi in B])

            e = np.max(np.abs(B - Bimpl.evalDerivOnWindow(s_, tau_, ddeg)))

            assert (
                e < 5.0e-3
            ), 'Large error on derivatives wrt t,    error = {:+.3e}'.format(e)
Beispiel #15
0
def pow_to_mul(expr):
    if expr.is_Atom or expr.is_Indexed:
        return expr
    elif expr.is_Pow:
        base, exp = expr.as_base_exp()
        if exp > 10 or exp < -10 or int(exp) != exp or exp == 0:
            # Large and non-integer powers remain untouched
            return expr
        elif exp == -1:
            # Reciprocals also remain untouched, but we traverse the base
            # looking for other Pows
            return expr.func(pow_to_mul(base), exp, evaluate=False)
        elif exp > 0:
            return sympy.Mul(*[base]*int(exp), evaluate=False)
        else:
            # SymPy represents 1/x as Pow(x,-1). Also, it represents
            # 2/x as Mul(2, Pow(x, -1)). So we shouldn't end up here,
            # but just in case SymPy changes its internal conventions...
            posexpr = sympy.Mul(*[base]*(-int(exp)), evaluate=False)
            return sympy.Pow(posexpr, -1, evaluate=False)
    else:
        return expr.func(*[pow_to_mul(i) for i in expr.args], evaluate=False)
Beispiel #16
0
def handle_func_normal(func):
    if func.L_PAREN():  # function called with parenthesis
        arg = convert_func_arg(func.func_arg())
    else:
        arg = convert_func_arg(func.func_arg_noparens())

    name = func.func_normal().start.text[1:]

    # change arc<trig> -> a<trig>
    if name in ["arcsin", "arccos", "arctan", "arccsc", "arcsec", "arccot", "asin", "acos", "atan"]:
        if len(name) > 4:
            name = "a" + name[3:]
        expr = getattr(sympy.functions, name)(arg, evaluate=False)
    if name in ["arsinh", "arcosh", "artanh"]:
        name = "a" + name[2:]
        expr = getattr(sympy.functions, name)(arg, evaluate=False)
    if name == 'overline':
        expr = sympy.functions.conjugate(arg, evaluate=False)
    if name == 'exp':
        expr = sympy.exp(arg, evaluate=False)

    func_pow = None
    should_pow = True
    if func.supexpr():
        if func.supexpr().expr():
            func_pow = convert_expr(func.supexpr().expr())
        else:
            func_pow = convert_atom(func.supexpr().atom())

    if name in ["sin", "cos", "tan", "csc", "sec", "cot", "sinh", "cosh", "tanh"]:
            if func_pow == -1:
                name = "a" + name
                should_pow = False
            expr = getattr(sympy.functions, name)(arg, evaluate=False)

    if func_pow and should_pow:
        expr = sympy.Pow(expr, func_pow, evaluate=False)

    return expr
Beispiel #17
0
def parse_expr(expr, local_dict=None):
    """
    Parses a json-object created with 'expr_to_json' into a Sympy expression.

    If a local_dict argument is passed, symbols with be looked up by name, and a new symbol will
    be created only if the name is not in local_dict.
    """
    if local_dict is None:
        local_dict = {}
    if expr["type"] == "Add":
        return sympy.Add._from_args([parse_expr(arg, local_dict) for arg in expr["args"]])
    elif expr["type"] == "Mul":
        return sympy.Mul._from_args([parse_expr(arg, local_dict) for arg in expr["args"]])
    elif expr["type"] == "Pow":
        return sympy.Pow(parse_expr(arg, local_dict) for arg in expr["args"])
    elif expr["type"] == "Symbol":
        try:
            return local_dict[expr["name"]]
        except KeyError:
            return sympy.Symbol(expr["name"])
    elif expr["type"] == "Number":
        return sympy.sympify(expr["value"])
    else:
        raise NotImplementedError(expr["type"] + " is not implemented")
Beispiel #18
0
def convert_exp(exp):
    if hasattr(exp, 'exp'):
        exp_nested = exp.exp()
    else:
        exp_nested = exp.exp_nofunc()

    if exp_nested:
        base = convert_exp(exp_nested)
        if isinstance(base, list):
            raise Exception("Cannot raise derivative to power")
        if exp.atom():
            if exp.atom().LETTER():  # Transpose
                if exp.atom().LETTER().getText() == 'T':
                    return sympy.Function('T')(base)
            else:
                exponent = convert_atom(exp.atom())
        elif exp.expr():
            exponent = convert_expr(exp.expr())
        return sympy.Pow(base, exponent, evaluate=False)
    else:
        if hasattr(exp, 'comp'):
            return convert_comp(exp.comp())
        else:
            return convert_comp(exp.comp_nofunc())
Beispiel #19
0
def fit_poly(x_vals, y_vals, degree, plot=False):
    """ fit a polynomial based on points list """

    x_vals = np.asarray(x_vals)
    y_vals = np.asarray(y_vals)
    coeffs = np.polyfit(x_vals, y_vals, degree)
    func = 0
    for i in range(len(coeffs)):
        if coeffs[i] < 0.0000000001:
            coeffs[i] = 0
        func = func + sp.Pow(x, degree - i) * coeffs[i]

    if plot:
        x_min = x_vals.min()
        x_max = x_vals.max()
        x_axis = np.linspace(x_min - abs(x_max - x_min),
                             x_max + abs(x_max - x_min), 100)
        y_axis = [func.subs(x, elem) for elem in x_axis]
        #print(y_axis)
        plt.plot(x_axis, y_axis)
        plt.scatter(x_vals, y_vals, color='r')
        plt.show()

    return func
def main():
    """
    main
    """
    res_t, count_t = TrailValue(func_1_expr, 1, 2, 1.0/sympy.Pow(10, 5))
    print('试值法 func 1 根: %.5f, 迭代次数: %d' % (res_t, count_t))

    res_n, count_n = Newton(func_1_expr, 1, 2, 1.0/sympy.Pow(10, 5))
    print('牛顿法 func 1 根: %.5f, 迭代次数: %d' % (res_n, count_n))

    res_t, count_t = TrailValue(func_2_expr, 2, 3, 1.0/sympy.Pow(10, 5))
    print('试值法 func 2 根: %.5f, 迭代次数: %d' % (res_t, count_t))

    res_n, count_n = Newton(func_2_expr, 2, 3, 1.0/sympy.Pow(10, 5))
    print('牛顿法 func 2 根: %.5f, 迭代次数: %d' % (res_n, count_n))

    res_t, count_t = TrailValue(func_3_expr, -2.5, -1.5, 1.0/sympy.Pow(10, 5))
    print('试值法 func 3 根: %.5f, 迭代次数: %d' % (res_t, count_t))

    res_n, count_n = Newton(func_3_expr, -2.5, -1.5, 1.0/sympy.Pow(10, 5))
    print('牛顿法 func 3 根: %.5f, 迭代次数: %d' % (res_n, count_n))
Beispiel #21
0
    def fourier_transform(self) -> sy.Expr:
        r"""
        The 2D Fourier transform of :math:`Z^m_n`.

        This function essentially implements eq. (7) of [Tatulli_2013]_.

        .. note::
            Compared to [Tatulli_2013]_, we are using a slightly
            different notation. Instead of indexing the dimensions of
            the Fourier space (or :math:`k`-space) using :math:`\kappa`
            and :math:`\alpha`, we use :math:`k_1` and :math:`k_2`.

        Returns:
            The 2D Fourier transform of :math:`Z^m_n`, that is,
            :math:`\mathcal{F}\lbrace Z^m_n \rbrace (k_1, k_2)`,
            as a `sy.Expr`.
        """

        # Define symbols for k1 and k2
        k1 = sy.Symbol('k1')
        k2 = sy.Symbol('k2')

        # Define the first factor, which only depends on n
        factor_1 = (sy.Pow(-1, self.n) * sy.sqrt(self.n + 1) / (sy.pi * k1) *
                    sy.besselj(2 * sy.pi * k1, self.n + 1))

        # Define the second factor that also depends on m
        if self.m == 0:
            factor_2 = sy.Pow(-1, self.n / 2)
        elif self.m > 0:
            factor_2 = (sy.sqrt(2) * sy.Pow(-1, (self.n - self.m) / 2) *
                        sy.Pow(sy.I, self.m) * sy.cos(self.m * k2))
        else:
            factor_2 = (sy.sqrt(2) * sy.Pow(-1, (self.n + self.m) / 2) *
                        sy.Pow(sy.I, -self.m) * sy.sin(-self.m * k2))

        return sy.nsimplify(sy.simplify(factor_1 * factor_2))
    print("Sigma = 0.5")
    stability(u, False, 0.5)

    print("Sigma = 1")
    stability(u, False, 1)
    refresh()


print("Вариант 3")
print("Уравнение вида:")
print("du/dt = (d^2u/dx^2) + (x^2 + 1) * du/dx + f(x, t)")
print("u(x,0) = phi(x), 0 <= x <= 1")
print("du/dx, (x = 0) = alpha(t), u(1,t) = beta(t), 0 <= t <= 0.1")

print("u(x, t) = x + t")
algorithm()

print("u(x,t) = 3 * x - 0.12 * t")
u_symbol = 3 * x - 0.12 * t
u = sympy.lambdify([x, t], 3 * x - 0.12 * t)
algorithm()

print("u(x,t) = x^3 + t^3")
u_symbol = sympy.Pow(x, 3) + sympy.Pow(t, 3)
u = sympy.lambdify([x, t], x * x * x + t * t * t)
algorithm()

print("u(x,t) = sin(2t + 1) + cos(2x)")
u_symbol = sympy.sin(2 * t + 1) + sympy.cos(2 * x)
u = sympy.lambdify([x, t], sympy.sin(2 * t + 1) + sympy.cos(2 * x))
algorithm()
Beispiel #23
0
def convert_func(func):
    if func.func_normal():
        if func.L_PAREN():  # function called with parenthesis
            arg = convert_func_arg(func.func_arg())
        else:
            arg = convert_func_arg(func.func_arg_noparens())

        name = func.func_normal().start.text[1:]

        # change arc<trig> -> a<trig>
        if name in [
                "arcsin", "arccos", "arctan", "arccsc", "arcsec", "arccot"
        ]:
            name = "a" + name[3:]
            expr = getattr(sympy.functions, name)(arg, evaluate=False)
        if name in ["arsinh", "arcosh", "artanh"]:
            name = "a" + name[2:]
            expr = getattr(sympy.functions, name)(arg, evaluate=False)

        if name == "exp":
            expr = sympy.exp(arg, evaluate=False)

        if (name == "log" or name == "ln"):
            if func.subexpr():
                if func.subexpr().expr():
                    base = convert_expr(func.subexpr().expr())
                else:
                    base = convert_atom(func.subexpr().atom())
            elif name == "log":
                base = 10
            elif name == "ln":
                base = sympy.E
            expr = sympy.log(arg, base, evaluate=False)

        func_pow = None
        should_pow = True
        if func.supexpr():
            if func.supexpr().expr():
                func_pow = convert_expr(func.supexpr().expr())
            else:
                func_pow = convert_atom(func.supexpr().atom())

        if name in [
                "sin", "cos", "tan", "csc", "sec", "cot", "sinh", "cosh",
                "tanh"
        ]:
            if func_pow == -1:
                name = "a" + name
                should_pow = False
            expr = getattr(sympy.functions, name)(arg, evaluate=False)

        if func_pow and should_pow:
            expr = sympy.Pow(expr, func_pow, evaluate=False)

        return expr
    elif func.LETTER() or func.SYMBOL():
        if func.LETTER():
            fname = func.LETTER().getText()
        elif func.SYMBOL():
            fname = func.SYMBOL().getText()[1:]
        fname = str(fname)  # can't be unicode
        if func.subexpr():
            subscript = None
            if func.subexpr().expr():  # subscript is expr
                subscript = convert_expr(func.subexpr().expr())
            else:  # subscript is atom
                subscript = convert_atom(func.subexpr().atom())
            subscriptName = StrPrinter().doprint(subscript)
            fname += '_{' + subscriptName + '}'
        input_args = func.args()
        output_args = []
        while input_args.args():  # handle multiple arguments to function
            output_args.append(convert_expr(input_args.expr()))
            input_args = input_args.args()
        output_args.append(convert_expr(input_args.expr()))
        return sympy.Function(fname)(*output_args)
    elif func.FUNC_INT():
        return handle_integral(func)
    elif func.FUNC_SQRT():
        expr = convert_expr(func.base)
        if func.root:
            r = convert_expr(func.root)
            return sympy.root(expr, r, evaluate=False)
        else:
            return sympy.sqrt(expr, evaluate=False)
    elif func.FUNC_OVERLINE():
        expr = convert_expr(func.base)
        return sympy.conjugate(expr, evaluate=False)
    elif func.FUNC_SUM():
        return handle_sum_or_prod(func, "summation")
    elif func.FUNC_PROD():
        return handle_sum_or_prod(func, "product")
    elif func.FUNC_LIM():
        return handle_limit(func)
Beispiel #24
0
                "help(%s)",
                no_pre_output,
                multivariate=False,
                eval_method=eval_function_docs,
                format_input_function=format_function_docs_input,
                format_output_function=format_nothing),
 'root_to_polynomial':
 ResultCard("Polynomial with this root",
            "minpoly(%s)",
            no_pre_output,
            multivariate=False),
 'matrix_inverse':
 ResultCard(
     "Inverse of matrix",
     "(%s).inv()",
     lambda statement, var, *args: sympy.Pow(statement, -1, evaluate=False),
     multivariate=False),
 'matrix_eigenvals':
 ResultCard("Eigenvalues",
            "(%s).eigenvals()",
            no_pre_output,
            multivariate=False,
            format_output_function=format_dict_title(
                "Eigenvalue", "Multiplicity")),
 'matrix_eigenvectors':
 ResultCard("Eigenvectors",
            "(%s).eigenvects()",
            no_pre_output,
            multivariate=False,
            format_output_function=format_list),
 'satisfiable':
Beispiel #25
0
 def basic_pow_term(**kwargs):
     if 'seed' in kwargs:
         seed = kwargs['seed']
     else:
         seed = random.random()
     # print('basic pow term seed', seed)
     random.seed(seed)
     if 'const_range' in kwargs:
         a, b = kwargs['const_range']
         A = random_non_zero_integer(a, b)
     else:
         A = random_non_zero_integer(-9, 9)
     if 'const_power_range' in kwargs:
         a, b = kwargs['const_power_range']
         e_const = random.randint(a, b)
     else:
         e_const = random.randint(-9, 9)
     if 'variables' in kwargs:
         variables = []
         for variable in kwargs['variables']:
             variables.append(variable)
     else:
         n = random.randint(0, 3)
         variables = []
         if n > 0:
             variables.append('x')
         if n > 1:
             variables.append('y')
         if n > 2:
             variables.append('z')
     e = []
     if 'var_power_ranges' in kwargs:
         for r in kwargs['var_power_ranges']:
             a, b = r
             e.append(random.randint(a, b))
     else:
         for var in variables:
             e.append(random.randint(-5, 5))
     fmt_out = ''
     term = 1
     if A < 0:
         parens = random.choice([True, False])
         if parens and e_const != 1:
             # print('parens:', A, e_const)
             fmt_out += pow_neg_style('\\left({A}\\right)'.format(A=A),
                                      e_const)
             term *= sy.Pow(A, e_const)
             # print('term:', term)
         else:
             fmt_out += pow_neg_style(A, e_const)
             term *= -sy.Pow(abs(A), e_const)
     elif A != 1:
         fmt_out = pow_neg_style(A, e_const)
         term *= sy.Pow(A, e_const)
     elif A == -1:
         fmt_out += '-'
         term *= -1
     i = 0
     for var in variables:
         fmt_out += pow_neg_style(var, e[i])
         term *= sy.Pow(sy.Symbol(var), e[i])
         i += 1
     return {'fmt': fmt_out, 'sym': term}
        (
            1 - sympy.Symbol("x") * sympy.Symbol("y"),
            (1, FunctionCall("mul", (Symbol("x"), Symbol("y")))),
        ),
    ],
)
def test_add_resulting_from_subtraction_is_converted_to_sub_function_call(
        sympy_addition, expected_args):
    assert expression_from_sympy(sympy_addition) == FunctionCall(
        "sub", expected_args)


@pytest.mark.parametrize(
    "sympy_power, expected_args",
    [
        (sympy.Pow(sympy.Symbol("x"), 2), (Symbol("x"), 2)),
        (sympy.Pow(2, sympy.Symbol("x")), (2, Symbol("x"))),
        (
            sympy.Pow(sympy.Symbol("x"), sympy.Symbol("y")),
            (Symbol("x"), Symbol("y")),
        ),
    ],
)
def test_sympy_pow_is_converted_to_pow_function_call(sympy_power,
                                                     expected_args):
    assert expression_from_sympy(sympy_power) == FunctionCall(
        "pow", expected_args)


@pytest.mark.parametrize(
    "sympy_power, expected_denominator",
Beispiel #27
0
    def cirq_class_resolver_dictionary(self) -> Dict[str, Type]:
        if self._crd is None:
            import cirq
            from cirq.devices.noise_model import _NoNoiseModel
            from cirq.experiments import (CrossEntropyResult,
                                          GridInteractionLayer)
            from cirq.google.devices.known_devices import (
                _NamedConstantXmonDevice)

            def _identity_operation_from_dict(qubits, **kwargs):
                return cirq.identity_each(*qubits)

            def single_qubit_matrix_gate(matrix):
                if not isinstance(matrix, np.ndarray):
                    matrix = np.array(matrix, dtype=np.complex128)
                return cirq.MatrixGate(matrix, qid_shape=(matrix.shape[0],))

            def two_qubit_matrix_gate(matrix):
                if not isinstance(matrix, np.ndarray):
                    matrix = np.array(matrix, dtype=np.complex128)
                return cirq.MatrixGate(matrix, qid_shape=(2, 2))

            self._crd = {
                'AmplitudeDampingChannel': cirq.AmplitudeDampingChannel,
                'AsymmetricDepolarizingChannel':
                cirq.AsymmetricDepolarizingChannel,
                'BitFlipChannel': cirq.BitFlipChannel,
                'CCNotPowGate': cirq.CCNotPowGate,
                'CCXPowGate': cirq.CCXPowGate,
                'CCZPowGate': cirq.CCZPowGate,
                'CNotPowGate': cirq.CNotPowGate,
                'ControlledGate': cirq.ControlledGate,
                'ControlledOperation': cirq.ControlledOperation,
                'CSwapGate': cirq.CSwapGate,
                'CXPowGate': cirq.CXPowGate,
                'CZPowGate': cirq.CZPowGate,
                'CrossEntropyResult': CrossEntropyResult,
                'Circuit': cirq.Circuit,
                'DepolarizingChannel': cirq.DepolarizingChannel,
                'ConstantQubitNoiseModel': cirq.ConstantQubitNoiseModel,
                'Duration': cirq.Duration,
                'FSimGate': cirq.FSimGate,
                'DensePauliString': cirq.DensePauliString,
                'MutableDensePauliString': cirq.MutableDensePauliString,
                'GateOperation': cirq.GateOperation,
                'GeneralizedAmplitudeDampingChannel':
                cirq.GeneralizedAmplitudeDampingChannel,
                'GlobalPhaseOperation': cirq.GlobalPhaseOperation,
                'GridInteractionLayer': GridInteractionLayer,
                'GridQid': cirq.GridQid,
                'GridQubit': cirq.GridQubit,
                'HPowGate': cirq.HPowGate,
                'ISwapPowGate': cirq.ISwapPowGate,
                'IdentityGate': cirq.IdentityGate,
                'IdentityOperation': _identity_operation_from_dict,
                'LineQubit': cirq.LineQubit,
                'LineQid': cirq.LineQid,
                'MatrixGate': cirq.MatrixGate,
                'MeasurementGate': cirq.MeasurementGate,
                'Moment': cirq.Moment,
                '_NamedConstantXmonDevice': _NamedConstantXmonDevice,
                '_NoNoiseModel': _NoNoiseModel,
                'NamedQubit': cirq.NamedQubit,
                '_PauliX': cirq.ops.pauli_gates._PauliX,
                '_PauliY': cirq.ops.pauli_gates._PauliY,
                '_PauliZ': cirq.ops.pauli_gates._PauliZ,
                'ParamResolver': cirq.ParamResolver,
                'PasqalDevice': cirq.pasqal.PasqalDevice,
                'PauliString': cirq.PauliString,
                'PhaseDampingChannel': cirq.PhaseDampingChannel,
                'PhaseFlipChannel': cirq.PhaseFlipChannel,
                'PhaseGradientGate': cirq.PhaseGradientGate,
                'PhasedISwapPowGate': cirq.PhasedISwapPowGate,
                'PhasedXPowGate': cirq.PhasedXPowGate,
                'PhasedXZGate': cirq.PhasedXZGate,
                'PhysicalZTag': cirq.google.PhysicalZTag,
                'QuantumFourierTransformGate': cirq.QuantumFourierTransformGate,
                'ResetChannel': cirq.ResetChannel,
                'SingleQubitMatrixGate': single_qubit_matrix_gate,
                'SingleQubitPauliStringGateOperation':
                cirq.SingleQubitPauliStringGateOperation,
                'SingleQubitReadoutCalibrationResult':
                cirq.experiments.SingleQubitReadoutCalibrationResult,
                'SwapPowGate': cirq.SwapPowGate,
                'SycamoreGate': cirq.google.SycamoreGate,
                'TaggedOperation': cirq.TaggedOperation,
                'ThreeDGridQubit': cirq.pasqal.ThreeDGridQubit,
                'TrialResult': cirq.TrialResult,
                'TwoQubitMatrixGate': two_qubit_matrix_gate,
                '_UnconstrainedDevice':
                cirq.devices.unconstrained_device._UnconstrainedDevice,
                'WaitGate': cirq.WaitGate,
                '_QubitAsQid': raw_types._QubitAsQid,
                'XPowGate': cirq.XPowGate,
                'XXPowGate': cirq.XXPowGate,
                'YPowGate': cirq.YPowGate,
                'YYPowGate': cirq.YYPowGate,
                'ZPowGate': cirq.ZPowGate,
                'ZZPowGate': cirq.ZZPowGate,

                # not a cirq class, but treated as one:
                'pandas.DataFrame': pd.DataFrame,
                'pandas.Index': pd.Index,
                'pandas.MultiIndex': pd.MultiIndex.from_tuples,
                'sympy.Symbol': sympy.Symbol,
                'sympy.Add': lambda args: sympy.Add(*args),
                'sympy.Mul': lambda args: sympy.Mul(*args),
                'sympy.Pow': lambda args: sympy.Pow(*args),
                'sympy.Float': lambda approx: sympy.Float(approx),
                'sympy.Integer': sympy.Integer,
                'sympy.Rational': sympy.Rational,
                'complex': complex,
            }
        return self._crd
Beispiel #28
0
 def op_divide(*args):
     if not len(args) == 2:
         raise Exception('divide given wrong number of arguments!')
     # print "divide: arg0=%s, arg1=%s" % (args[0],args[1])
     return sympy.Mul(args[0], sympy.Pow(args[1], -1))
Beispiel #29
0
def _arg_from_proto(
        arg_proto,
        *,
        arg_function_language,
        required_arg_name=None,
):
    """Extracts a python value from an argument value proto.
    Args:
        arg_proto: The proto containing a serialized value.
        arg_function_language: The `arg_function_language` field from
            `Program.Language`.
        required_arg_name: If set to `None`, the method will return `None` when
            given an unset proto value. If set to a string, the method will
            instead raise an error complaining that the value is missing in that
            situation.
    Returns:
        The deserialized value, or else None if there was no set value and
        `required_arg_name` was set to `None`.
    """
    supported = SUPPORTED_FUNCTIONS_FOR_LANGUAGE.get(arg_function_language)
    if supported is None:
        raise ValueError(f'Unrecognized arg_function_language: '
                         f'{arg_function_language!r}')

    which = arg_proto.WhichOneof('arg')
    if which == 'arg_value':
        arg_value = arg_proto.arg_value
        which_val = arg_value.WhichOneof('arg_value')
        if which_val == 'float_value' or which_val == 'double_value':
            if which_val == 'double_value':
                result = float(arg_value.double_value)
            else:
                result = float(arg_value.float_value)
            if math.ceil(result) == math.floor(result):
                result = int(result)
            return result
        if which_val == 'bool_values':
            return list(arg_value.bool_values.values)
        if which_val == 'string_value':
            return str(arg_value.string_value)
        raise ValueError(f'Unrecognized value type: {which_val!r}')

    if which == 'symbol':
        return sympy.Symbol(arg_proto.symbol)

    if which == 'func':
        func = arg_proto.func

        if func.type not in supported:
            raise ValueError(
                f'Unrecognized function type {func.type!r} '
                f'for arg_function_language={arg_function_language!r}')

        if func.type == 'add':
            return sympy.Add(*[
                _arg_from_proto(a,
                                arg_function_language=arg_function_language,
                                required_arg_name='An addition argument')
                for a in func.args
            ])

        if func.type == 'mul':
            return sympy.Mul(*[
                _arg_from_proto(a,
                                arg_function_language=arg_function_language,
                                required_arg_name='A multiplication argument')
                for a in func.args
            ])

        if func.type == 'pow':
            return sympy.Pow(*[
                _arg_from_proto(a,
                                arg_function_language=arg_function_language,
                                required_arg_name='A power argument')
                for a in func.args
            ])

    if required_arg_name is not None:
        raise ValueError(
            f'{required_arg_name} is missing or has an unrecognized '
            f'argument type (WhichOneof("arg")={which!r}).')

    return None
Beispiel #30
0
    A = np.multiply(np.subtract(1, moisture_content), np.divide(mf, rho_cs))
    B = np.divide(1, np.subtract(1, porosity))
    return np.multiply(
        B,
        np.divide(
            A,
            np.add(
                A,
                np.add(np.divide(np.subtract(1, mf), rho_solvent),
                       np.multiply(moisture_content, np.divide(mf,
                                                               rho_water))))))


sigma, sigma_star, phi, phi_m, phi_o, mu_f, beta = sy.symbols(
    'sigma sigma_star phi phi_m phi_o mu_f beta', real=True)
e_f = sy.exp(-1. * (sy.Pow((sigma_star / sigma), beta)))
e_phij = e_f * (phi_m - phi_o) + phi_o
e_mu = mu_f * sy.Pow(1 - (phi / e_phij), -2.0)
e_gd = sigma / e_mu
e_dgds = sy.diff(e_gd, sigma)
e_sigj = sigma_star / sy.Pow(-sy.log(
    (phi - phi_o) / (phi_m - phi_o)), 1. / beta)

f_f = sy.lambdify([sigma, sigma_star, beta], e_f, 'numpy')
f_phij = sy.lambdify([sigma, sigma_star, beta, phi_m, phi_o], e_phij, 'numpy')
f_mu = sy.lambdify([sigma, sigma_star, beta, phi_m, phi_o, phi, mu_f], e_mu,
                   'numpy')
f_gd = sy.lambdify([sigma, sigma_star, beta, phi_m, phi_o, phi, mu_f], e_gd,
                   'numpy')
f_dgds = sy.lambdify([sigma, sigma_star, beta, phi_m, phi_o, phi, mu_f],
                     e_dgds, 'numpy')