Exemplo n.º 1
0
def tustin(tf, sRate):
	s =	getMapping(tf)['s']
	T = 1/sRate
	poles = sympy.roots(sympy.denom(tf), s, multiple=True)
	centroid = np.mean(np.abs(poles))
	invz = sympy.Symbol('invz', real=True)
	# normalized center frequency derived from poles of filter SISO transfer function
	w0 = 2*np.pi*centroid/(sRate*2*np.pi)
	# modified bilinear transform w/ frequency warping
	bt = w0/sympy.tan(w0*T/2) * ((1-invz)/(1+invz))
	dt = sympy.simplify(tf.subs({s: bt}))
	b = sympy.Poly(sympy.numer(dt)).all_coeffs()[::-1]
	a = sympy.Poly(sympy.denom(dt)).all_coeffs()[::-1]
	normalize = lambda x: float(x/a[0])
	return (map(normalize, b), map(normalize, a))
Exemplo n.º 2
0
def poles(G):
    '''
    Return the poles of a multivariable transfer function system. Applies
    Theorem 4.4 (p135).

    Parameters
    ----------
    G : numpy matrix (n x n)
        The transfer function G(s) of the system.

    Returns
    -------
    zero : array
        List of zeros.

    Example
    -------
    >>> def G(s):
    ...     return 1 / (s + 2) * numpy.matrix([[s - 1,  4],
    ...                                       [4.5, 2 * (s - 1)]])
    >>> poles(G)
    [-2.00000000000000]

    Note
    ----
    Not applicable for a non-squared plant, yet.
    '''

    s = sympy.Symbol('s')
    G = sympy.Matrix(G(s))  # convert to sympy matrix object
    det = sympy.simplify(G.det())
    pole = sympy.solve(sympy.denom(det))
    return pole
Exemplo n.º 3
0
def find_simple_recurrence_vector(l):
    """
    This function is used internally by other functions from the
    sympy.concrete.guess module. While most users may want to rather use the
    function find_simple_recurrence when looking for recurrence relations
    among rational numbers, the current function may still be useful when
    some post-processing has to be done.

    The function returns a vector of length n when a recurrence relation of
    order n is detected in the sequence of rational numbers v.

    If the returned vector has a length 1, then the returned value is always
    the list [0], which means that no relation has been found.

    While the functions is intended to be used with rational numbers, it should
    work for other kinds of real numbers except for some cases involving
    quadratic numbers; for that reason it should be used with some caution when
    the argument is not a list of rational numbers.

    Examples
    ========

    >>> from sympy.concrete.guess import find_simple_recurrence_vector
    >>> from sympy import fibonacci
    >>> find_simple_recurrence_vector([fibonacci(k) for k in range(12)])
    [1, -1, -1]

    See also
    ========

    See the function sympy.concrete.guess.find_simple_recurrence which is more
    user-friendly.

    """
    q1 = [0]
    q2 = [Integer(1)]
    b, z = 0, len(l) >> 1
    while len(q2) <= z:
        while l[b]==0:
            b += 1
            if b == len(l):
                c = 1
                for x in q2:
                    c = lcm(c, denom(x))
                if q2[0]*c < 0: c = -c
                for k in range(len(q2)):
                    q2[k] = int(q2[k]*c)
                return q2
        a = Integer(1)/l[b]
        m = [a]
        for k in range(b+1, len(l)):
            m.append(-sum(l[j+1]*m[b-j-1] for j in range(b, k))*a)
        l, m = m, [0] * max(len(q2), b+len(q1))
        for k in range(len(q2)):
            m[k] = a*q2[k]
        for k in range(b, b+len(q1)):
            m[k] += q1[k-b]
        while m[-1]==0: m.pop() # because trailing zeros can occur
        q1, q2, b = q2, m, 1
    return [0]
Exemplo n.º 4
0
def e2nd(expression):
	""" basic helper function that accepts a sympy expression, expands it,
	attempts to simplify it, and returns a numerator and denomenator pair for the instantiation of a scipy
	LTI system object. """
	expression = expression.expand()
	expression = expression.cancel()
	n = sympy.Poly(sympy.numer(expression), s).all_coeffs()
	d = sympy.Poly(sympy.denom(expression), s).all_coeffs()
	n = map(float, n)
	d = map(float, d)
	return (n, d)
Exemplo n.º 5
0
def e2nd(expression):
    """ basic helper function that accepts a sympy expression, expands it,
	attempts to simplify it, and returns a numerator and denomenator pair for the instantiation of a scipy
	LTI system object. """
    expression = expression.expand()
    expression = expression.cancel()
    n = sympy.Poly(sympy.numer(expression), s).all_coeffs()
    d = sympy.Poly(sympy.denom(expression), s).all_coeffs()
    n = map(float, n)
    d = map(float, d)
    return (n, d)
def _conversion_fraction(context, is_train):
  """E.g., "How many grams are in three quarters of a kg?"."""
  dimension = random.choice(DIMENSIONS)

  # Limit probability of giving zero answer.
  allow_zero = random.random() < 0.2

  # Repeat until we find a pair with an integral answer. (Avoids ambiguity with
  # decimals.)
  while True:
    base_unit, target_unit = random.sample(list(dimension.keys()), 2)
    base_value = number.non_integer_rational(2, signed=False)
    if train_test_split.is_train(base_value) != is_train:
      continue
    answer = (base_value * sympy.Rational(dimension[base_unit])
              / sympy.Rational(dimension[target_unit]))
    if (abs(answer) <= 100000
        and sympy.denom(answer) == 1
        and (allow_zero or answer != 0)):
      break

  template, case = random.choice([
      ('Сколько {target_name_skolko} в {base_value} {base_name_fraction}?', 'v'),
      ('Переведите {base_value} {base_name_fraction} в {target_name}?', 'perevedi'),
  ])

  if sympy.denom(base_value) > 20 or random.choice([False, True]):
    base_value_string = base_value  # Will be represented as e.g., 2/3.
  else:
    base_value_string = display.StringNumber(base_value, case=case, gender='fem')  # e.g., two thirds
  # тут всегда единственное у меры

  question = example.question(
      context, template,
      base_name=base_unit.name,
      base_name_fraction=base_unit.name_perevedi[1],
      base_value=base_value_string,
      target_name=target_unit.name,
      target_name_skolko=target_unit.name_skolko)
  return example.Problem(question=question, answer=answer)
Exemplo n.º 7
0
    def __new__(cls, b, e, evaluate=True):
        from sympy.functions.elementary.exponential import exp_polar
        from sympy.functions import log
        # don't optimize "if e==0; return 1" here; it's better to handle that
        # in the calling routine so this doesn't get called
        b = _sympify(b)
        e = _sympify(e)
        if evaluate:
            if e is S.Zero:
                return S.One
            elif e is S.One:
                return b
            elif S.NaN in (b, e):
                if b is S.One:  # already handled e == 0 above
                    return S.One
                return S.NaN
            else:
                if e.func == log:
                    if len(e.args) == 2:
                        lbase = e.args[1]
                    else:
                        lbase = S.Exp1
                    if lbase == b:
                        return e.args[0]

                if e is Mul and e.args[1].func == log:
                    if len(e.args[1].args) == 2:
                        lbase = e.args[1].args[1]
                    else:
                        lbase = S.Exp1
                    if lbase == b:
                        return e.args[1].args[0] ** e.args[0]

                # recognize base as E
                if not e.is_Atom and b is not S.Exp1 and b.func is not exp_polar:
                    from sympy import numer, denom, log, sign, im, factor_terms
                    c, ex = factor_terms(e, sign=False).as_coeff_Mul()
                    den = denom(ex)
                    if den.func is log and den.args[0] == b:
                        return S.Exp1**(c*numer(ex))
                    elif den.is_Add:
                        s = sign(im(b))
                        if s.is_Number and s and den == \
                                log(-factor_terms(b, sign=False)) + s*S.ImaginaryUnit*S.Pi:
                            return S.Exp1**(c*numer(ex))

                obj = b._eval_power(e)
                if obj is not None:
                    return obj
        obj = Expr.__new__(cls, b, e)
        obj.is_commutative = (b.is_commutative and e.is_commutative)
        return obj
Exemplo n.º 8
0
def sympy_to_tf(G, data):
    """convert a discrete transfer function in sympy to a contorl.tf"""
    z = sympy.symbols('z')
    Gs = G.subs(data)
    try:
        num = np.array(sympy.Poly(sympy.numer(Gs), z).all_coeffs(),
                       dtype=float)
        den = np.array(sympy.Poly(sympy.denom(Gs), z).all_coeffs(),
                       dtype=float)
    except Exception:
        raise TypeError('failed to convert expression to float polynomials: ',
                        Gs)
    return control.tf(num, den, 1.0 / data['f_s'])
def _conversion_fraction(context, is_train):
    """E.g., "How many grams are in three quarters of a kg?"."""
    dimension = random.choice(DIMENSIONS)

    # Limit probability of giving zero answer.
    allow_zero = random.random() < 0.2

    # Repeat until we find a pair with an integral answer. (Avoids ambiguity with
    # decimals.)
    while True:
        base_unit, target_unit = random.sample(list(dimension.keys()), 2)
        base_value = number.non_integer_rational(2, signed=False)
        if train_test_split.is_train(base_value) != is_train:
            continue
        answer = (base_value * sympy.Rational(dimension[base_unit]) /
                  sympy.Rational(dimension[target_unit]))
        if (abs(answer) <= 100000 and sympy.denom(answer) == 1
                and (allow_zero or answer != 0)):
            break

    template = random.choice([
        'Ada berapa {target_name} di {base_value} dari sebuah {base_name}?',
        'Berapa {base_value} dari {base_name} di {target_name}?',
    ])

    if sympy.denom(base_value) > 20 or random.choice([False, True]):
        base_value_string = base_value  # Will be represented as e.g., 2/3.
    else:
        base_value_string = display.StringNumber(
            base_value)  # e.g., two thirds

    question = example.question(context,
                                template,
                                base_name=base_unit.name,
                                base_value=base_value_string,
                                target_name=target_unit.name)
    return example.Problem(question=question, answer=answer)
Exemplo n.º 10
0
def entropy_of_value(value):
    """Returns "min entropy" that would give probability of getting this value."""
    if isinstance(value, display.Decimal):
        return entropy_of_value(sympy.numer(value))

    if is_non_integer_rational(value):
        numer = sympy.numer(value)
        denom = sympy.denom(value)
        return entropy_of_value(numer) + entropy_of_value(denom)
    elif not is_integer(value):
        raise ValueError('Unhandled value: {}'.format(value))

    # Note: we sample integers in a range of size approx 10**entropy about zero,
    # so assume that `abs(value)` is about half of the upper range.
    return math.log10(5 * abs(value) + 1)
Exemplo n.º 11
0
    def Pow(expr, assumptions):
        """
        Imaginary**integer/odd  -> Imaginary
        Imaginary**integer/even -> Real if integer % 2 == 0
        b**Imaginary            -> !Imaginary if exponent is an integer multiple of I*pi/log(b)
        Imaginary**Real         -> ?
        Negative**even root     -> Imaginary
        Negative**odd root      -> Real
        Negative**Real          -> Imaginary
        Real**Integer           -> Real
        Real**Positive          -> Real
        """
        if expr.is_number:
            return AskImaginaryHandler._number(expr, assumptions)

        if expr.base.func == C.exp:
            if ask(Q.imaginary(expr.base.args[0]), assumptions):
                if ask(Q.imaginary(expr.exp), assumptions):
                    return False
                i = expr.base.args[0] / I / pi
                if ask(Q.integer(2 * i), assumptions):
                    return ask(Q.imaginary(((-1)**i)**expr.exp), assumptions)

        if ask(Q.imaginary(expr.base), assumptions):
            if ask(Q.integer(expr.exp), assumptions):
                odd = ask(Q.odd(expr.exp), assumptions)
                if odd is not None:
                    return odd
                return

        if ask(Q.imaginary(expr.exp), assumptions):
            imlog = ask(Q.imaginary(C.log(expr.base)), assumptions)
            if imlog is not None:
                return False  # I**i -> real; (2*I)**i -> complex ==> not imaginary

        if ask(Q.real(expr.base), assumptions):
            if ask(Q.real(expr.exp), assumptions):
                if ask(
                        Q.rational(expr.exp) & Q.even(denom(expr.exp)),
                        assumptions):
                    return ask(Q.negative(expr.base), assumptions)
                elif ask(Q.integer(expr.exp), assumptions):
                    return False
                elif ask(Q.positive(expr.base), assumptions):
                    return False
                elif ask(Q.negative(expr.base), assumptions):
                    return True
