Esempio n. 1
0
def getPoly(order, sym=sympy.symbols('x')):
    roots = random_integers(-5, 5, order)
    leadCoeff = random_integers(1, 5)
    poly = sympy.S(leadCoeff)
    for root in roots:
        poly *= sym - root
    return sympy.Poly(poly.expand())
Esempio n. 2
0
def check_gramian(env, src, tgt, hyp):
    # Read src
    try:
        degree, pos = env.parse_int(src)
        nx = src[
            pos:
        ]  # retourne src sans le degree et le séparateur qui va avec si j'ai bien suivi
        system = []
        while len(nx) > 0:
            b, nx = env.prefix_to_infix(nx[1:])
            # convertit en sympy, on en aura besoin de toutes facons
            s = sp.S(b)
            system.append(s)

        # get expected shape of solution (from tgt)
        nr_lines = tgt.count(env.line_separator)
        nr_cols = tgt.count(env.list_separator)
        if nr_cols % nr_lines != 0 or nr_cols // nr_lines != degree:
            logger.error("Incorrect target gramian in check_gramian")
            return False
        nr_cols = nr_cols // nr_lines

        for i in range(degree):
            valA, valB = env.compute_gradient_control(
                system[i], env.eval_point, degree, nr_lines
            )
            if i == 0:
                A = valA
                B = valB
            else:
                A = np.vstack((A, valA))
                B = np.vstack((B, valB))

        A = A / np.linalg.norm(A)
        B = B / np.linalg.norm(A)

        # read hyp, check correct shape
        h = hyp
        K0 = np.zeros((nr_lines, nr_cols))
        for i in range(nr_lines):
            for j in range(nr_cols):
                val, pos = env.parse_float(h)
                if np.isnan(val):
                    return False
                if len(h) <= pos or h[pos] != env.list_separator:
                    return False
                K0[i][j] = val
                h = h[pos + 1 :]
            if len(h) == 0 or h[0] != env.line_separator:
                return False
            h = h[1:]

        V = A + B @ K0
        return max(np.linalg.eigvals(V).real) < 0

    except TimeoutError:
        return False
    except Exception as e:
        logger.info(f"{e} in check_gramian")
        return False
Esempio n. 3
0
def upsample(input: {'field_type': pystencils.field.FieldType.CUSTOM}, result,
             factor):

    ndim = input.spatial_dimensions
    here = pystencils.x_vector(ndim)

    assignments = AssignmentCollection({
        result.center:
        pystencils.astnodes.ConditionalFieldAccess(
            input.absolute_access(
                tuple(
                    cast_func(sympy.S(1) / factor * h, create_type('int64'))
                    for h in here), ()),
            sympy.Or(*[s % cast_func(factor, 'int64') > 0 for s in here]))
    })

    def create_autodiff(self, constant_fields=None, **kwargs):
        backward_assignments = downsample(AdjointField(result),
                                          AdjointField(input), factor)
        self._autodiff = pystencils.autodiff.AutoDiffOp(
            assignments,
            "",
            backward_assignments=backward_assignments,
            **kwargs)

    assignments._create_autodiff = types.MethodType(create_autodiff,
                                                    assignments)
    return assignments
Esempio n. 4
0
        def calculator(pool, var_node):
            """
            Symbolically sums the expression of the node.
            :return: a lambda expression that substitutes the given lower- and upper bound in the sum
            """
            variable, node_id = var_node
            expression = pool.get_node(node_id).expression
            variables = {str(v): v for v in expression.free_symbols}

            if len(variables) == 0:
                return lambda lb, ub: (ub - lb + 1) * float(expression)

            v = variables[variable] if variable in variables else sympy.S(
                variable)
            # TODO add caching again
            # TODO Deferred, only numeric / one call => directly
            try:
                expression = sympy.expand(expression)
                # print("Value at r=10 is {}".format(expression.subs({"r": 10})))
                result = sympy.Sum(expression, (v, self.lb, self.ub)).doit()
                # print("Symbolic sum of {} = {}".format(expression, result))
                return lambda lb, ub: result.subs({self.lb: lb, self.ub: ub})
            except sympy.BasePolynomialError as e:
                print(
                    "Problem trying to sum the expression {} for variable {}".
                    format(expression, v))
                raise e
Esempio n. 5
0
def check_expression(expr, var_symbols):
    """Does eval(expr) both in Sage and SymPy and does other checks."""

    # evaluate the expression in the context of Sage:
    sage.var(var_symbols)
    a = globals().copy()
    # safety checks...
    assert not "sin" in a
    a.update(sage.__dict__)
    assert "sin" in a
    e_sage = eval(expr, a)
    assert not isinstance(e_sage, sympy.Basic)

    # evaluate the expression in the context of SymPy:
    if var_symbols:
        sympy.var(var_symbols)
    b = globals().copy()
    assert not "sin" in b
    b.update(sympy.__dict__)
    assert "sin" in b
    b.update(sympy.__dict__)
    e_sympy = eval(expr, b)
    assert isinstance(e_sympy, sympy.Basic)

    # Do the actual checks:
    assert sympy.S(e_sage) == e_sympy
    assert e_sage == sage.SR(e_sympy)
Esempio n. 6
0
def setup_mms(eps=None):
    '''Simple MMS problem for UnitSquareMesh'''
    from common import as_expression
    import sympy as sp

    x, y = sp.symbols('x[0] x[1]')

    sigma = sp.Matrix([
        sp.sin(sp.pi * x * (1 - x) * y * (1 - y)),
        sp.sin(2 * sp.pi * x * (1 - x) * y * (1 - y))
    ])

    sp_div = lambda f: f[0].diff(x, 1) + f[1].diff(y, 1)

    sp_grad = lambda f: sp.Matrix([f.diff(x, 1), f.diff(y, 1)])

    f = -sp_grad(sp_div(sigma)) + sigma
    g = sp.S(0)

    sigma_exact = as_expression(sigma)
    # It's quite interesting that you get surface divergence as the extra var
    p_exact = as_expression(sp_div(-sigma))
    f_rhs, g_rhs = map(as_expression, (f, g))

    return (sigma_exact, p_exact), (f_rhs, g_rhs)
Esempio n. 7
0
def command(args):
    from decimal import Decimal as D
    import sympy
    import sys

    import sr.tools.budget as budget

    try:
        root = budget.find_root()
    except budget.NotBudgetRepo:
        print("Error: Please run in budget.git", file=sys.stderr)
        exit(1)

    t = budget.load_budget(root)

    config = None

    # find the first BudgetItem to get its config
    for i in t.walk():
        if isinstance(i, budget.BudgetItem):
            config = i.conf
            break

    assert config is not None

    r = sympy.S(args.expression)
    r = D("%.2f" % r.evalf(subs=config.vars))

    print(r)
Esempio n. 8
0
    def test_get_factorial_term(self):
        """
        Given the tuples of integers a and b,
        Then, the "factorial term" should be exactly "a_result" and "b_result", respectively

        :return:
        """

        a = (2, 3, 4)
        b = (0, 1, 6)
        a_expected = sp.S(1) / (sp.factorial(2) * sp.factorial(3) * sp.factorial(4))
        b_expected = sp.S(1) / (sp.factorial(6))
        a_result = get_one_over_n_factorial(a)
        b_result = get_one_over_n_factorial(b)
        self.assertEqual(a_expected, a_result)
        self.assertEqual(b_expected, b_result)
Esempio n. 9
0
    def __add_component(
            self, pam, component
    ):  # Assume components of type numpy.ndarray or sympy.Matrix

        if not isinstance(component, np.ndarray):
            component = np.array(component)

        if component.dtype == np.dtype(object):
            try:
                S = np.vectorize(lambda x: complex(x))
                S(component)
            except:
                return self.__add_components(
                    self.__extract_components(component, pam=pam))

        if self.exact:
            S = np.vectorize(lambda x: sympy.S(x))
        else:
            S = np.vectorize(lambda x: complex(x))
        component = S(component)

        if self.__shape is None:
            self.__shape = component.shape
        elif component.shape != self.__shape:
            raise ValueError(
                "Different components of the same Operator object report different shape."
            )

        if pam in self.components:
            self.components[pam] += component
        else:
            self.components[pam] = component