Exemplo n.º 12
0
def _div_op(value, sample_args, rationals_allowed):
    """Returns sampled args for `ops.Div`."""
    assert rationals_allowed  # should be True if this function gets invoked
    entropy, sample_args = sample_args.peel()

    numer = sympy.numer(value)
    denom = sympy.denom(value)

    if sample_args.count == 1:
        mult = number.integer(entropy, signed=True, min_abs=1)
        op_args = [numer * mult, denom * mult]
    elif sample_args.count == 2:
        if numer == 0 or random.choice([False, True]):
            x = number.integer(entropy,
                               signed=True,
                               min_abs=1,
                               coprime_to=denom)
            op_args = [sympy.Rational(x * numer, denom), x]
        else:
            x = number.integer(entropy,
                               signed=True,
                               min_abs=1,
                               coprime_to=numer)
            op_args = [x, sympy.Rational(x * denom, numer)]
    else:
        assert sample_args.count >= 3
        p2, p1 = _split_factors(numer)
        q1, q2 = _split_factors(denom)
        entropy -= _entropy_of_factor_split(numer) + _entropy_of_factor_split(
            denom)
        entropy_r = random.uniform(0, entropy)
        entropy_s = entropy - entropy_r
        r = number.integer(entropy_r,
                           signed=True,
                           min_abs=1,
                           coprime_to=q1 * p2)
        s = number.integer(entropy_s,
                           signed=False,
                           min_abs=1,
                           coprime_to=p1 * q2)
        op_args = [
            sympy.Rational(r * p1, s * q1),
            sympy.Rational(r * q2, s * p2)
        ]

    return ops.Div, op_args, sample_args
Exemplo n.º 13
0
Arquivo: sets.py Projeto: B-Rich/sympy
    def Pow(expr, assumptions):
        """
        Imaginary**integer/odd  -> Imaginary
        Imaginary**integer/even -> Real if integer % 2 == 0
        b**Imaginary            -> !Imaginary if exponent is an integer multiple of I*pi/log(b)
        Imaginary**Real         -> ?
        Negative**even root     -> Imaginary
        Negative**odd root      -> Real
        Negative**Real          -> Imaginary
        Real**Integer           -> Real
        Real**Positive          -> Real
        """
        if expr.is_number:
            return AskImaginaryHandler._number(expr, assumptions)

        if expr.base.func == C.exp:
            if ask(Q.imaginary(expr.base.args[0]), assumptions):
                if ask(Q.imaginary(expr.exp), assumptions):
                    return False
                i = expr.base.args[0]/I/pi
                if ask(Q.integer(2*i), assumptions):
                    return ask(Q.imaginary(((-1)**i)**expr.exp), assumptions)

        if ask(Q.imaginary(expr.base), assumptions):
            if ask(Q.integer(expr.exp), assumptions):
                odd = ask(Q.odd(expr.exp), assumptions)
                if odd is not None:
                    return odd
                return

        if ask(Q.imaginary(expr.exp), assumptions):
            imlog = ask(Q.imaginary(C.log(expr.base)), assumptions)
            if imlog is not None:
                return False  # I**i -> real; (2*I)**i -> complex ==> not imaginary

        if ask(Q.real(expr.base), assumptions):
            if ask(Q.real(expr.exp), assumptions):
                if ask(Q.rational(expr.exp) & Q.even(denom(expr.exp)), assumptions):
                    return ask(Q.negative(expr.base), assumptions)
                elif ask(Q.integer(expr.exp), assumptions):
                    return False
                elif ask(Q.positive(expr.base), assumptions):
                    return False
                elif ask(Q.negative(expr.base), assumptions):
                    return True
Exemplo n.º 14
0
    def __new__(cls, b, e, evaluate=None):
        if evaluate is None:
            evaluate = global_evaluate[0]
        from sympy.functions.elementary.exponential import exp_polar

        b = _sympify(b)
        e = _sympify(e)
        if evaluate:
            if e is S.Zero:
                return S.One
            elif e is S.One:
                return b
            elif e.is_integer and _coeff_isneg(b):
                if e.is_even:
                    b = -b
                elif e.is_odd:
                    return -Pow(-b, e)
            if b is S.One:
                if e in (S.NaN, S.Infinity, -S.Infinity):
                    return S.NaN
                return S.One
            elif S.NaN in (
                    b,
                    e):  # XXX S.NaN**x -> S.NaN under assumption that x != 0
                return S.NaN
            else:
                # recognize base as E
                if not e.is_Atom and b is not S.Exp1 and b.func is not exp_polar:
                    from sympy import numer, denom, log, sign, im, factor_terms
                    c, ex = factor_terms(e, sign=False).as_coeff_Mul()
                    den = denom(ex)
                    if den.func is log and den.args[0] == b:
                        return S.Exp1**(c * numer(ex))
                    elif den.is_Add:
                        s = sign(im(b))
                        if s.is_Number and s and den == \
                                log(-factor_terms(b, sign=False)) + s*S.ImaginaryUnit*S.Pi:
                            return S.Exp1**(c * numer(ex))

                obj = b._eval_power(e)
                if obj is not None:
                    return obj
        obj = Expr.__new__(cls, b, e)
        obj.is_commutative = (b.is_commutative and e.is_commutative)
        return obj
Exemplo n.º 15
0
def mutate_rat(value, *, keep_sign=True, mutate_up=None):
    '''Mutate rational number'''

    r = random.random()
    numer, denom = sp.numer(value), sp.denom(value)

    # swap numerator and denominator
    if r < 0.20:
        numer, denom = (mutate_int(denom, mutate_up=mutate_up, keep_sign=keep_sign),
                        mutate_int(numer, mutate_up=mutate_up))
    # mutate numerator
    elif r < 0.65:
        numer = mutate_int(numer, mutate_up=mutate_up, keep_sign=keep_sign)
    # mutate denominator
    else:
        denom = mutate_int(denom, mutate_up=mutate_up, keep_sign=keep_sign)

    return sp.Rational(numer, denom or 1)
Exemplo n.º 16
0
    def pk_parameters(self, seed=None):
        statements = self.model.statements
        odes = statements.ode_system
        central = odes.find_central()
        output = odes.find_output()
        depot = odes.find_depot(statements)
        peripherals = odes.find_peripherals()
        elimination_rate = odes.get_flow(central, output)

        expressions = []  # Eq(name, expr)
        # FO abs + 1comp + FO elimination
        if len(odes) == 3 and depot and odes.t not in elimination_rate.free_symbols:
            ode_list, ics = odes.to_explicit_odes(skip_output=True)
            sols = sympy.dsolve(ode_list, ics=ics)
            expr = sols[1].rhs
            d = sympy.diff(expr, odes.t)
            tmax_closed_form = sympy.solve(d, odes.t)[0]
            expressions.append(sympy.Eq(sympy.Symbol('t_max'), tmax_closed_form))
            e2 = sympy.simplify(expr / depot.dose.amount / sympy.denom(elimination_rate))
            cmax_dose_closed_form = sympy.simplify(e2.subs({odes.t: tmax_closed_form}))
            expressions.append(sympy.Eq(sympy.Symbol('C_max_dose'), cmax_dose_closed_form))

        # Any abs + 1comp + FO elimination
        if not peripherals and odes.t not in elimination_rate.free_symbols:
            elimination_system = statements.copy().ode_system
            # keep central and output
            for name in elimination_system.names:
                if name not in [central.name, output.name]:
                    elimination_system.remove_compartment(elimination_system.find_compartment(name))
                    ode_list, ics = elimination_system.to_explicit_odes(skip_output=True)
                    A0 = sympy.Symbol('A0')
                    ic = ics.popitem()
                    ics = {ic[0]: A0}
                    sols = sympy.dsolve(ode_list[0], ics=ics)
                    eq = sympy.Eq(sympy.Rational(1, 2) * A0, sols.rhs)
                    thalf_elim = sympy.solve(eq, odes.t)[0]
                    expressions.append(sympy.Eq(sympy.Symbol('t_half_elim'), thalf_elim))

        # Any abs + any comp + FO elimination
        if odes.t not in elimination_rate.free_symbols:
            expressions.append(sympy.Eq(sympy.Symbol('k_e'), elimination_rate))

        df = self.individual_parameter_statistics(expressions, seed=seed)
        return df
Exemplo n.º 17
0
    def __new__(cls, b, e, evaluate=None):
        if evaluate is None:
            evaluate = global_evaluate[0]
        from sympy.functions.elementary.exponential import exp_polar

        b = _sympify(b)
        e = _sympify(e)
        if evaluate:
            if e is S.Zero:
                return S.One
            elif e is S.One:
                return b
            elif e.is_integer and _coeff_isneg(b):
                if e.is_even:
                    b = -b
                elif e.is_odd:
                    return -Pow(-b, e)
            if b is S.One:
                if e in (S.NaN, S.Infinity, -S.Infinity):
                    return S.NaN
                return S.One
            elif S.NaN in (b, e):  # XXX S.NaN**x -> S.NaN under assumption that x != 0
                return S.NaN
            else:
                # recognize base as E
                if not e.is_Atom and b is not S.Exp1 and b.func is not exp_polar:
                    from sympy import numer, denom, log, sign, im, factor_terms
                    c, ex = factor_terms(e, sign=False).as_coeff_Mul()
                    den = denom(ex)
                    if den.func is log and den.args[0] == b:
                        return S.Exp1**(c*numer(ex))
                    elif den.is_Add:
                        s = sign(im(b))
                        if s.is_Number and s and den == \
                                log(-factor_terms(b, sign=False)) + s*S.ImaginaryUnit*S.Pi:
                            return S.Exp1**(c*numer(ex))

                obj = b._eval_power(e)
                if obj is not None:
                    return obj
        obj = Expr.__new__(cls, b, e)
        obj.is_commutative = (b.is_commutative and e.is_commutative)
        return obj
Exemplo n.º 18
0
  def _rational_to_string(self, rational):
    """Converts a rational to words, e.g., "two thirds"."""
    numer = sympy.numer(rational)
    denom = sympy.denom(rational)

    numer_words = self._to_string(numer)

    if denom == 1:
      return numer_words

    if denom <= 0 or denom >= len(_PLURAL_DENOMINATORS):
      raise ValueError('Unsupported denominator {}.'.format(denom))

    if numer == 1:
      denom_word = _SINGULAR_DENOMINATORS[denom]
    else:
      denom_word = _PLURAL_DENOMINATORS[denom]

    return '{} {}'.format(numer_words, denom_word)
Exemplo n.º 19
0
  def __init__(self, value):
    """Initializes a `Decimal`.

    Args:
      value: (Sympy) value to display as a decimal.

    Raises:
      ValueError: If `value` cannot be represented as a non-terminating decimal.
    """
    self._value = sympy.Rational(value)

    numer = int(sympy.numer(self._value))
    denom = int(sympy.denom(self._value))

    denom_factors = list(sympy.factorint(denom).keys())
    for factor in denom_factors:
      if factor not in [2, 5]:
        raise ValueError('Cannot represent {} as a non-recurring decimal.'
                         .format(value))
    self._decimal = decimal.Decimal(numer) / decimal.Decimal(denom)