Esempio n. 10
0
def main():
    t, kf, P0, t0, excess_C, limiting_C, eps_l, beta = sympy.symbols(
        't k_f P0 t0 Y Z epsilon beta', negative=False)
    for f in funcs:
        args = t, kf, P0, t0, excess_C, limiting_C, eps_l
        kwargs = {'exp': sympy.exp}
        if f in (pseudo_rev, binary_rev):
            args += (beta, )
        if f is binary_rev:
            kwargs['one'] = sympy.S(1)
        expr = f(*args, **kwargs)
        with open(f.__name__ + '.png', 'wb') as ofh:
            sympy.printing.preview(expr,
                                   output='png',
                                   filename='out.png',
                                   viewer='BytesIO',
                                   outputbuffer=ofh)
        with open(f.__name__ + '_diff.png', 'wb') as ofh:
            sympy.printing.preview(expr.diff(t).subs({
                t0: 0
            }).simplify(),
                                   output='png',
                                   filename='out.png',
                                   viewer='BytesIO',
                                   outputbuffer=ofh)
Esempio n. 11
0
def test_special_printers():
    class IntervalPrinter(LambdaPrinter):
        """Use ``lambda`` printer but print numbers as ``mpi`` intervals. """
        def _print_Integer(self, expr):
            return "mpi('%s')" % super(IntervalPrinter,
                                       self)._print_Integer(expr)

        def _print_Rational(self, expr):
            return "mpi('%s')" % super(IntervalPrinter,
                                       self)._print_Rational(expr)

    def intervalrepr(expr):
        return IntervalPrinter().doprint(expr)

    expr = sympy.sqrt(sympy.sqrt(2) + sympy.sqrt(3)) + sympy.S(1) / 2

    func0 = lambdify((), expr, modules="mpmath", printer=intervalrepr)
    func1 = lambdify((), expr, modules="mpmath", printer=IntervalPrinter)
    func2 = lambdify((), expr, modules="mpmath", printer=IntervalPrinter())

    mpi = type(mpmath.mpi(1, 2))

    assert isinstance(func0(), mpi)
    assert isinstance(func1(), mpi)
    assert isinstance(func2(), mpi)
def ab5_coefficients(l1, m1, l2, m2, p, symbolic=False):
    """a5 and b5 are the coefficients used in the evaluation of the SVWF translation
    operator. Their computation is based on the sympy.physics.wigner package and is performed with symbolic numbers.

    Args:
        l1 (int):           l=1,...: Original wave's SVWF multipole degree
        m1 (int):           m=-l,...,l: Original wave's SVWF multipole order
        l2 (int):           l=1,...: Partial wave's SVWF multipole degree
        m2 (int):           m=-l,...,l: Partial wave's SVWF multipole order
        p (int):            p parameter
        symbolic (bool):    If True, symbolic numbers are returned. Otherwise, complex.

    Returns:
        A tuple (a5, b5) where a5 and b5 are symbolic or complex.
    """
    jfac = sympy.I**(abs(m1 - m2) - abs(m1) - abs(m2) + l2 - l1 +
                     p) * (-1)**(m1 - m2)
    fac1 = sympy.sqrt((2 * l1 + 1) * (2 * l2 + 1) /
                      sympy.S(2 * l1 * (l1 + 1) * l2 * (l2 + 1)))
    fac2a = (l1 * (l1 + 1) + l2 * (l2 + 1) - p *
             (p + 1)) * sympy.sqrt(2 * p + 1)
    fac2b = sympy.sqrt((l1 + l2 + 1 + p) * (l1 + l2 + 1 - p) * (p + l1 - l2) *
                       (p - l1 + l2) * (2 * p + 1))
    wig1 = sympy.physics.wigner.wigner_3j(l1, l2, p, m1, -m2, -(m1 - m2))
    wig2a = sympy.physics.wigner.wigner_3j(l1, l2, p, 0, 0, 0)
    wig2b = sympy.physics.wigner.wigner_3j(l1, l2, p - 1, 0, 0, 0)

    if symbolic:
        a = jfac * fac1 * fac2a * wig1 * wig2a
        b = jfac * fac1 * fac2b * wig1 * wig2b
    else:
        a = complex(jfac * fac1 * fac2a * wig1 * wig2a)
        b = complex(jfac * fac1 * fac2b * wig1 * wig2b)
    return a, b