Exemplo n.º 20
0
    def __new__(cls, b, e, evaluate=None):
        if evaluate is None:
            evaluate = global_evaluate[0]
        from sympy.functions.elementary.exponential import exp_polar

        # don't optimize "if e==0; return 1" here; it's better to handle that
        # in the calling routine so this doesn't get called
        b = _sympify(b)
        e = _sympify(e)
        if evaluate:
            if e is S.Zero:
                return S.One
            elif e is S.One:
                return b
            elif b is S.One:
                if e in (S.NaN, S.Infinity, -S.Infinity):
                    return S.NaN
                return S.One
            elif S.NaN in (b, e):
                return S.NaN
            else:
                # recognize base as E
                if not e.is_Atom and b is not S.Exp1 and b.func is not exp_polar:
                    from sympy import numer, denom, log, sign, im, factor_terms
                    c, ex = factor_terms(e, sign=False).as_coeff_Mul()
                    den = denom(ex)
                    if den.func is log and den.args[0] == b:
                        return S.Exp1**(c * numer(ex))
                    elif den.is_Add:
                        s = sign(im(b))
                        if s.is_Number and s and den == \
                                log(-factor_terms(b, sign=False)) + s*S.ImaginaryUnit*S.Pi:
                            return S.Exp1**(c * numer(ex))

                obj = b._eval_power(e)
                if obj is not None:
                    return obj
        obj = Expr.__new__(cls, b, e)
        obj.is_commutative = (b.is_commutative and e.is_commutative)
        return obj
Exemplo n.º 21
0
def separate_imaginary(eqn, model_type):
    """
Separates the real and imaginary components of symbolic equations. <br/>
Needs - sympy equation, string model type ('short', 'open', etc.)

#**Example:**
```
    >> calc_magnitude(OpenModel(complex=True).s_parameters()[0])
```
    """
    # TODO - this doesn't really work for S12/S21
    from sympy import symbols, expand, simplify, conjugate, denom, I
    l0, l1, l2, c0, c1, c2, x = symbols('l0 l1 l2 c0 c1 c2 x')
    L = symbols('L', real=True)
    eqn = eqn.subs(math.pi, sympy.pi)
    eqn = eqn.subs(f**2*l2 + f*l1 + l0, L) if model_type == 'short' else eqn.subs(1 / (c0+c1*f+c2*f**2), L)
    conj = denom(conjugate(eqn))
    eqn = simplify(expand(simplify(eqn)*conj))
    eqn = simplify(eqn*1/conj)
    # eqn = eqn.subs(L, l0 + l1*f + l2*f**2) if model_type == 'short' else eqn.subs(L, 1 / (c0+c1*f+c2*f**2))
    return np.array(['real', simplify(eqn.subs(I, 0)),
                     'imag', simplify(expand(eqn) - eqn.subs(sympy.I, 0)).subs(I, 1)])
def _mul_op(value, sample_args, rationals_allowed):
  """Returns sampled args for `ops.Mul`."""
  if sample_args.count >= 3:
    _, op_args, sample_args = _div_op(value, sample_args, rationals_allowed)
    op_args = [op_args[0], sympy.Integer(1) / op_args[1]]
  elif sample_args.count == 1:
    entropy, sample_args = sample_args.peel()
    assert _entropy_of_factor_split(value) >= entropy
    op_args = _split_factors(value)
  else:
    assert sample_args.count == 2
    entropy, sample_args = sample_args.peel()
    numer = sympy.numer(value)
    denom = sympy.denom(value)
    p1, p2 = _split_factors(numer)
    entropy -= _entropy_of_factor_split(numer)
    mult = number.integer(entropy, signed=True, min_abs=1, coprime_to=p1)
    op_args = [p1 / (mult * denom), p2 * mult]

  if random.choice([False, True]):
    op_args = list(reversed(op_args))

  return ops.Mul, op_args, sample_args
Exemplo n.º 23
0
tf = ahkabHelpers.reduceTF(tf, mycircuit)

sRate = 44.1e3

fs = lambda x: sympy.N(abs(tf.subs({s:sympy.I*x})))
ws = np.logspace(1, np.log10(sRate), 5e2)
mags = map(fs,ws)

print tf
(b, a) = ahkabHelpers.tustin(tf, sRate)
print b,a

pylab.semilogx(ws, map(fs, ws), 'v', label="from transfer function")
pylab.semilogx(r['ac']['w'][::10], np.abs(r['ac']['VU1o'][::10]), '-', label='from AC simulation')
pylab.vlines(np.abs(sympy.roots(sympy.denom(tf), s, multiple=True)), 0, 1, 'r')

# build white noise input vector, normalized to \pm 1.0
x = list(2*np.random.random(sRate)-1.0)
# allocate output vector for y[n-2] indexing to work
y = [0.0]*len(x)

# Direct Form I
for n in range(len(x)):
	y[n] = b[0]*x[n] + b[1]*x[n-1] + b[2]*x[n-2] - a[1]*y[n-1] - a[2]*y[n-2]

# frequencies to radians
freqs = (np.fft.fftfreq(len(y), 1/sRate))[0:len(y)/2] * (2*np.pi)
mags = 	(np.abs(np.fft.fft(np.array(y))))[0:len(y)/2]

# normalize magnitude to 1.0
def ac_analysis(param_d, param_l, instance, file_sufix):
    """ Performs ac analysis

        param_d: substitutions for symbols, or named parameters for plot
        
        param_l: expresions to plot

        format is:
        .ac expresion0 [expresion1 expresion2 ...] sweep = parameter_to_sweep [symmbol_or_option0 = value0
        symmbol_or_option1 = value1 ...]
        
        expresions are on positiona parameters list can hold expresions containing parameters or functions of nodal
        voltages [v(node)] and element and port currents [i(element) isub(port)]

        named parameters (param_d) can contain options for analysis or substitutions for symbols, substituions will be
        done as they are without any parsing, be aware of symbol and option names clashes.

        Config options:
        fstart:         first value of frequency for AC analysis [float]
        fstop:          last value of frequency for AC analysis [float]
        fscale:         scale for frequency points [linear | log]
        npoints:        numbers of points for ac analysis [integer]
        yscale:         scale for y-axis to being displayed on [linear or log]
        hold:           hold plot for next analysis and don't save it to file [yes | no]
        show_poles:     show poles of function on plot [yes | no]
        show_zeroes:    show zeros of function on plot [yes | no]
        title:          display title above ac plot [string]
        show_legend:    show legend on plot [yes | no]
        xkcd:           style plot to be xkcd like scetch
    """
    warnings.filterwarnings('ignore')  # Just getting rid of those fake casting from complex warnings
    s, w = sympy.symbols(('s', 'w'))
    config = {'fstart': 1,
              'fstop': 1e6,
              'fscale': 'log',
              'npoints': 100,
              'yscale': 'log',
              'type': 'amp',
              'hold': 'no',
              'show_poles': 'yes',
              'show_zeros': 'yes',
              'title': None,
              'show_legend': 'no',
              'xkcd': 'no'}

    for config_name in config.keys():
        if config_name in param_d:
            config.update({config_name: param_d[config_name]})
            param_d.pop(config_name)

    subst = []
    for symbol, value in param_d.iteritems():
        tokens = scs_parser.parse_param_expresion(value)
        try:
            value = float(sympy.sympify(scs_parser.params2values(tokens, instance.paramsd),sympy.abc._clash))
        except ValueError:
            raise scs_errors.ScsAnalysisError("Passed subsitution for %s is not a number")

        subst.append((symbol, value))

    if config['fscale'] == 'log':
        fs = np.logspace(np.log10(float(config['fstart'])), np.log10(float(config['fstop'])), int(config['npoints']))
    elif config['fscale'] == 'linear':
        fs = np.linspace(float(config['fstart']), float(config['fstop']), int(config['npoints']))
    else:
        raise scs_errors.ScsAnalysisError(("Option %s for fscale invalid!" % config['yscale']))

    if config['yscale'] != 'log' and config['yscale'] != 'linear':
        raise scs_errors.ScsAnalysisError(("Option %s for yscale invalid!" % config['fscale']))

    filename = "%s.results" % file_sufix

    with open(filename, 'a') as fil:
        if config['xkcd'] == 'yes':
            plt.xkcd()
        plt.hold(True)

        for expresion in param_l:
            fil.write("%s: %s \n---------------------\n" % ('AC analysis of', expresion))
            tokens = scs_parser.parse_analysis_expresion(expresion)
            value0 = sympy.factor(sympy.sympify(scs_parser.results2values(tokens, instance),sympy.abc._clash), s).simplify()
            fil.write("%s = %s \n\n" % (expresion, str(value0)))
            denominator = sympy.denom(value0)
            numerator = sympy.numer(value0)
            poles = sympy.solve(denominator, s)
            zeros = sympy.solve(numerator, s)
            poles_r = sympy.roots(denominator, s)
            zeros_r = sympy.roots(numerator, s)
            gdc = str(value0.subs(s, 0).simplify())
            fil.write('G_DC = %s\n\n' % gdc)

            p = 0
            titled = 1
            for pole, degree in poles_r.iteritems():
                if pole == 0:
                    titled *= s ** degree
                else:
                    titled *= (s / sympy.symbols("\\omega_p%d" % p) + 1)
                p += 1
            z = 0
            titlen = 1
            for zero, degree in zeros_r.iteritems():
                if zero == 0:
                    titlen *= s ** degree
                else:
                    titlen *= (s / sympy.symbols("\\omega_z%d" % z) + 1)
                z += 1
            # title = sympy.symbols("G_DC") * (titlen / titled)
            value = value0.subs(subst)
            f = sympy.symbols('f', real=True)
            value = value.subs(s, sympy.sympify('2*pi*I').evalf() * f)
            tf = sympy.lambdify(f, abs(sympy.numer(value)) / abs(sympy.denom(value)))
            phf = sympy.lambdify(f, sympy.arg(value))

            if config['type'] == 'amp':
                zf = tf
                ylabel = '|T(f)|'
            elif config['type'] == 'phase':
                zf = phf
                ylabel = 'ph(T(f))'
            else:
                raise scs_errors.ScsAnalysisError("Option %s for type invalid!" % config['type'])

            try:
                ys = [float(zf(f)) for f in fs]
            except (ValueError, TypeError):
                raise scs_errors.ScsAnalysisError(
                    "Numeric error while evaluating expresions: %s. Not all values where subsituted?" % value0)

            plt.plot(fs, ys, label=expresion)

            plt.title(r'$%s$' % config['title'] if config['title'] else ' ', y=1.05)
            try:
                plt.xscale(config['fscale'])
                plt.yscale(config['yscale'])
            except ValueError, e:
                raise scs_errors.ScsAnalysisError(e)

            plt.xlabel('f [Hz]')
            plt.ylabel(ylabel)

            if len(poles):
                fil.write('Poles: \n')

            p = 0
            for pole in poles:

                try:
                    pole_value = pole.subs(subst)
                    pole_value_f = abs(np.float64(-abs(pole_value) / sympy.sympify('2*pi').evalf()))
                    pole_s = (-pole).simplify()
                    polestr = str(pole_s)
                    fil.write('wp_%d = %s\n\n' % (p, polestr))

                    p += 1
                    if pole_value_f > float(config['fstop']) \
                            or pole_value_f < float(config['fstart']) \
                            or np.isnan(zf(pole_value_f)):
                        continue
                    if config['show_poles'] == 'yes':
                        pole_label = r'$\omega_{p%d} $' % (p - 1)
                        plt.plot(pole_value_f, zf(pole_value_f), 'o', label=pole_label)
                        plt.text(pole_value_f, zf(pole_value_f), pole_label)
                        plt.axvline(pole_value_f, linestyle='dashed')
                except:
                    pass

            z = 0
            for zero in zeros:
                try:
                    zero_value = zero.subs(subst)
                    zero_value_f = abs(np.float64(-abs(zero_value) / sympy.sympify('2*pi').evalf()))
                    zero_s = (-zero).simplify()
                    zerostr = str(zero_s)
                    fil.write('wz_%d = %s\n\n' % (z, zerostr))
                    z += 1
                    if zero_value_f > float(config['fstop']) \
                            or zero_value_f < float(config['fstart']) \
                            or np.isnan(zf(zero_value_f)):
                        continue
                    if config['show_zeros'] == 'yes':
                        zero_label = r'$\omega_{z%d} $' % (z - 1)
                        plt.plot(zero_value_f, zf(zero_value_f), '*', label=zero_label)
                        plt.axvline(zero_value_f, linestyle='dashed')
                        plt.text(zero_value_f, zf(zero_value_f), zero_label)
                except:
                    pass
            if config['show_legend'] == 'yes':
                plt.legend()
            if config['hold'] == 'no':
                plt.hold(False)
                plt.savefig('%s_%d.png' % (file_sufix, PlotNumber.plot_num))
                plt.clf()
                PlotNumber.plot_num += 1