Esempio n. 13
0
    def sympy_parse(line, local_ns, *args, **kwargs):
        import sympy

        try:
            return sympy.S(line, *args, **kwargs)
        except ValueError as err:
            if ":=" in line:
                name, expr = line.split(":=")
                result = sympy_parse(expr, local_ns, *args, **kwargs)
                local_ns[name.strip()] = result
                return result
            elif "=" in line:
                return sympy.S("Eq(" + ",".join(line.split("=")) + ")", *args,
                               **kwargs)
            else:
                raise err
Esempio n. 14
0
    def propagate(self, source, dists, c_matrix):
        propagation = [None] * (max(source.keys()) + 1)

        execution_order = hoplite_utils.get_execution_order(source)

        for elem in execution_order:
            if source[elem]['op'] == 'input':
                propagation[elem] = dists[self.input_rvars[elem]]
            if source[elem]['op'] == 'const':
                propagation[elem] = {
                    sympy.S(1.0): float(source[elem]['value'])
                }
            if source[elem]['op'] == 'output':
                propagation[elem] = propagation[source[elem]['preds'][0]]
            if source[elem]['op'] == 'add':
                propagation[elem] = pce_ops.add(
                    propagation[source[elem]['preds'][0]],
                    propagation[source[elem]['preds'][1]])
            if source[elem]['op'] == 'sub':
                propagation[elem] = pce_ops.sub(
                    propagation[source[elem]['preds'][0]],
                    propagation[source[elem]['preds'][1]])
            if source[elem]['op'] == 'mul':
                propagation[elem] = pce_ops.mul(
                    propagation[source[elem]['preds'][0]],
                    propagation[source[elem]['preds'][1]], c_matrix)
            if source[elem]['op'] == 'noise':
                propagation[elem] = pce_ops.add(
                    propagation[source[elem]['preds'][0]],
                    self.noise_dists[source[elem]['symbol']])

        return propagation
Esempio n. 15
0
    def _pce_const(self, node_id):
        """ Generate the PCE format of a constant.
        """
        node = self._systemgraph.node(node_id)

        # Returns the value of the node.
        return {sympy.S(1.0): node['value']}
Esempio n. 16
0
    def insert_node(self, operation, name=None, value=None):
        """ Introduces a new node of the indicated operation in the system graph. If the
        operation is a constant, the insertion additionally requires a value to be specified.
        Any value passed to the insertion for non-constant operation will be ignored.
        """
        self.debug('systemgraph.insert_node start')

        # Request a new unique ID for the node to generate
        node_id = self.node_id

        # Check that the operation to insert is supported by the graph
        if not operation in SUPPORTED_OPERATIONS:
            self.warning('Operation type not supported, defaults to %s',
                         SUPPORTED_OPERATIONS[0])
            operation = SUPPORTED_OPERATIONS[0]

        # Generate the dictionary that represents the node.
        # Contents of the dictionary are:
        # +===================+===============+==================================================+
        # | Field             | Type          | Comments                                         |
        # +===================+===============+==================================================+
        # | type              | String        | -                                                |
        # +-------------------+---------------+--------------------------------------------------+
        # | id                | Integer       | Unique for each node in the graph.               |
        # +-------------------+---------------+--------------------------------------------------+
        # | value             | sympy.S       | Only present for 'const' nodes.                  |
        # +-------------------+---------------+--------------------------------------------------+
        # | predecessors      | List(Integer) | Not present for 'const' or 'input' nodes.        |
        # |                   |               | Number and interpretation of the elements in the |
        # |                   |               | list are dependent on each type of node.         |
        # +-------------------+---------------+--------------------------------------------------+
        # | successors        | List(Integer) | Not present for 'output' nodes.                  |
        # +===================+===============+==================================================+
        node = {
            'type': operation,
            'id': node_id,
            'name':
            name if not name is None else '%s.%s' % (operation, node_id)
        }
        if operation not in ['input', 'const']:
            node['predecessors'] = []
        if operation not in ['output']:
            node['successors'] = []
        if operation in ['const']:
            # Transform the value of the constant to the internal sympy representation.
            # While doing this, we check that the value argument is provided and it is valid.
            try:
                node['name'] = str(float(value))
                node['value'] = sympy.S(float(value))
            except ValueError:
                self.fatal(
                    'systemgraph.insert_node() argument cannot be converted to float'
                )
            except TypeError:
                self.fatal(
                    'systemgraph.insert_node() argument is null or of an invalid type'
                )
            except Exception, message:
                self.fatal('systemgraph.insert_node() %s', message)