Exemplo n.º 25
0
def ALGO4(As,Bs,Cs,Ds,do_test):
    
    
    
#-------------------STEP 1------------------------------
    if not is_row_proper(As):
        Us,Ast=row_proper(As)
        
    else:
        Us,Ast=eye(As.rows),As
    
    Bst=Us*Bs
    Bst=expand(Bst)
    r=Ast.cols
    #-------------------STEP 2------------------------------
    K=simplify(Ast.inv()*Bst)  #very important 
    Ys=zeros(K.shape)
    for i,j in  product(range(K.rows),range(K.cols)):
        Ys[i,j],q=div(numer(K[i,j]),denom(K[i,j]))       
    
    B_hat=Bst-Ast*Ys
    
    #-------------------END STEP 2------------------------------
    #-------------------STEP 3------------------------------
    Psi=diag(*[[s**( mc.row_degrees(Ast,s)[j]  -i -1) for i in range( mc.row_degrees(Ast,s)[j])] for j in range(r)]).T
    S=diag(*[s**(rho) for rho in mc.row_degrees(Ast,s)])
    Ahr=mc.highest_row_degree_matrix(Ast,s)
    Help=Ast-S*Ahr
    
    SOL={}
    numvar=Psi.rows*Psi.cols
    alr=symbols('a0:%d'%numvar)
    Alr=Matrix(Psi.cols,Psi.rows,alr)
    RHS=Psi*Alr
    for i,j in  product(range(Help.rows),range(Help.cols)):                 #diagonal explain later
        SOL.update(solve_undetermined_coeffs(Eq(Help[i,j],RHS[i,j]),alr,s))
    
    Alr=Alr.subs(SOL)    #substitute(SOL)
    
    
    Aoc=Matrix(BlockDiagMatrix(*[Matrix(rho, rho, lambda i,j: KroneckerDelta(i+1,j))for rho in mc.row_degrees(Ast,s)]))
    Boc=eye(sum(mc.row_degrees(Ast,s)))
    Coc=Matrix(BlockDiagMatrix(*[SparseMatrix(1,rho,{(x,0):1 if x==0 else 0 for x in range(rho)}) for rho in mc.row_degrees(Ast,s)]))

    A0=Aoc-Alr*Ahr.inv()*Matrix(Coc)
    C0=Ahr.inv()*Coc



    SOL={}
    numvar=Psi.cols*Bst.cols
    b0=symbols('b0:%d'%numvar)
    B0=Matrix(Psi.cols,Bst.cols,b0)
    RHS=Psi*B0

    for i,j in  product(range(B_hat.rows),range(B_hat.cols)):                 #diagonal explain later
        SOL.update(solve_undetermined_coeffs(Eq(B_hat[i,j],RHS[i,j]),b0,s))
    B0=B0.subs(SOL)    #substitute(SOL)

    LHS_matrix=simplify(Cs*C0)                                        #left hand side of the equation (1)

    sI_A=s*eye(A0.cols)- A0
    max_degree=mc.find_degree(LHS_matrix,s)                   #get the degree of the matrix at the LHS
                                                  #which is also the maximum degree for the coefficients of Λ(s)
    #---------------------------Creating Matrices Λ(s) and C -------------------------------------

    Lamda=[]
    numvar=((max_degree))*A0.cols
    a=symbols('a0:%d'%numvar)
    for i in range(A0.cols):                                        # paratirisi den douleuei to prin giat;i otra oxi diagonios
        p=sum(a[n +i*(max_degree)]*s**n for n in range(max_degree))  # we want variables one degree lower because we are multiplying by first order monomials
        Lamda.append(p)
        
    Lamda=Matrix(Cs.rows,A0.cols,Lamda)                                #convert the list to Matrix
    
    c=symbols('c0:%d'%(Lamda.rows*Lamda.cols))
    C=Matrix(Lamda.rows,Lamda.cols,c)
    #-----------------------------------------
    
    RHS_matrix=Lamda*sI_A +C                            #right hand side of the equation (1)
     
    '''
    -----------Converting equation (1) to a system of linear -----------
    -----------equations, comparing the coefficients of the  -----------
    -----------polynomials in both sides of the equation (1) -----------
    '''
     EQ=[Eq(LHS_matrix[i,j],expand(RHS_matrix[i,j])) for i,j in product(range(LHS_matrix.rows),range(LHS_matrix.cols)) ]
# This is the standard form for the second order system transfer function

# In[7]:

G = K / (tau**2 * s**2 + 2 * tau * zeta * s + 1)
G

# In[8]:

invL(G)

# The characteristic equation is the denominator of the transfer function

# In[5]:

ce = sympy.Eq(sympy.denom(G), 0)
ce

# In[6]:

roots = sympy.roots(ce, s)
roots

# The shape of the inverse Laplace depends on the nature of the roots, which depends on the value of $\zeta$

# Overdamped: $\zeta>1$. Two distinct real roots

# In[3]:

G
Exemplo n.º 27
0
    def prep_geodesic_eqns(self, parameters: Dict = None):
        r"""
        Define geodesic equations.

        Args:
            parameters:
                dictionary of model parameter values to be used for
                equation substitutions

        Attributes:
            gstar_ij_tanbeta_mat (`Matrix`_):
                :math:`\dots`

            g_ij_tanbeta_mat (`Matrix`_):
                :math:`\dots`

            tanbeta_poly_eqn (:class:`~sympy.core.relational.Equality`):
                :math:`\dots` where :math:`a := \tan\alpha`

            tanbeta_eqn (:class:`~sympy.core.relational.Equality`):
                :math:`\tan{\left(\beta \right)} = \dots` where
                :math:`a := \tan\alpha`

            gstar_ij_tanalpha_mat (`Matrix`_):
                a symmetric tensor with components (using shorthand
                :math:`a := \tan\alpha`)

                :math:`g^*[1,1] = \dots`

                :math:`g^*[1,2] = g^*[2,1] = \dots`

                :math:`g^*[2,2] = \dots`

            gstar_ij_mat (`Matrix`_):
                a symmetric tensor with components
                (using shorthand :math:`a := \tan\alpha`, and with a
                particular choice of model parameters)

                :math:`g^*[1,1] = \dots`

                :math:`g^*[1,2] = g^*[2,1] = \dots`

                :math:`g^*[2,2] =  \dots`

            g_ij_tanalpha_mat (`Matrix`_):
                a symmetric tensor with components (using shorthand
                :math:`a := \tan\alpha`)

                :math:`g[1,1] = \dots`

                :math:`g[1,2] = g[2,1] = \dots`

                :math:`g[2,2] = \dots`

            g_ij_mat (`Matrix`_):
                a symmetric tensor with components
                (using shorthand :math:`a := \tan\alpha`, and with a
                particular choice of model parameters)

                :math:`g[1,1] =\dots`

                :math:`g[1,2] = g[2,1] = \dots`

                :math:`g[2,2] = \dots`

            g_ij_mat_lambdified   (function) :
                lambdified version of `g_ij_mat`

            gstar_ij_mat_lambdified (function) :
                lambdified version of `gstar_ij_mat`
        """
        logging.info("gme.core.geodesic.prep_geodesic_eqns")
        self.gstar_ij_tanbeta_mat = None
        self.g_ij_tanbeta_mat = None
        self.tanbeta_poly_eqn = None
        self.tanbeta_eqn = None
        self.gstar_ij_tanalpha_mat = None
        self.gstar_ij_mat = None
        self.g_ij_tanalpha_mat = None
        self.g_ij_mat = None
        self.g_ij_mat_lambdified = None
        self.gstar_ij_mat_lambdified = None

        mu_eta_sub = {mu: self.mu_, eta: self.eta_}

        # if parameters is None: return
        H_ = self.H_eqn.rhs.subs(mu_eta_sub)

        # Assume indexing here ranges in [1,2]
        def p_i_lambda(i):
            return [px, pz][i - 1]

        # r_i_lambda = lambda i: [rx, rz][i-1]
        # rdot_i_lambda = lambda i: [rdotx, rdotz][i-1]

        def gstar_ij_lambda(i, j):
            return simplify(
                Rational(2, 2) * diff(diff(H_, p_i_lambda(i)), p_i_lambda(j)))

        gstar_ij_mat = Matrix([
            [gstar_ij_lambda(1, 1),
             gstar_ij_lambda(2, 1)],
            [gstar_ij_lambda(1, 2),
             gstar_ij_lambda(2, 2)],
        ])
        gstar_ij_pxpz_mat = gstar_ij_mat.subs({varphi_r(rvec): varphi})
        g_ij_pxpz_mat = gstar_ij_mat.inv().subs({varphi_r(rvec): varphi})

        cosbeta_eqn = Eq(cos(beta), 1 / sqrt(1 + tan(beta)**2))
        sinbeta_eqn = Eq(sin(beta), sqrt(1 - 1 / (1 + tan(beta)**2)))
        sintwobeta_eqn = Eq(sin(2 * beta), cos(beta)**2 - sin(beta)**2)

        self.gstar_ij_tanbeta_mat = expand_trig(
            simplify(gstar_ij_pxpz_mat.subs(e2d(
                self.px_pz_tanbeta_eqn)))).subs(e2d(cosbeta_eqn))
        self.g_ij_tanbeta_mat = expand_trig(
            simplify(g_ij_pxpz_mat.subs(e2d(self.px_pz_tanbeta_eqn)))).subs(
                e2d(cosbeta_eqn))

        tanalpha_beta_eqn = self.tanalpha_beta_eqn.subs(mu_eta_sub)
        tanbeta_poly_eqn = Eq(
            numer(tanalpha_beta_eqn.rhs) -
            tanalpha_beta_eqn.lhs * denom(tanalpha_beta_eqn.rhs),
            0,
        ).subs({tan(alpha): ta})

        tanbeta_eqn = Eq(tan(beta), solve(tanbeta_poly_eqn, tan(beta))[0])
        self.tanbeta_poly_eqn = tanbeta_poly_eqn
        self.tanbeta_eqn = tanbeta_eqn

        # Replace all refs to beta with refs to alpha
        self.gstar_ij_tanalpha_mat = (self.gstar_ij_tanbeta_mat.subs(
            e2d(sintwobeta_eqn)).subs(e2d(sinbeta_eqn)).subs(
                e2d(cosbeta_eqn)).subs(e2d(tanbeta_eqn))).subs(mu_eta_sub)
        self.gstar_ij_mat = (self.gstar_ij_tanalpha_mat.subs({
            ta: tan(alpha)
        }).subs(e2d(self.tanalpha_rdot_eqn)).subs(
            e2d(self.varphi_rx_eqn.subs(
                {varphi_r(rvec): varphi}))).subs(parameters)).subs(mu_eta_sub)
        self.g_ij_tanalpha_mat = (expand_trig(self.g_ij_tanbeta_mat).subs(
            e2d(sintwobeta_eqn)).subs(e2d(sinbeta_eqn)).subs(
                e2d(cosbeta_eqn)).subs(e2d(tanbeta_eqn))).subs(mu_eta_sub)
        self.g_ij_mat = (self.g_ij_tanalpha_mat.subs({
            ta: rdotz / rdotx
        }).subs(e2d(self.varphi_rx_eqn.subs(
            {varphi_r(rvec): varphi}))).subs(parameters)).subs(mu_eta_sub)
        self.g_ij_mat_lambdified = lambdify((rx, rdotx, rdotz, varepsilon),
                                            self.g_ij_mat, "numpy")
        self.gstar_ij_mat_lambdified = lambdify((rx, rdotx, rdotz, varepsilon),
                                                self.gstar_ij_mat, "numpy")
Exemplo n.º 28
0
m2_2 = G[:,[0,2]]
m2 = m2_1.row_join(m2_2)
m2_3 = G[:,[0,1]]
m2 = m2.row_join(m2_3)
print(m2_1)
print(m2_2)
print(m2_3)

# combine order one and two minors

print('---All poles---')
m1count = np.shape(m1)[0]
#find out how many roots there are in total between all 1st order minors
n1Roots = 0
for m in range(m1count):
    n1Roots = n1Roots + sp.degree(sp.denom(m1[m]),s)

#find out how many roots there are in total between all 2nd order minors
n2Roots = 0
r,c = np.shape(m2)
for i in range(r):
    for j in range(c):
        n2Roots = n2Roots + sp.degree(sp.denom(m2[i,j]),s)
print(n2Roots)

# calculate and find common roots 
roots_denom = [None]*(n1Roots + n2Roots)
n = 0
for m in range(m1count):
    denom_roots = sp.solve(sp.denom(m1[m]))
    for i  in range(len(denom_roots)):
Exemplo n.º 29
0
 def round(self, ndigits=0):
   """Returns a new `Decimal` rounded to this many decimal places."""
   scale = sympy.Integer(10 ** ndigits)
   numer = sympy.numer(self.value) * scale
   denom = sympy.denom(self.value)
   return Decimal(int(round(numer / denom)) / scale)
Exemplo n.º 30
0
def parametric_differentiation(f,
                               g,
                               dependent_variable,
                               n,
                               simplification_method='None'):
    '''
    Performs differentiation on two parametric equations.
    
    Parameters
    ----------
    f: Sympy Mul
        A Sympy Mul object containing the first parametric equation.
        
    g: Sympy Mul
        A Sympy Mul object containing the second parametric equation.
        
    dependent_variable: Sympy Symbol
        Dependent variable.
    n: integer
        Order of differentiation.
        
    simplification_method: str (or list if method is 'collect'), optional
        Simplification method to be applied to the final answer.
        
    Example
    -------
    >> t = sym.symbols('t')
    >> x = t ** 3 - 3 * t ** 2
    >> y = t ** 4 - 8 * t ** 2
    >> parametric_differentiation(f = x, g = y, 
                                  dependent_variable = t, n = 3)
    
    >> t = sym.symbols('t')
    >> x = sin(t)
    >> y = cos(t)
    >> parametric_differentiation(f = x, g = y, 
                                  dependent_variable = t, n = 2,
                                  simplification_method = 'simplify')
    '''

    t = dependent_variable
    # check that a positive integer
    if np.mod(n, 1) != 0 or n < 0:
        raise ValueError('n must be a positive integer')
    else:
        if n == 1:
            para_derivative = sym.diff(g, t) / sym.diff(f, t)
        else:
            # perform the normal differentiation recurssively
            para_derivative = sym.diff(
                parametric_differentiation(g, f, t, n - 1), t) / sym.diff(
                    f, t)
    numerator, denominator = sym.numer(para_derivative), sym.denom(
        para_derivative)
    # perform simplification according to the simplification method specfied
    if simplification_method == 'None':
        result = sym.factor(numerator) / sym.factor(denominator)
    elif simplification_method == 'simplify':
        result = sym.simplify(numerator) / sym.simplify(denominator)
    elif simplification_method == 'factor':
        result = sym.factor(numerator) / sym.factor(denominator)
    elif simplification_method == 'expand':
        result = sym.expand(numerator) / sym.expand(denominator)
    elif 'collect' in simplification_method:
        # stop and return an error if simplification method is not a list
        if not isinstance(simplification_method, list):
            raise ValueError(
                'Specifiy the simplification_method argument as a list.')
        result = sym.collect(numerator,
                             simplification_method[1]) / sym.collect(
                                 denominator, simplification_method[1])
    elif simplification_method == 'together':
        result = sym.together(numerator) / sym.together(denominator)
    elif simplification_method == 'cancel':
        result = sym.cancel(numerator) / sym.cancel(denominator)
    else:
        raise ValueError(
            "%s is an invalid value for the argument 'simplification_method'" %
            (simplification_method))
    return result
Exemplo n.º 31
0
	def simplify(self):
		self._tuple = tuple(sympy.factor(ex) for ex in self._tuple)
		m = functools.reduce(lambda x, y: x * sympy.denom(y), self._tuple, 1)
		self._tuple = tuple(ex * m for ex in self._tuple)
		d = functools.reduce(sympy.gcd, self._tuple)
		self._tuple = tuple(sympy.factor(ex / d) for ex in self._tuple)
Exemplo n.º 32
0
    def define_px_poly_eqn(
        self, eta_choice: Rational = None, do_ndim: bool = False
    ) -> None:
        r"""
        Define :math:`p_x` polynomial.

        TODO: remove ref to xiv_0

        Define polynomial form of function combining normal-slowness
        covector components :math:`(p_x,p_z)`
        (where the latter is given in terms of the vertical erosion rate
        :math:`\xi^{\downarrow} = -\dfrac{1}{p_z}`)
        and the erosion model flow component :math:`\varphi(\mathbf{r})`

        Args:
            eta_choice (:class:`~sympy.core.numbers.Rational`):
                value of :math:`\eta` to use instead value given at
                instantiation; otherwise the latter value is used

        Attributes:
            poly_px_xiv_varphi_eqn (:class:`~sympy.polys.polytools.Poly`):
                :math:`\operatorname{Poly}{\left(
                \left(\xi^{\downarrow}\right)^{4}
                \varphi^{4}{\left(\mathbf{r} \right)} p_{x}^{6}
                -  \left(\xi^{\downarrow}\right)^{4} p_{x}^{2}
                -  \left(\xi^{\downarrow}\right)^{2}, p_{x},
                domain=\mathbb{Z}\left[\varphi{\left(\mathbf{r} \right)},
                \xi^{\downarrow}\right] \right)}`

            poly_px_xiv_eqn (:class:`~sympy.core.relational.Equality`):
                :math:`\varphi_0^{4}
                \left(\xi^{\downarrow{0}}\right)^{4} p_{x}^{6}
                \left(\varepsilon
                + \left(\frac{x_{1} - {r}^x}{x_{1}}\right)^{2 \mu}\right)^{4}
                - \left(\xi^{\downarrow{0}}\right)^{4} p_{x}^{2}
                - \left(\xi^{\downarrow{0}}\right)^{2} = 0`
        """
        logging.info(f"gme.core.pxpoly.define_px_poly_eqn (ndim={do_ndim})")
        if do_ndim:
            # Non-dimensionalized version
            varphi0_solns = solve(
                self.sinCi_xih0_eqn.subs({eta: eta_choice}), varphi_0
            )
            varphi0_eqn = Eq(varphi_0, varphi0_solns[0])
            if eta_choice is not None and eta_choice <= 1:
                tmp_eqn = separatevars(
                    simplify(
                        self.px_xiv_varphi_eqn.subs({eta: eta_choice})
                        .subs({varphi_r(rvec): self.varphi_rxhat_eqn.rhs})
                        .subs(e2d(self.px_pxhat_eqn))
                        .subs(e2d(varphi0_eqn))
                    )
                )
                self.poly_pxhat_xiv_eqn = simplify(
                    Eq(
                        (
                            numer(tmp_eqn.lhs)
                            - denom(tmp_eqn.lhs) * (tmp_eqn.rhs)
                        )
                        / xiv ** 2,
                        0,
                    )
                )
                self.poly_pxhat_xiv0_eqn = self.poly_pxhat_xiv_eqn.subs(
                    {xiv: xiv_0}
                ).subs(e2d(self.xiv0_xih0_Ci_eqn))
            else:
                tmp_eqn = separatevars(
                    simplify(
                        self.px_xiv_varphi_eqn.subs({eta: eta_choice})
                        .subs({varphi_r(rvec): self.varphi_rxhat_eqn.rhs})
                        .subs(e2d(self.px_pxhat_eqn))
                        .subs(e2d(varphi0_eqn))
                    )
                )
                self.poly_pxhat_xiv_eqn = simplify(
                    Eq(
                        (
                            numer(tmp_eqn.lhs)
                            - denom(tmp_eqn.lhs) * (tmp_eqn.rhs)
                        )
                        / xiv ** 2,
                        0,
                    )
                )
                self.poly_pxhat_xiv0_eqn = simplify(
                    Eq(
                        self.poly_pxhat_xiv_eqn.lhs.subs({xiv: xiv_0}).subs(
                            e2d(self.xiv0_xih0_Ci_eqn)
                        )
                        / xih_0 ** 2,
                        0,
                    )
                )
        else:
            # Dimensioned version
            tmp_eqn = simplify(self.px_xiv_varphi_eqn.subs({eta: eta_choice}))
            if eta_choice is not None and eta_choice <= 1:
                self.poly_px_xiv_varphi_eqn = poly(tmp_eqn.lhs, px)
            else:
                self.poly_px_xiv_varphi_eqn = poly(
                    numer(tmp_eqn.lhs) - denom(tmp_eqn.lhs) * (tmp_eqn.rhs), px
                )
            self.poly_px_xiv_eqn = Eq(
                self.poly_px_xiv_varphi_eqn.subs(e2d(self.varphi_rx_eqn)), 0
            )
        if G[r, c] != 0:
            m1.append(G[r, c])
            print G[r, c]

print '---Minors of order 2---'
m2_1 = G[:,[1,2]]
m2_2 = G[:,[0,2]]
m2_3 = G[:,[0,1]]
print m2_1
print m2_2
print m2_3

print '---All poles---'
m1count = np.shape(m1)[0]
for m in range(0, m1count):
    print sp.solve(sp.denom(m1[m]))

def M21(s):
    return G[:,[1,2]]
def M12(s):
    return G[:,[0,1]]
def M13(s):
    return G[:,[0,1]]
    
print poles(M21)
print poles(M12)
print poles(M13)

print 'Therefore the poles are -1, 1 and -2'

##Usefull Sage example
Exemplo n.º 34
0
def apart_fact(Fs):
    S=0
    Ls = apart(Fs).as_ordered_terms()
    for l in Ls:
        S += numer(l)/factor(denom(l))
    return expand_mul(S)
Exemplo n.º 35
0
 def export(self, x):
     return float(sp.numer(x)) / sp.denom(x)
Exemplo n.º 36
0
def differential_constants(model, p1, p2, p3):
    """
    Description:
    This function calculates the differential constants u and q necessary to calculate the tip sample interaction
    force.
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Parameters:
    :param model:   string
                    Model name, e.g. 'Gen. Kelvin Voigt', 'Gen. Maxwell'
    :param p1:      float
                    Either Ge or Jg
    :param p2:      array of floats
                    Either G or J
    :param pe:      array of floats
                    tau - charactersitic times
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Return, function output:
    retrun:         u:  array of floats
                        differential constants u0, u1, ... un
                    q:  array of floats
                        differential constants q0, q1, ... qn
    """
    s = sym.symbols('s')

    if model == 'Gen. Kelvin-Voigt':
        if len(p2) == len(p3):  # checks J and tau are same lenght
            U = p1 + sum(p2[:] / (1.0 + p3[:] * s))
            U_n = (U).normal()  # writes retardance with common denominator

            u_n = sym.numer(U_n)  # selects the numerator
            u_n = sym.expand(u_n)  # expands each term
            u_n = sym.collect(
                u_n, s)  # collect the terms with the same exponent of s

            q_n = sym.denom(U_n)  # selects the denominator
            q_n = sym.expand(q_n)  # expands each term
            q_n = sym.collect(
                q_n, s)  # collect the terms with the same exponent of s

            q_arr = np.zeros(
                len(p2) +
                1)  # initializes array with lenght J, tau + 1 to store q
            u_arr = np.zeros(
                len(p2) +
                1)  # initializes array with lenght J, tau + 1 to store u

            for i in range(len(p2) + 1):
                q_arr[i] = q_n.coeff(
                    s, i
                )  # selects the terms multiplied by s^n which are synonymus for q0, .., qn
                u_arr[i] = u_n.coeff(
                    s, i
                )  # selects the terms multiplied by s^n which are synonymus for u0, .., un
        else:
            print('input arrays have unequal length')

    if model == 'Gen. Maxwell':
        if len(p2) == len(p3):
            Q = p1 + sum((p2[:] * p3[:]) / (1.0 + p3[:] * s))
            Q_n = (Q).normal()  # writes retardance with common denominator

            u_n = sym.denom(Q_n)  # selects the denominator
            u_n = sym.expand(u_n)  # expands each term
            u_n = sym.collect(
                u_n, s)  # collect the terms with the same exponent of s

            q_n = sym.numer(Q_n)  # selects the numerator
            q_n = sym.expand(q_n)  # expands each term
            q_n = sym.collect(
                q_n, s)  # collect the terms with the same exponent of s

            q_arr = np.zeros(
                len(p2) +
                1)  # initializes array with lenght J, tau + 1 to store q
            u_arr = np.zeros(
                len(p2) +
                1)  # initializes array with lenght J, tau + 1 to store u

            for i in range(len(p2) + 1):
                q_arr[i] = q_n.coeff(
                    s, i
                )  # selects the terms multiplied by s^n which are synonymus for q0, .., qn
                u_arr[i] = u_n.coeff(
                    s, i
                )  # selects the terms multiplied by s^n which are synonymus for u0, .., un
        else:
            print('input arrays have unequal length')

    return u_arr, q_arr