Esempio n. 17
0
 def cross(A,B):
     dum=Vec('dum','MC')
     dum.set_E(sp.S(0))
     x= A.vec[2]*B.vec[3]-A.vec[3]*B.vec[2]
     y=-A.vec[1]*B.vec[3]+A.vec[3]*B.vec[1]
     z= A.vec[1]*B.vec[2]-A.vec[2]*B.vec[1]
     dum.vec[1:]=[x,y,z]
     return dum
Esempio n. 18
0
def check_term(term, pows):
    """ Check that no k_i part of term has a power greater than
        that in pows. """
    assert isinstance(term, sympy.Mul), "Term not of type Mul"
    # check each part of the term
    for part in term.args:
        sym = None
        if isinstance(part, sympy.Pow):
            sym = part.args[0]
            power = part.args[1]
        elif isinstance(part, sympy.Symbol):
            sym = part
            power = sympy.S(1)
        if 'k_' in str(sym):
            if int(power) > pows[int(str(sym).split('k_')[1])]:
                return sympy.S(0)
    return term
Esempio n. 19
0
def test_conv9b():
    x = Symbol("x")
    y = Symbol("y")
    assert sympify(sympy.I) == I
    assert sympify(2*sympy.I+3) == 2*I+3
    assert sympify(2*sympy.I/5+sympy.S(3)/5) == 2*I/5+Integer(3)/5
    assert sympify(sympy.Symbol("x")*sympy.I + 3) == x*I+3
    assert sympify(sympy.Symbol("x") + sympy.I*sympy.Symbol("y")) == x+I*y
Esempio n. 20
0
def test_conv9():
    x = Symbol("x")
    y = Symbol("y")
    assert (I)._sympy_() == sympy.I
    assert (2*I+3)._sympy_() == 2*sympy.I+3
    assert (2*I/5+Integer(3)/5)._sympy_() == 2*sympy.I/5+sympy.S(3)/5
    assert (x*I+3)._sympy_() == sympy.Symbol("x")*sympy.I + 3
    assert (x+I*y)._sympy_() == sympy.Symbol("x") + sympy.I*sympy.Symbol("y")