Exemplo n.º 37
0
def symmetryDetection(allVariables,
                      diffEquations,
                      observables,
                      obsFunctions,
                      initFunctions,
                      predictions,
                      predFunctions,
                      ansatz='uni',
                      pMax=2,
                      inputs=[],
                      fixed=[],
                      parallel=1,
                      allTrafos=False,
                      timeTrans=False,
                      pretty=True,
                      suffix=''):

    n = len(allVariables)
    m = len(diffEquations)
    h = len(observables)

    ###########################################################################################
    #############################     prepare equations    ####################################
    ###########################################################################################
    sys.stdout.write('Preparing equations...')
    sys.stdout.flush()

    # make infinitesimal ansatz
    infis, diffInfis, rs = makeAnsatz(ansatz, allVariables, m, len(inputs),
                                      pMax, fixed)

    # get infinitesimals of time transformation
    if timeTrans:
        rs.append(spy.var('r_T_1'))
        diffInfiT = rs[-1]
        allVariables += [T]
    else:
        diffInfiT = None

    # and convert to polynomial
    infis, diffInfis = transformInfisToPoly(infis, diffInfis, allVariables, rs,
                                            parallel, ansatz)

    diffInfiT = Apoly(diffInfiT, allVariables, rs)

    ### extract numerator and denominator of equations
    #differential equations
    numerators = [0] * m
    denominators = [0] * m
    for k in range(m):
        rational = spy.together(diffEquations[k])
        numerators[k] = Apoly(spy.numer(rational), allVariables, None)
        denominators[k] = Apoly(spy.denom(rational), allVariables, None)

    #observation functions
    obsNumerators = [0] * h
    obsDenominatros = [0] * h
    for k in range(h):
        rational = spy.together(obsFunctions[k])
        obsNumerators[k] = Apoly(spy.numer(rational), allVariables, None)
        obsDenominatros[k] = Apoly(spy.denom(rational), allVariables, None)

    #initial functions
    if len(initFunctions) != 0:
        initNumerators = [0] * m
        initDenominatros = [0] * m
        for k in range(m):
            rational = spy.together(initFunctions[k])
            initNumerators[k] = Apoly(spy.numer(rational), allVariables, None)
            initDenominatros[k] = Apoly(spy.denom(rational), allVariables,
                                        None)
    else:
        initNumerators = []
        initDenominatros = []

    ### calculate numerator of derivatives of equations
    #differential equatioins
    derivativesNum = [0] * m
    for i in range(m):
        derivativesNum[i] = [0] * n
    for k in range(m):
        for l in range(n):
            derivativesNum[k][l] = Apoly(None, allVariables, None)
            derivativesNum[k][l].add(numerators[k].diff(l).mul(
                denominators[k]))
            derivativesNum[k][l].sub(numerators[k].mul(
                denominators[k].diff(l)))

    #observation functions
    obsDerivativesNum = [0] * h
    for i in range(h):
        obsDerivativesNum[i] = [0] * n
    for k in range(h):
        for l in range(n):
            obsDerivativesNum[k][l] = Apoly(None, allVariables, None)
            obsDerivativesNum[k][l].add(obsNumerators[k].diff(l).mul(
                obsDenominatros[k]))
            obsDerivativesNum[k][l].sub(obsNumerators[k].mul(
                obsDenominatros[k].diff(l)))

    #initial functions
    if len(initFunctions) != 0:
        initDerivativesNum = [0] * len(initFunctions)
        for i in range(m):
            initDerivativesNum[i] = [0] * n
        for k in range(m):
            for l in range(n):
                initDerivativesNum[k][l] = Apoly(None, allVariables, None)
                initDerivativesNum[k][l].add(initNumerators[k].diff(l).mul(
                    initDenominatros[k]))
                initDerivativesNum[k][l].sub(initNumerators[k].mul(
                    initDenominatros[k].diff(l)))
    else:
        initDerivativesNum = []

    sys.stdout.write('\rPreparing equations...done\n')
    sys.stdout.flush()

    ###########################################################################################
    ############################     build linear system    ###################################
    ###########################################################################################
    sys.stdout.write('\nBuilding system...')
    sys.stdout.flush()

    rSystem = buildSystem(numerators, denominators, derivativesNum,
                          obsDerivativesNum, initDenominatros,
                          initDerivativesNum, initFunctions, infis, diffInfis,
                          diffInfiT, allVariables, rs, parallel, ansatz)

    sys.stdout.write('done\n')
    sys.stdout.flush()

    ###########################################################################################
    ##############################     solve system    ########################################
    ###########################################################################################
    sys.stdout.write('\nSolving system of size ' + str(rSystem.shape[0]) + 'x' +\
         str(rSystem.shape[1]) + '...')
    sys.stdout.flush()

    #get LU decomposition from scipy
    rSystem = scipy.linalg.lu(rSystem, permute_l=True)[1]

    #calculate reduced row echelon form
    rSystem, pivots = getrref(rSystem)

    sys.stdout.write('done\n')
    sys.stdout.flush()

    ###########################################################################################
    #############################     process results    ######################################
    ###########################################################################################
    sys.stdout.write('\nProcessing results...')
    sys.stdout.flush()

    # calculate solution space
    sys.stdout.write('\n  calculating solution space')
    sys.stdout.flush()
    baseMatrix = nullSpace(rSystem, pivots)

    #substitute solutions into infinitesimals
    #(and remove the ones with common parameter factors)
    sys.stdout.write('\n  substituting solutions')
    sys.stdout.flush()
    infisAll = []
    for l in range(baseMatrix.shape[1]):
        infisTmp = [0] * n
        for i in range(len(infis)):
            infisTmp[i] = infis[i].getCopy()
            infisTmp[i].rs = baseMatrix[:, l]
            infisTmp[i] = infisTmp[i].as_expr()
        if timeTrans:
            infisTmp.append(baseMatrix[-1, l] * T)

        if allTrafos:
            infisAll.append(infisTmp)
        else:
            if not checkForCommonFactor(infisTmp, allVariables, m):
                infisAll.append(infisTmp)

    print('')
    sys.stdout.write('done\n')
    sys.stdout.flush()

    # print transformations
    print('\n\n')
    if len(infisAll) != 0:
        printTransformations(infisAll, allVariables, pretty, suffix)

    ###########################################################################################
    ############################     check predictions    #####################################
    ###########################################################################################
    if predictions != False:
        checkPredictions(predictions, predFunctions, infisAll, allVariables)

    print(
        time.strftime('\nTotal time: %Hh:%Mm:%Ss',
                      time.gmtime(time.time() - t0)))
Exemplo n.º 38
0
def gen_lobatto(max_order):
    assert max_order > 2

    x = sm.symbols('x')

    lobs = [0, 1]
    lobs[0] = (1 - x) / 2
    lobs[1] = (1 + x) / 2

    dlobs = [lob.diff('x') for lob in lobs]

    legs = [sm.legendre(0, 'y')]
    clegs = [sm.ccode(legs[0])]
    dlegs = [sm.legendre(0, 'y').diff('y')]
    cdlegs = [sm.ccode(dlegs[0])]

    clobs = [sm.ccode(lob) for lob in lobs]
    cdlobs = [sm.ccode(dlob) for dlob in dlobs]

    denoms = [] # for lobs.

    for ii in range(2, max_order + 1):
        coef = sm.sympify('sqrt(2 * (2 * %s - 1)) / 2' % ii)
        leg = sm.legendre(ii - 1, 'y')

        pleg = leg.as_poly()
        coefs = pleg.all_coeffs()
        denom = max(sm.denom(val) for val in coefs)

        cleg = sm.ccode(sm.horner(leg*denom)/denom)

        dleg = leg.diff('y')
        cdleg = sm.ccode(sm.horner(dleg*denom)/denom)

        lob = sm.simplify(coef * sm.integrate(leg, ('y', -1, x)))
        lobnc = sm.simplify(sm.integrate(leg, ('y', -1, x)))

        plobnc = lobnc.as_poly()
        coefs = plobnc.all_coeffs()
        denom = sm.denom(coef) * max(sm.denom(val) for val in coefs)

        clob = sm.ccode(sm.horner(lob*denom)/denom)

        dlob = lob.diff('x')
        cdlob = sm.ccode(sm.horner(dlob*denom)/denom)

        legs.append(leg)
        clegs.append(cleg)
        dlegs.append(dleg)
        cdlegs.append(cdleg)
        lobs.append(lob)
        clobs.append(clob)
        dlobs.append(dlob)
        cdlobs.append(cdlob)
        denoms.append(denom)

    coef = sm.sympify('sqrt(2 * (2 * %s - 1)) / 2' % (max_order + 1))
    leg = sm.legendre(max_order, 'y')

    pleg = leg.as_poly()
    coefs = pleg.all_coeffs()
    denom = max(sm.denom(val) for val in coefs)

    cleg = sm.ccode(sm.horner(leg*denom)/denom)

    dleg = leg.diff('y')
    cdleg = sm.ccode(sm.horner(dleg*denom)/denom)

    legs.append(leg)
    clegs.append(cleg)
    dlegs.append(dleg)
    cdlegs.append(cdleg)

    kerns = []
    ckerns = []
    dkerns = []
    cdkerns = []
    for ii, lob in enumerate(lobs[2:]):
        kern = sm.simplify(lob / (lobs[0] * lobs[1]))
        dkern = kern.diff('x')

        denom = denoms[ii] / 4
        ckern = sm.ccode(sm.horner(kern*denom)/denom)
        cdkern = sm.ccode(sm.horner(dkern*denom)/denom)

        kerns.append(kern)
        ckerns.append(ckern)
        dkerns.append(dkern)
        cdkerns.append(cdkern)

    return (legs, clegs, dlegs, cdlegs,
            lobs, clobs, dlobs, cdlobs,
            kerns, ckerns, dkerns, cdkerns,
            denoms)
Exemplo n.º 39
0
def approximants(l, X=Symbol('x'), simplify=False):
    """
    Return a generator for consecutive Pade approximants for a series.
    It can also be used for computing the rational generating function of a
    series when possible, since the last approximant returned by the generator
    will be the generating function (if any).

    The input list can contain more complex expressions than integer or rational
    numbers; symbols may also be involved in the computation. An example below
    show how to compute the generating function of the whole Pascal triangle.

    The generator can be asked to apply the sympy.simplify function on each
    generated term, which will make the computation slower; however it may be
    useful when symbols are involved in the expressions.

    Examples
    ========

    >>> from sympy.series import approximants
    >>> from sympy import lucas, fibonacci, symbols, binomial
    >>> g = [lucas(k) for k in range(16)]
    >>> [e for e in approximants(g)]
    [2, -4/(x - 2), (5*x - 2)/(3*x - 1), (x - 2)/(x**2 + x - 1)]

    >>> h = [fibonacci(k) for k in range(16)]
    >>> [e for e in approximants(h)]
    [x, -x/(x - 1), (x**2 - x)/(2*x - 1), -x/(x**2 + x - 1)]

    >>> x, t = symbols("x,t")
    >>> p=[sum(binomial(k,i)*x**i for i in range(k+1)) for k in range(16)]
    >>> y = approximants(p, t)
    >>> for k in range(3): print(next(y))
    1
    (x + 1)/((-x - 1)*(t*(x + 1) + (x + 1)/(-x - 1)))
    nan

    >>> y = approximants(p, t, simplify=True)
    >>> for k in range(3): print(next(y))
    1
    -1/(t*(x + 1) - 1)
    nan

    See Also
    ========
    See function sympy.concrete.guess.guess_generating_function_rational and
    function mpmath.pade

    """
    p1, q1 = [Integer(1)], [Integer(0)]
    p2, q2 = [Integer(0)], [Integer(1)]
    while len(l):
        b = 0
        while l[b] == 0:
            b += 1
            if b == len(l):
                return
        m = [Integer(1) / l[b]]
        for k in range(b + 1, len(l)):
            s = 0
            for j in range(b, k):
                s -= l[j + 1] * m[b - j - 1]
            m.append(s / l[b])
        l = m
        a, l[0] = l[0], 0
        p = [0] * max(len(p2), b + len(p1))
        q = [0] * max(len(q2), b + len(q1))
        for k in range(len(p2)):
            p[k] = a * p2[k]
        for k in range(b, b + len(p1)):
            p[k] += p1[k - b]
        for k in range(len(q2)):
            q[k] = a * q2[k]
        for k in range(b, b + len(q1)):
            q[k] += q1[k - b]
        while p[-1] == 0:
            p.pop()
        while q[-1] == 0:
            q.pop()
        p1, p2 = p2, p
        q1, q2 = q2, q

        # yield result
        from sympy import denom, lcm, simplify as simp
        c = 1
        for x in p:
            c = lcm(c, denom(x))
        for x in q:
            c = lcm(c, denom(x))
        out = (sum(c * e * X**k
                   for k, e in enumerate(p)) / sum(c * e * X**k
                                                   for k, e in enumerate(q)))
        if simplify: yield (simp(out))
        else: yield out
    return