Esempio n. 21
0
def Cross(A,
          B,
          X=[sympy.symbols('x'),
             sympy.symbols('y'),
             sympy.symbols('z')],
          coordinate='Cartesian',
          metric=[[sympy.S(1), 0, 0], [0, sympy.S(1), 0], [0, 0,
                                                           sympy.S(1)]],
          evaluation=0):
    '''
    Calculate cross product in general curvilinear coordinates (orthogonal or non-orthogonal).
    [email protected] 2020.06.17    
    '''
    if (coordinate == 'Cartesian') or (coordinate == 'Cylinder') or (
            coordinate == 'Sphere') or (coordinate == 'Toroidal'):
        metric = Metric(X=X, coordinate=coordinate, contra=1)
    else:
        print('Coordinate: ' + coordinate +
              ' is used, you should be explictly given at input !')
        metric = metric

    J = Jacobian(metric)
    H = Lame(metric)
    # get the covariant metric tensor with matrix inverse
    g_co = metric.inv(method='GE')

    # get the normalized cotravariant component of vector fields A and B
    A1 = g_co[0, 0] * A[0] / H[0] + g_co[0, 1] * A[1] / H[1] + g_co[
        0, 2] * A[2] / H[2]
    A2 = g_co[1, 0] * A[0] / H[0] + g_co[1, 1] * A[1] / H[1] + g_co[
        1, 2] * A[2] / H[2]
    A3 = g_co[2, 0] * A[0] / H[0] + g_co[2, 1] * A[1] / H[1] + g_co[
        2, 2] * A[2] / H[2]
    B1 = g_co[0, 0] * B[0] / H[0] + g_co[0, 1] * B[1] / H[1] + g_co[
        0, 2] * B[2] / H[2]
    B2 = g_co[1, 0] * B[0] / H[0] + g_co[1, 1] * B[1] / H[1] + g_co[
        1, 2] * B[2] / H[2]
    B3 = g_co[2, 0] * B[0] / H[0] + g_co[2, 1] * B[1] / H[1] + g_co[
        2, 2] * B[2] / H[2]

    D1 = J**-1 * H[0] * (A2 * B3 - A3 * B2)
    D2 = -J**-1 * H[1] * (A1 * B3 - A3 * B1)
    D3 = J**-1 * H[2] * (A1 * B2 - A2 * B1)
    D = [D1, D2, D3]

    return D
Esempio n. 22
0
File: cone.py Progetto: 3gx/SymPyFME
 def infer_pos_polynom(self, comb):
     assert len(comb) == len(self.gen_pos_polynoms)
     for x in comb:
         assert self.eval_sign(sympy.S(x)) >= 0, str(x)
     gen_poly = self.gen_pos_polynoms
     new_poly = sum([v_i * gen_poly[i] for (i, v_i) in enumerate(comb)])
     self.inf_pos_polynoms.append(new_poly)
     self.pos_polynoms.append(new_poly)
Esempio n. 23
0
 def get_signal_variance(self, output):
     if not self.computed:
         sys.exit("System has not been computed")
     result = 0.0
     for i in self.signal_propagation[output]:
         if not i == sympy.S(1.0):
             result += self.signal_propagation[output][i]**2
     return result / 3
Esempio n. 24
0
def test_issue9474():
    mods = [None, 'math']
    if numpy:
        mods.append('numpy')
    if mpmath:
        mods.append('mpmath')
    for mod in mods:
        f = lambdify(x, sympy.S(1)/x, modules=mod)
        assert f(2) == 0.5
        f = lambdify(x, floor(sympy.S(1)/x), modules=mod)
        assert f(2) == 0

    for absfunc, modules in product([Abs, abs], mods):
        f = lambdify(x, absfunc(x), modules=modules)
        assert f(-1) == 1
        assert f(1) == 1
        assert f(3+4j) == 5
Esempio n. 25
0
def decorate_dataframe(df):

    # Get properties matched from catalog
    catalog_matched_props = []

    for col in df.columns:
        mcol = col.lower()
        mcol = re.sub(r'\(.*\)', '', mcol)  # Remove parenthesis
        mcol = re.sub(r'\'', '', mcol)  # Remove apostrophes
        mcol = mcol.strip()

        for prop in catalog['properties']:
            if mcol in prop['spec']['name']:
                catalog_name = prop['spec']['name'].replace(' ', '')
                catalog_matched_props.append({
                    'catalog_name':
                    catalog_name,
                    'df_name':
                    col,
                    'symbol':
                    sp.symbols(prop['spec']['symbol']),
                    'units':
                    prop['spec']['units']
                })
            # TODO: check for alternate names

    # Get ALL available property class names and objects
    mech_props = {
        c[0].lower(): c[1]
        for c in inspect.getmembers(mechanical_properties, inspect.isclass)
    }

    # Get equations of matched properties
    eqns = []
    df_sym_col = {
    }  # Matched columns in df in 'catalog_symbol': 'col_name' format.
    for cmp in catalog_matched_props:
        if cmp['catalog_name'] in mech_props:
            eqns.append(sp.Eq(mech_props[cmp['catalog_name']]().equation()))
            df_sym_col[cmp['symbol']] = cmp['df_name']

    # Solve each row of the dataframe
    for idx, row in df.iterrows():

        eqns_tosolve = eqns[:]

        # add equation of symbol and its values from provided df
        for col in df_sym_col:
            eqns_tosolve.append(sp.Eq(col, row[df_sym_col[col]]))

        soln = sp.solve(eqns_tosolve)

        if soln:
            print idx, eqns_tosolve, soln
            df.loc[idx, "Calculated Poisson's ratio"] = round(
                soln[0][sp.S('nu')], 2)

    return df