Exemplo n.º 40
0
def gen_lobatto(max_order):
    assert max_order > 2

    x = sm.symbols('x')

    lobs = [0, 1]
    lobs[0] = (1 - x) / 2
    lobs[1] = (1 + x) / 2

    dlobs = [lob.diff('x') for lob in lobs]

    legs = [sm.legendre(0, 'y')]
    clegs = [sm.ccode(legs[0])]
    dlegs = [sm.legendre(0, 'y').diff('y')]
    cdlegs = [sm.ccode(dlegs[0])]

    clobs = [sm.ccode(lob) for lob in lobs]
    cdlobs = [sm.ccode(dlob) for dlob in dlobs]

    denoms = []  # for lobs.

    for ii in range(2, max_order + 1):
        coef = sm.sympify('sqrt(2 * (2 * %s - 1)) / 2' % ii)
        leg = sm.legendre(ii - 1, 'y')

        pleg = leg.as_poly()
        coefs = pleg.all_coeffs()
        denom = max(sm.denom(val) for val in coefs)

        cleg = sm.ccode(sm.horner(leg * denom) / denom)

        dleg = leg.diff('y')
        cdleg = sm.ccode(sm.horner(dleg * denom) / denom)

        lob = sm.simplify(coef * sm.integrate(leg, ('y', -1, x)))
        lobnc = sm.simplify(sm.integrate(leg, ('y', -1, x)))

        plobnc = lobnc.as_poly()
        coefs = plobnc.all_coeffs()
        denom = sm.denom(coef) * max(sm.denom(val) for val in coefs)

        clob = sm.ccode(sm.horner(lob * denom) / denom)

        dlob = lob.diff('x')
        cdlob = sm.ccode(sm.horner(dlob * denom) / denom)

        legs.append(leg)
        clegs.append(cleg)
        dlegs.append(dleg)
        cdlegs.append(cdleg)
        lobs.append(lob)
        clobs.append(clob)
        dlobs.append(dlob)
        cdlobs.append(cdlob)
        denoms.append(denom)

    coef = sm.sympify('sqrt(2 * (2 * %s - 1)) / 2' % (max_order + 1))
    leg = sm.legendre(max_order, 'y')

    pleg = leg.as_poly()
    coefs = pleg.all_coeffs()
    denom = max(sm.denom(val) for val in coefs)

    cleg = sm.ccode(sm.horner(leg * denom) / denom)

    dleg = leg.diff('y')
    cdleg = sm.ccode(sm.horner(dleg * denom) / denom)

    legs.append(leg)
    clegs.append(cleg)
    dlegs.append(dleg)
    cdlegs.append(cdleg)

    kerns = []
    ckerns = []
    dkerns = []
    cdkerns = []
    for ii, lob in enumerate(lobs[2:]):
        kern = sm.simplify(lob / (lobs[0] * lobs[1]))
        dkern = kern.diff('x')

        denom = denoms[ii] / 4
        ckern = sm.ccode(sm.horner(kern * denom) / denom)
        cdkern = sm.ccode(sm.horner(dkern * denom) / denom)

        kerns.append(kern)
        ckerns.append(ckern)
        dkerns.append(dkern)
        cdkerns.append(cdkern)

    return (legs, clegs, dlegs, cdlegs, lobs, clobs, dlobs, cdlobs, kerns,
            ckerns, dkerns, cdkerns, denoms)
Exemplo n.º 41
0
def guess(l, all=False, evaluate=True, niter=2, variables=None):
    """
    This function is adapted from the Rate.m package for Mathematica
    written by Christian Krattenthaler.
    It tries to guess a formula from a given sequence of rational numbers.

    In order to speed up the process, the 'all' variable is set to False by
    default, stopping the computation as some results are returned during an
    iteration; the variable can be set to True if more iterations are needed
    (other formulas may be found; however they may be equivalent to the first
    ones).

    Another option is the 'evaluate' variable (default is True); setting it
    to False will leave the involved products unevaluated.

    By default, the number of iterations is set to 2 but a greater value (up
    to len(l)-1) can be specified with the optional 'niter' variable.
    More and more convoluted results are found when the order of the
    iteration gets higher:

      * first iteration returns polynomial or rational functions;
      * second iteration returns products of rising factorials and their
        inverses;
      * third iteration returns products of products of rising factorials
        and their inverses;
      * etc.

    The returned formulas contain symbols i0, i1, i2, ... where the main
    variables is i0 (and auxiliary variables are i1, i2, ...). A list of
    other symbols can be provided in the 'variables' option; the length of
    the least should be the value of 'niter' (more is acceptable but only
    the first symbols will be used); in this case, the main variable will be
    the first symbol in the list.

    >>> from sympy.concrete.guess import guess
    >>> guess([1,2,6,24,120], evaluate=False)
    [Product(i1 + 1, (i1, 1, i0 - 1))]

    >>> from sympy import symbols
    >>> r = guess([1,2,7,42,429,7436,218348,10850216], niter=4)
    >>> i0 = symbols("i0")
    >>> [r[0].subs(i0,n).doit() for n in range(1,10)]
    [1, 2, 7, 42, 429, 7436, 218348, 10850216, 911835460]
    """
    if any(a==0 for a in l[:-1]):
        return []
    N = len(l)
    niter = min(N-1, niter)
    myprod = product if evaluate else Product
    g = []
    res = []
    if variables == None:
        symb = symbols('i:'+str(niter))
    else:
        symb = variables
    for k, s in enumerate(symb):
        g.append(l)
        n, r = len(l), []
        for i in range(n-2-1, -1, -1):
            ri = rinterp(enumerate(g[k][:-1], start=1), i, X=s)
            if ((denom(ri).subs({s:n}) != 0)
                    and (ri.subs({s:n}) - g[k][-1] == 0)
                    and ri not in r):
              r.append(ri)
        if r:
            for i in range(k-1, -1, -1):
                r = list(map(lambda v: g[i][0]
                      * myprod(v, (symb[i+1], 1, symb[i]-1)), r))
            if not all: return r
            res += r
        l = [Rational(l[i+1], l[i]) for i in range(N-k-1)]
    return res
# In[7]:

G = K/(tau**2*s**2 + 2*tau*zeta*s + 1)
G


# In[8]:

invL(G)


# The characteristic equation is the denominator of the transfer function

# In[5]:

ce = sympy.Eq(sympy.denom(G), 0)
ce


# In[6]:

roots = sympy.roots(ce, s)
roots


# The shape of the inverse Laplace depends on the nature of the roots, which depends on the value of $\zeta$

# Overdamped: $\zeta>1$. Two distinct real roots

# In[3]:
Exemplo n.º 43
0
def find_simple_recurrence_vector(l):
    """
    This function is used internally by other functions from the
    sympy.concrete.guess module. While most users may want to rather use the
    function find_simple_recurrence when looking for recurrence relations
    among rational numbers, the current function may still be useful when
    some post-processing has to be done.

    The function returns a vector of length n when a recurrence relation of
    order n is detected in the sequence of rational numbers v.

    If the returned vector has a length 1, then the returned value is always
    the list [0], which means that no relation has been found.

    While the functions is intended to be used with rational numbers, it should
    work for other kinds of real numbers except for some cases involving
    quadratic numbers; for that reason it should be used with some caution when
    the argument is not a list of rational numbers.

    Examples
    ========

    >>> from sympy.concrete.guess import find_simple_recurrence_vector
    >>> from sympy import fibonacci
    >>> find_simple_recurrence_vector([fibonacci(k) for k in range(12)])
    [1, -1, -1]

    See also
    ========

    See the function sympy.concrete.guess.find_simple_recurrence which is more
    user-friendly.

    """
    q1 = [0]
    q2 = [Integer(1)]
    z = len(l) >> 1
    while len(q2) <= z:
        b = 0
        while l[b] == 0:
            b += 1
            if b == len(l):
                c = 1
                for x in q2:
                    c = lcm(c, denom(x))
                if q2[0] * c < 0: c = -c
                for k in range(len(q2)):
                    q2[k] = int(q2[k] * c)
                return q2
        m = [Integer(1) / l[b]]
        for k in range(b + 1, len(l)):
            s = 0
            for j in range(b, k):
                s -= l[j + 1] * m[b - j - 1]
            m.append(s / l[b])
        l = m
        a, l[0] = l[0], 0
        q = [0] * max(len(q2), b + len(q1))
        for k in range(len(q2)):
            q[k] = a * q2[k]
        for k in range(b, b + len(q1)):
            q[k] += q1[k - b]
        while q[-1] == 0:
            q.pop()  # because trailing zeros can occur
        q1, q2 = q2, q
    return [0]
Exemplo n.º 44
0
def approximants(l, X=Symbol('x'), simplify=False):
    """
    Return a generator for consecutive Pade approximants for a series.
    It can also be used for computing the rational generating function of a
    series when possible, since the last approximant returned by the generator
    will be the generating function (if any).

    The input list can contain more complex expressions than integer or rational
    numbers; symbols may also be involved in the computation. An example below
    show how to compute the generating function of the whole Pascal triangle.

    The generator can be asked to apply the sympy.simplify function on each
    generated term, which will make the computation slower; however it may be
    useful when symbols are involved in the expressions.

    Examples
    ========

    >>> from sympy.series import approximants
    >>> from sympy import lucas, fibonacci, symbols, binomial
    >>> g = [lucas(k) for k in range(16)]
    >>> [e for e in approximants(g)]
    [2, -4/(x - 2), (5*x - 2)/(3*x - 1), (x - 2)/(x**2 + x - 1)]

    >>> h = [fibonacci(k) for k in range(16)]
    >>> [e for e in approximants(h)]
    [x, -x/(x - 1), (x**2 - x)/(2*x - 1), -x/(x**2 + x - 1)]

    >>> x, t = symbols("x,t")
    >>> p=[sum(binomial(k,i)*x**i for i in range(k+1)) for k in range(16)]
    >>> y = approximants(p, t)
    >>> for k in range(3): print(next(y))
    1
    (x + 1)/((-x - 1)*(t*(x + 1) + (x + 1)/(-x - 1)))
    nan

    >>> y = approximants(p, t, simplify=True)
    >>> for k in range(3): print(next(y))
    1
    -1/(t*(x + 1) - 1)
    nan

    See also
    ========
    See function sympy.concrete.guess.guess_generating_function_rational and
    function mpmath.pade

    """
    p1, q1 = [Integer(1)], [Integer(0)]
    p2, q2 = [Integer(0)], [Integer(1)]
    while len(l):
        b = 0
        while l[b]==0:
            b += 1
            if b == len(l):
                return
        m = [Integer(1)/l[b]]
        for k in range(b+1, len(l)):
            s = 0
            for j in range(b, k):
                s -= l[j+1] * m[b-j-1]
            m.append(s/l[b])
        l = m
        a, l[0] = l[0], 0
        p = [0] * max(len(p2), b+len(p1))
        q = [0] * max(len(q2), b+len(q1))
        for k in range(len(p2)):
            p[k] = a*p2[k]
        for k in range(b, b+len(p1)):
            p[k] += p1[k-b]
        for k in range(len(q2)):
            q[k] = a*q2[k]
        for k in range(b, b+len(q1)):
            q[k] += q1[k-b]
        while p[-1]==0: p.pop()
        while q[-1]==0: q.pop()
        p1, p2 = p2, p
        q1, q2 = q2, q

        # yield result
        from sympy import denom, lcm, simplify as simp
        c = 1
        for x in p:
            c = lcm(c, denom(x))
        for x in q:
            c = lcm(c, denom(x))
        out = ( sum(c*e*X**k for k, e in enumerate(p))
              / sum(c*e*X**k for k, e in enumerate(q)) )
        if simplify: yield(simp(out))
        else: yield out
    return