def PrintCoefficientsOfFunctions(phi_orthonormalized_list, StartFunctionIndex):
    """
    Prints the coefficients of orthonormalized functions as

        phi_j = alpha_j * \sum_{i=1}^n a_{ij} t^{1/i}

    where alpha_j = sqrt{2/j}, and a_{ij} are integers
    """

    print('-------------------------')
    print('Coefficient of functions:')
    print('-------------------------')
    print('')
    print('i       alpha_[i]   a_[ij]')
    print('------  ----------  ---------')

    NumFunctions = len(phi_orthonormalized_list)
    for j in range(NumFunctions):

        # Multiply each function with sqrt(2/i+1) to have integer coefficients
        Alpha = (sympy.S(-1)**(sympy.S(j))) * sympy.sqrt(
            sympy.Rational(2, j + StartFunctionIndex + 1))
        Function = phi_orthonormalized_list[j] / Alpha
        Function = sympy.simplify(Function)

        # Convert the function to a polynomial
        Polynomial = sympy.Poly(Function)

        # Get the coefficient of each monomial
        Coefficients = []
        for i in range(j + 1):
            Coefficient = Polynomial.coeff_monomial(t**(sympy.Rational(
                1, i + 1 + StartFunctionIndex)))
            Coefficients.append(Coefficient)

        # Print human friendly
        Sign = (-1)**(j)
        SignAsString = '-'
        if Sign > 0: SignAsString = '+'
        AlphaAsString = SignAsString + 'sqrt(2/%d)' % (j + StartFunctionIndex +
                                                       1)
        print('i = %d:  %s  %s' %
              (j + StartFunctionIndex, AlphaAsString, Coefficients))

    print('')
Esempio n. 27
0
 def calc(self):
     """
     求解导数
     :return: 导数计算后的结果
     """
     self.func = func_name_substitution(self.func)
     deri = sympy.Derivative(sympy.sympify(self.func),
                             sympy.S(self.deri_param), self.times).doit()
     return deri
Esempio n. 28
0
def test_extract_coeffs_nlin():
    eqn = sympy.sympify("y -2*x -3 + exp(x)")
    local_map = {sympy.symbols("y"): 0, sympy.symbols("x"): 1}
    coords = [sympy.symbols("r_1"), sympy.symbols("r_0"), sympy.S(1)]

    lin, nlin = extract_coefficients(eqn, local_map, coords)
    assert lin[1] == -2
    assert lin[0] == 1
    assert nlin == sympy.sympify("exp(r_0) - 3")
Esempio n. 29
0
 def get_noise_variance(self, output, wlv):
     if not self.computed:
         sys.exit("System has not been computed")
     result = 0.0
     for i in self.noised_outputs[output]:
         if not i == sympy.S(1.0):
             result += (self.signal_propagation[output].get(i, 0.0) -
                        self.noised_outputs[output].get(i, 0.0))**2
     return (result).subs(zip(self.noise_wlvars, wlv)) / 3
Esempio n. 30
0
File: chem.py Progetto: QamarQQ/C-
def mk_exprs_symbs(rxns, names):
    concs = sym.symbols(names, real=True, nonnegative=True)
    c_dict = dict(zip(names, concs))
    f = {n: 0 for n in names}
    for coeff, r_stoich, net_stoich in rxns:
        r = sym.S(coeff) * prod([c_dict[rk]**p for rk, p in r_stoich.items()])
        for nk, nm in net_stoich.items():
            f[nk] += nm * r
    return [f[n] for n in names], concs