Exemplo n.º 45
0
def test_issue_5933():
    from sympy import Polygon, RegularPolygon, denom
    x = Polygon(*RegularPolygon((0, 0), 1, 5).vertices).centroid.x
    assert abs(denom(x).n()) > 1e-12
    assert abs(denom(radsimp(x))) > 1e-12  # in case simplify didn't handle it
Exemplo n.º 46
0
def guess(l, all=False, evaluate=True, niter=2, variables=None):
    """
    This function is adapted from the Rate.m package for Mathematica
    written by Christian Krattenthaler.
    It tries to guess a formula from a given sequence of rational numbers.

    In order to speed up the process, the 'all' variable is set to False by
    default, stopping the computation as some results are returned during an
    iteration; the variable can be set to True if more iterations are needed
    (other formulas may be found; however they may be equivalent to the first
    ones).

    Another option is the 'evaluate' variable (default is True); setting it
    to False will leave the involved products unevaluated.

    By default, the number of iterations is set to 2 but a greater value (up
    to len(l)-1) can be specified with the optional 'niter' variable.
    More and more convoluted results are found when the order of the
    iteration gets higher:

      * first iteration returns polynomial or rational functions;
      * second iteration returns products of rising factorials and their
        inverses;
      * third iteration returns products of products of rising factorials
        and their inverses;
      * etc.

    The returned formulas contain symbols i0, i1, i2, ... where the main
    variables is i0 (and auxiliary variables are i1, i2, ...). A list of
    other symbols can be provided in the 'variables' option; the length of
    the least should be the value of 'niter' (more is acceptable but only
    the first symbols will be used); in this case, the main variable will be
    the first symbol in the list.

    Examples
    ========

    >>> from sympy.concrete.guess import guess
    >>> guess([1,2,6,24,120], evaluate=False)
    [Product(i1 + 1, (i1, 1, i0 - 1))]

    >>> from sympy import symbols
    >>> r = guess([1,2,7,42,429,7436,218348,10850216], niter=4)
    >>> i0 = symbols("i0")
    >>> [r[0].subs(i0,n).doit() for n in range(1,10)]
    [1, 2, 7, 42, 429, 7436, 218348, 10850216, 911835460]
    """
    if any(a == 0 for a in l[:-1]):
        return []
    N = len(l)
    niter = min(N - 1, niter)
    myprod = product if evaluate else Product
    g = []
    res = []
    if variables is None:
        symb = symbols('i:' + str(niter))
    else:
        symb = variables
    for k, s in enumerate(symb):
        g.append(l)
        n, r = len(l), []
        for i in range(n - 2 - 1, -1, -1):
            ri = rinterp(enumerate(g[k][:-1], start=1), i, X=s)
            if ((denom(ri).subs({s: n}) != 0)
                    and (ri.subs({s: n}) - g[k][-1] == 0) and ri not in r):
                r.append(ri)
        if r:
            for i in range(k - 1, -1, -1):
                r = list(
                    map(
                        lambda v: g[i][0] * myprod(v, (symb[i + 1], 1, symb[i]
                                                       - 1)), r))
            if not all: return r
            res += r
        l = [Rational(l[i + 1], l[i]) for i in range(N - k - 1)]
    return res
def _split_value_equally(delta, count):
  """Splits an integer or rational into roughly equal parts."""
  numer = sympy.numer(delta)
  denom = sympy.denom(delta)
  return [int(math.floor((numer + i) / count)) / denom for i in range(count)]
Exemplo n.º 48
0
hf_lp = lambdify(s, Vo_lp, 'numpy')
bode_output_lp = hf_lp(ss)
plt.loglog(ww, abs(bode_output_lp), lw=2)
plt.title("bode plot of lowpass filter")
plt.xlabel('frequency')
plt.ylabel('H(jw)')
plt.grid(True)
plt.show()

numerator_lp = [
    float(numer(Vo_lp.simplify()).coeff(s, 2)),
    float(numer(Vo_lp.simplify()).coeff(s, 1)),
    float(numer(Vo_lp.simplify()).coeff(s, 0))
]
denominator_lp = [
    float(denom(Vo_lp.simplify()).coeff(s, 2)),
    float(denom(Vo_lp.simplify()).coeff(s, 1)),
    float(denom(Vo_lp.simplify()).coeff(s, 0))
]

#1
v, t = sp.step([numerator_lp, denominator_lp], None, np.arange(0, 1e-3, 1e-6))
plt.plot(v, t)
plt.title("Step response of lowpass filter")
plt.grid(True)
plt.xlabel('t')
plt.ylabel('Vo')
plt.show()

#2
t1 = np.arange(0, 1e-2, 1e-6)
Exemplo n.º 49
0
def symmetryDetection(allVariables, diffEquations, observables, obsFunctions, initFunctions,
						predictions, predFunctions, ansatz = 'uni', pMax = 2, inputs = [], 
						fixed = [], parallel = 1, allTrafos = False, timeTrans = False,
						pretty = True, suffix=''):
	
	n = len(allVariables)
	m = len(diffEquations)
	h = len(observables)

	###########################################################################################
	#############################     prepare equations    ####################################
	###########################################################################################
	sys.stdout.write('Preparing equations...')
	sys.stdout.flush()

	# make infinitesimal ansatz
	infis, diffInfis, rs = makeAnsatz(ansatz, allVariables, m, len(inputs), pMax, fixed)

	# get infinitesimals of time transformation
	if timeTrans:
		rs.append(spy.var('r_T_1'))
		diffInfiT = rs[-1]
		allVariables += [T]
	else:
		diffInfiT = None

	# and convert to polynomial
	infis, diffInfis = transformInfisToPoly(infis, diffInfis, allVariables, rs, parallel, ansatz)
	
	diffInfiT = Apoly(diffInfiT, allVariables, rs)

	### extract numerator and denominator of equations
	#differential equations
	numerators = [0]*m
	denominators = [0]*m
	for k in range(m):
		rational = spy.together(diffEquations[k])
		numerators[k] = Apoly(spy.numer(rational), allVariables, None)
		denominators[k] = Apoly(spy.denom(rational), allVariables, None)

	#observation functions
	obsNumerators = [0]*h
	obsDenominatros = [0]*h
	for k in range(h):
		rational = spy.together(obsFunctions[k])
		obsNumerators[k] = Apoly(spy.numer(rational), allVariables, None)
		obsDenominatros[k] = Apoly(spy.denom(rational), allVariables, None)

	#initial functions
	if len(initFunctions) != 0:
		initNumerators = [0]*m
		initDenominatros = [0]*m
		for k in range(m):
			rational = spy.together(initFunctions[k])
			initNumerators[k] = Apoly(spy.numer(rational), allVariables, None)
			initDenominatros[k] = Apoly(spy.denom(rational), allVariables, None)
	else:
		initNumerators = []
		initDenominatros = []

	### calculate numerator of derivatives of equations
	#differential equatioins
	derivativesNum = [0]*m
	for i in range(m):
		derivativesNum[i] = [0]*n
	for k in range(m):
		for l in range(n):
			derivativesNum[k][l] = Apoly(None, allVariables, None)
			derivativesNum[k][l].add(numerators[k].diff(l).mul(denominators[k]))
			derivativesNum[k][l].sub(numerators[k].mul(denominators[k].diff(l)))

	#observation functions
	obsDerivativesNum = [0]*h
	for i in range(h):
		obsDerivativesNum[i] = [0]*n
	for k in range(h):
		for l in range(n):
			obsDerivativesNum[k][l] = Apoly(None, allVariables, None)
			obsDerivativesNum[k][l].add(obsNumerators[k].diff(l).mul(obsDenominatros[k]))
			obsDerivativesNum[k][l].sub(obsNumerators[k].mul(obsDenominatros[k].diff(l)))

	#initial functions
	if len(initFunctions) != 0:
		initDerivativesNum = [0]*len(initFunctions)
		for i in range(m):
			initDerivativesNum[i] = [0]*n
		for k in range(m):
			for l in range(n):
				initDerivativesNum[k][l] = Apoly(None, allVariables, None)
				initDerivativesNum[k][l].add(initNumerators[k].diff(l).mul(initDenominatros[k]))
				initDerivativesNum[k][l].sub(initNumerators[k].mul(initDenominatros[k].diff(l)))
	else:
		initDerivativesNum = []

	sys.stdout.write('\rPreparing equations...done\n')
	sys.stdout.flush()

	###########################################################################################
	############################     build linear system    ###################################
	###########################################################################################
	sys.stdout.write('\nBuilding system...')
	sys.stdout.flush()

	rSystem = buildSystem(numerators, denominators, derivativesNum, obsDerivativesNum,
				initDenominatros, initDerivativesNum, initFunctions, 
				infis, diffInfis, diffInfiT, allVariables, rs, parallel, ansatz)

	sys.stdout.write('done\n')
	sys.stdout.flush()

	
	###########################################################################################
	##############################     solve system    ########################################
	###########################################################################################
	sys.stdout.write('\nSolving system of size ' + str(rSystem.shape[0]) + 'x' +\
						str(rSystem.shape[1]) + '...')
	sys.stdout.flush()

	#get LU decomposition from scipy
	rSystem = scipy.linalg.lu(rSystem, permute_l=True)[1]

	#calculate reduced row echelon form
	rSystem, pivots = getrref(rSystem)

	sys.stdout.write('done\n')
	sys.stdout.flush()

	###########################################################################################
	#############################     process results    ######################################
	###########################################################################################
	sys.stdout.write('\nProcessing results...')
	sys.stdout.flush()

	# calculate solution space
	sys.stdout.write('\n  calculating solution space')
	sys.stdout.flush()
	baseMatrix = nullSpace(rSystem, pivots)

	#substitute solutions into infinitesimals
	#(and remove the ones with common parameter factors)
	sys.stdout.write('\n  substituting solutions')
	sys.stdout.flush()
	infisAll = []
	for l in range(baseMatrix.shape[1]):
		infisTmp = [0]*n
		for i in range(len(infis)):
			infisTmp[i] = infis[i].getCopy()
			infisTmp[i].rs = baseMatrix[:,l]
			infisTmp[i] = infisTmp[i].as_expr()
		if timeTrans:
			infisTmp.append(baseMatrix[-1,l] * T)

		if allTrafos:
			infisAll.append(infisTmp)
		else:
			if not checkForCommonFactor(infisTmp, allVariables, m):
				infisAll.append(infisTmp)
			
	print('')
	sys.stdout.write('done\n')
	sys.stdout.flush()

	# print transformations
	print('\n\n')
	if len(infisAll) != 0: printTransformations(infisAll, allVariables, pretty,suffix)

	###########################################################################################
	############################     check predictions    #####################################
	###########################################################################################
	if predictions != False:
		checkPredictions(predictions, predFunctions, infisAll, allVariables)

	print(time.strftime('\nTotal time: %Hh:%Mm:%Ss', time.gmtime(time.time()-t0)))
Exemplo n.º 50
0
        if G[r, c] != 0:
            m1.append(G[r, c])
            print G[r, c]

print '---Minors of order 2---'
m2_1 = G[:, [1, 2]]
m2_2 = G[:, [0, 2]]
m2_3 = G[:, [0, 1]]
print m2_1
print m2_2
print m2_3

print '---All poles---'
m1count = np.shape(m1)[0]
for m in range(0, m1count):
    print sp.solve(sp.denom(m1[m]))


def M21(s):
    return G[:, [1, 2]]


def M12(s):
    return G[:, [0, 1]]


def M13(s):
    return G[:, [0, 1]]


print poles(M21)