Beispiel #1
0
 def _matches(self):
     eq = self.ode_problem.eq
     f = self.ode_problem.func.func
     x = self.ode_problem.sym
     order = self.ode_problem.order
     df = f(x).diff(x)
     self.eqs = []
     eq = eq.collect(f(x), func=cancel)
     eq = fraction(factor(eq))[0]
     factors = Mul.make_args(factor(eq))
     roots = [fac.as_base_exp() for fac in factors if len(fac.args) != 0]
     if len(roots) > 1 or roots[0][1] > 1:
         for base, expo in roots:
             if base.has(f(x)):
                 self.eqs.append(base)
         if len(self.eqs) > 0:
             return True
     roots = solve(eq, df)
     if len(roots) > 0:
         self.eqs = [(df - root) for root in roots]
         if len(self.eqs) == 1:
             if order > 1:
                 return False
             if self.eqs[0].has(Float):
                 return False
             return fraction(factor(self.eqs[0]))[0] - eq != 0
         return True
     return False
Beispiel #2
0
 def _matches(self):
     eq = self.ode_problem.eq
     f = self.ode_problem.func.func
     x = self.ode_problem.sym
     order =self.ode_problem.order
     df = f(x).diff(x)
     self.eqs = []
     eq = eq.collect(f(x), func = cancel)
     eq = fraction(factor(eq))[0]
     roots = factor_list(eq)[1]
     if len(roots)>1 or roots[0][1]>1:
         for base,expo in roots:
             if base.has(f(x)):
                 self.eqs.append(base)
         if len(self.eqs)>0:
             return True
     roots = solve(eq, df)
     if len(roots)>0:
         self.eqs = [(df - root) for root in roots]
         if len(self.eqs)==1:
             if order>1:
                 return False
             return fraction(factor(self.eqs[0]))[0]-eq!=0
         return True
     return False
Beispiel #3
0
	def count_ops_alg(expr):
		ops  = 0
		args = [expr]

		while args:
			a = args.pop()

			if not isinstance(a, Basic):
				continue

			if a.is_Rational:
				if a is not S.One: # -1/3 = NEG + DIV
					ops += bool (a.p < 0) + bool (a.q != 1)

			elif a.is_Mul:
				if _coeff_isneg(a):
					ops += 1
					if a.args[0] is S.NegativeOne:
						a = a.as_two_terms()[1]
					else:
						a = -a

				n, d = fraction(a)

				if n.is_Integer:
					ops += 1 + bool (n < 0)
					args.append(d) # won't be -Mul but could be Add

				elif d is not S.One:
					if not d.is_Integer:
						args.append(d)
					ops += 1
					args.append(n) # could be -Mul

				else:
					ops += len(a.args) - 1
					args.extend(a.args)

			elif a.is_Add:
				laargs = len(a.args)
				negs   = 0

				for ai in a.args:
					if _coeff_isneg(ai):
						negs += 1
						ai	= -ai
					args.append(ai)

				ops += laargs - (negs != laargs) # -x - y = NEG + SUB

			elif a.is_Pow:
				ops += 1
				args.append(a.base)

		return ops
def simplify(expr, ratio=1.7, measure=count_ops, fu=False):
    """
    Simplifies the given expression.

    Simplification is not a well defined term and the exact strategies
    this function tries can change in the future versions of SymPy. If
    your algorithm relies on "simplification" (whatever it is), try to
    determine what you need exactly  -  is it powsimp()?, radsimp()?,
    together()?, logcombine()?, or something else? And use this particular
    function directly, because those are well defined and thus your algorithm
    will be robust.

    Nonetheless, especially for interactive use, or when you don't know
    anything about the structure of the expression, simplify() tries to apply
    intelligent heuristics to make the input expression "simpler".  For
    example:

    >>> from sympy import simplify, cos, sin
    >>> from sympy.abc import x, y
    >>> a = (x + x**2)/(x*sin(y)**2 + x*cos(y)**2)
    >>> a
    (x**2 + x)/(x*sin(y)**2 + x*cos(y)**2)
    >>> simplify(a)
    x + 1

    Note that we could have obtained the same result by using specific
    simplification functions:

    >>> from sympy import trigsimp, cancel
    >>> trigsimp(a)
    (x**2 + x)/x
    >>> cancel(_)
    x + 1

    In some cases, applying :func:`simplify` may actually result in some more
    complicated expression. The default ``ratio=1.7`` prevents more extreme
    cases: if (result length)/(input length) > ratio, then input is returned
    unmodified.  The ``measure`` parameter lets you specify the function used
    to determine how complex an expression is.  The function should take a
    single argument as an expression and return a number such that if
    expression ``a`` is more complex than expression ``b``, then
    ``measure(a) > measure(b)``.  The default measure function is
    :func:`count_ops`, which returns the total number of operations in the
    expression.

    For example, if ``ratio=1``, ``simplify`` output can't be longer
    than input.

    ::

        >>> from sympy import sqrt, simplify, count_ops, oo
        >>> root = 1/(sqrt(2)+3)

    Since ``simplify(root)`` would result in a slightly longer expression,
    root is returned unchanged instead::

       >>> simplify(root, ratio=1) == root
       True

    If ``ratio=oo``, simplify will be applied anyway::

        >>> count_ops(simplify(root, ratio=oo)) > count_ops(root)
        True

    Note that the shortest expression is not necessary the simplest, so
    setting ``ratio`` to 1 may not be a good idea.
    Heuristically, the default value ``ratio=1.7`` seems like a reasonable
    choice.

    You can easily define your own measure function based on what you feel
    should represent the "size" or "complexity" of the input expression.  Note
    that some choices, such as ``lambda expr: len(str(expr))`` may appear to be
    good metrics, but have other problems (in this case, the measure function
    may slow down simplify too much for very large expressions).  If you don't
    know what a good metric would be, the default, ``count_ops``, is a good
    one.

    For example:

    >>> from sympy import symbols, log
    >>> a, b = symbols('a b', positive=True)
    >>> g = log(a) + log(b) + log(a)*log(1/b)
    >>> h = simplify(g)
    >>> h
    log(a*b**(-log(a) + 1))
    >>> count_ops(g)
    8
    >>> count_ops(h)
    5

    So you can see that ``h`` is simpler than ``g`` using the count_ops metric.
    However, we may not like how ``simplify`` (in this case, using
    ``logcombine``) has created the ``b**(log(1/a) + 1)`` term.  A simple way
    to reduce this would be to give more weight to powers as operations in
    ``count_ops``.  We can do this by using the ``visual=True`` option:

    >>> print(count_ops(g, visual=True))
    2*ADD + DIV + 4*LOG + MUL
    >>> print(count_ops(h, visual=True))
    2*LOG + MUL + POW + SUB

    >>> from sympy import Symbol, S
    >>> def my_measure(expr):
    ...     POW = Symbol('POW')
    ...     # Discourage powers by giving POW a weight of 10
    ...     count = count_ops(expr, visual=True).subs(POW, 10)
    ...     # Every other operation gets a weight of 1 (the default)
    ...     count = count.replace(Symbol, type(S.One))
    ...     return count
    >>> my_measure(g)
    8
    >>> my_measure(h)
    14
    >>> 15./8 > 1.7 # 1.7 is the default ratio
    True
    >>> simplify(g, measure=my_measure)
    -log(a)*log(b) + log(a) + log(b)

    Note that because ``simplify()`` internally tries many different
    simplification strategies and then compares them using the measure
    function, we get a completely different result that is still different
    from the input expression by doing this.
    """
    expr = sympify(expr)

    try:
        return expr._eval_simplify(ratio=ratio, measure=measure)
    except AttributeError:
        pass

    original_expr = expr = signsimp(expr)

    from sympy.simplify.hyperexpand import hyperexpand
    from sympy.functions.special.bessel import BesselBase
    from sympy import Sum, Product

    if not isinstance(expr, Basic) or not expr.args:  # XXX: temporary hack
        return expr

    if not isinstance(expr, (Add, Mul, Pow, ExpBase)):
        if isinstance(expr, Function) and hasattr(expr, "inverse"):
            if len(expr.args) == 1 and len(expr.args[0].args) == 1 and \
               isinstance(expr.args[0], expr.inverse(argindex=1)):
                return simplify(expr.args[0].args[0], ratio=ratio,
                                measure=measure, fu=fu)
        return expr.func(*[simplify(x, ratio=ratio, measure=measure, fu=fu)
                         for x in expr.args])

    # TODO: Apply different strategies, considering expression pattern:
    # is it a purely rational function? Is there any trigonometric function?...
    # See also https://github.com/sympy/sympy/pull/185.

    def shorter(*choices):
        '''Return the choice that has the fewest ops. In case of a tie,
        the expression listed first is selected.'''
        if not has_variety(choices):
            return choices[0]
        return min(choices, key=measure)

    expr = bottom_up(expr, lambda w: w.normal())
    expr = Mul(*powsimp(expr).as_content_primitive())
    _e = cancel(expr)
    expr1 = shorter(_e, _mexpand(_e).cancel())  # issue 6829
    expr2 = shorter(together(expr, deep=True), together(expr1, deep=True))

    if ratio is S.Infinity:
        expr = expr2
    else:
        expr = shorter(expr2, expr1, expr)
    if not isinstance(expr, Basic):  # XXX: temporary hack
        return expr

    expr = factor_terms(expr, sign=False)

    # hyperexpand automatically only works on hypergeometric terms
    expr = hyperexpand(expr)

    expr = piecewise_fold(expr)

    if expr.has(BesselBase):
        expr = besselsimp(expr)

    if expr.has(TrigonometricFunction) and not fu or expr.has(
            HyperbolicFunction):
        expr = trigsimp(expr, deep=True)

    if expr.has(log):
        expr = shorter(expand_log(expr, deep=True), logcombine(expr))

    if expr.has(CombinatorialFunction, gamma):
        expr = combsimp(expr)

    if expr.has(Sum):
        expr = sum_simplify(expr)

    if expr.has(Product):
        expr = product_simplify(expr)

    short = shorter(powsimp(expr, combine='exp', deep=True), powsimp(expr), expr)
    short = shorter(short, factor_terms(short), expand_power_exp(expand_mul(short)))
    if short.has(TrigonometricFunction, HyperbolicFunction, ExpBase):
        short = exptrigsimp(short, simplify=False)

    # get rid of hollow 2-arg Mul factorization
    hollow_mul = Transform(
        lambda x: Mul(*x.args),
        lambda x:
        x.is_Mul and
        len(x.args) == 2 and
        x.args[0].is_Number and
        x.args[1].is_Add and
        x.is_commutative)
    expr = short.xreplace(hollow_mul)

    numer, denom = expr.as_numer_denom()
    if denom.is_Add:
        n, d = fraction(radsimp(1/denom, symbolic=False, max_terms=1))
        if n is not S.One:
            expr = (numer*n).expand()/d

    if expr.could_extract_minus_sign():
        n, d = fraction(expr)
        if d != 0:
            expr = signsimp(-n/(-d))

    if measure(expr) > ratio*measure(original_expr):
        expr = original_expr

    return expr
Beispiel #5
0
def test_fraction():
    x, y, z = map(Symbol, 'xyz')
    A = Symbol('A', commutative=False)

    assert fraction(S.Half) == (1, 2)

    assert fraction(x) == (x, 1)
    assert fraction(1 / x) == (1, x)
    assert fraction(x / y) == (x, y)
    assert fraction(x / 2) == (x, 2)

    assert fraction(x * y / z) == (x * y, z)
    assert fraction(x / (y * z)) == (x, y * z)

    assert fraction(1 / y**2) == (1, y**2)
    assert fraction(x / y**2) == (x, y**2)

    assert fraction((x**2 + 1) / y) == (x**2 + 1, y)
    assert fraction(x * (y + 1) / y**7) == (x * (y + 1), y**7)

    assert fraction(exp(-x), exact=True) == (exp(-x), 1)
    assert fraction((1 / (x + y)) / 2,
                    exact=True) == (1, Mul(2, (x + y), evaluate=False))

    assert fraction(x * A / y) == (x * A, y)
    assert fraction(x * A**-1 / y) == (x * A**-1, y)

    n = symbols('n', negative=True)
    assert fraction(exp(n)) == (1, exp(-n))
    assert fraction(exp(-n)) == (exp(-n), 1)

    p = symbols('p', positive=True)
    assert fraction(exp(-p) * log(p), exact=True) == (exp(-p) * log(p), 1)

    m = Mul(1, 1, S.Half, evaluate=False)
    assert fraction(m) == (1, 2)
    assert fraction(m, exact=True) == (Mul(1, 1, evaluate=False), 2)

    m = Mul(1, 1, S.Half, S.Half, Pow(1, -1, evaluate=False), evaluate=False)
    assert fraction(m) == (1, 4)
    assert fraction(m, exact=True) == \
            (Mul(1, 1, evaluate=False), Mul(2, 2, 1, evaluate=False))
Beispiel #6
0
def test_radsimp():
    r2 = sqrt(2)
    r3 = sqrt(3)
    r5 = sqrt(5)
    r7 = sqrt(7)
    assert fraction(radsimp(1 / r2)) == (sqrt(2), 2)
    assert radsimp(1/(1 + r2)) == \
        -1 + sqrt(2)
    assert radsimp(1/(r2 + r3)) == \
        -sqrt(2) + sqrt(3)
    assert fraction(radsimp(1/(1 + r2 + r3))) == \
        (-sqrt(6) + sqrt(2) + 2, 4)
    assert fraction(radsimp(1/(r2 + r3 + r5))) == \
        (-sqrt(30) + 2*sqrt(3) + 3*sqrt(2), 12)
    assert fraction(radsimp(
        1 /
        (1 + r2 + r3 + r5))) == ((-34 * sqrt(10) - 26 * sqrt(15) -
                                  55 * sqrt(3) - 61 * sqrt(2) + 14 * sqrt(30) +
                                  93 + 46 * sqrt(6) + 53 * sqrt(5), 71))
    assert fraction(radsimp(
        1 / (r2 + r3 + r5 + r7))) == ((-50 * sqrt(42) - 133 * sqrt(5) -
                                       34 * sqrt(70) - 145 * sqrt(3) +
                                       22 * sqrt(105) + 185 * sqrt(2) +
                                       62 * sqrt(30) + 135 * sqrt(7), 215))
    z = radsimp(1 / (1 + r2 / 3 + r3 / 5 + r5 + r7))
    assert len((3616791619821680643598 * z).args) == 16
    assert radsimp(1 / z) == 1 / z
    assert radsimp(1 / z,
                   max_terms=20).expand() == 1 + r2 / 3 + r3 / 5 + r5 + r7
    assert radsimp(1/(r2*3)) == \
        sqrt(2)/6
    assert radsimp(1 / (r2 * a + r3 + r5 + r7)) == (
        (8 * sqrt(2) * a**7 - 8 * sqrt(7) * a**6 - 8 * sqrt(5) * a**6 -
         8 * sqrt(3) * a**6 - 180 * sqrt(2) * a**5 + 8 * sqrt(30) * a**5 +
         8 * sqrt(42) * a**5 + 8 * sqrt(70) * a**5 - 24 * sqrt(105) * a**4 +
         84 * sqrt(3) * a**4 + 100 * sqrt(5) * a**4 + 116 * sqrt(7) * a**4 -
         72 * sqrt(70) * a**3 - 40 * sqrt(42) * a**3 - 8 * sqrt(30) * a**3 +
         782 * sqrt(2) * a**3 - 462 * sqrt(3) * a**2 - 302 * sqrt(7) * a**2 -
         254 * sqrt(5) * a**2 + 120 * sqrt(105) * a**2 - 795 * sqrt(2) * a -
         62 * sqrt(30) * a + 82 * sqrt(42) * a + 98 * sqrt(70) * a -
         118 * sqrt(105) + 59 * sqrt(7) + 295 * sqrt(5) + 531 * sqrt(3)) /
        (16 * a**8 - 480 * a**6 + 3128 * a**4 - 6360 * a**2 + 3481))
    assert radsimp(1 / (r2 * a + r2 * b + r3 + r7)) == (
        (sqrt(2) * a *
         (a + b)**2 - 5 * sqrt(2) * a + sqrt(42) * a + sqrt(2) * b *
         (a + b)**2 - 5 * sqrt(2) * b + sqrt(42) * b - sqrt(7) *
         (a + b)**2 - sqrt(3) * (a + b)**2 - 2 * sqrt(3) + 2 * sqrt(7)) /
        (2 * a**4 + 8 * a**3 * b + 12 * a**2 * b**2 - 20 * a**2 +
         8 * a * b**3 - 40 * a * b + 2 * b**4 - 20 * b**2 + 8))
    assert radsimp(1/(r2*a + r2*b + r2*c + r2*d)) == \
        sqrt(2)/(2*a + 2*b + 2*c + 2*d)
    assert radsimp(1 / (1 + r2 * a + r2 * b + r2 * c + r2 * d)) == (
        (sqrt(2) * a + sqrt(2) * b + sqrt(2) * c + sqrt(2) * d - 1) /
        (2 * a**2 + 4 * a * b + 4 * a * c + 4 * a * d + 2 * b**2 + 4 * b * c +
         4 * b * d + 2 * c**2 + 4 * c * d + 2 * d**2 - 1))
    assert radsimp((y**2 - x)/(y - sqrt(x))) == \
        sqrt(x) + y
    assert radsimp(-(y**2 - x)/(y - sqrt(x))) == \
        -(sqrt(x) + y)
    assert radsimp(1/(1 - I + a*I)) == \
        (-I*a + 1 + I)/(a**2 - 2*a + 2)
    assert radsimp(1/((-x + y)*(x - sqrt(y)))) == \
        (-x - sqrt(y))/((x - y)*(x**2 - y))
    e = (3 + 3 * sqrt(2)) * x * (3 * x - 3 * sqrt(y))
    assert radsimp(e) == x * (3 + 3 * sqrt(2)) * (3 * x - 3 * sqrt(y))
    assert radsimp(1 / e) == (
        (-9 * x + 9 * sqrt(2) * x - 9 * sqrt(y) + 9 * sqrt(2) * sqrt(y)) /
        (9 * x * (9 * x**2 - 9 * y)))
    assert radsimp(1 + 1/(1 + sqrt(3))) == \
        Mul(S.Half, -1 + sqrt(3), evaluate=False) + 1
    A = symbols("A", commutative=False)
    assert radsimp(x**2 + sqrt(2)*x**2 - sqrt(2)*x*A) == \
        x**2 + sqrt(2)*x**2 - sqrt(2)*x*A
    assert radsimp(1 / sqrt(5 + 2 * sqrt(6))) == -sqrt(2) + sqrt(3)
    assert radsimp(1 / sqrt(5 + 2 * sqrt(6))**3) == -(-sqrt(3) + sqrt(2))**3

    # issue 6532
    assert fraction(radsimp(1 / sqrt(x))) == (sqrt(x), x)
    assert fraction(radsimp(1 / sqrt(2 * x + 3))) == (sqrt(2 * x + 3),
                                                      2 * x + 3)
    assert fraction(radsimp(1 / sqrt(2 * (x + 3)))) == (sqrt(2 * x + 6),
                                                        2 * x + 6)

    # issue 5994
    e = S('-(2 + 2*sqrt(2) + 4*2**(1/4))/'
          '(1 + 2**(3/4) + 3*2**(1/4) + 3*sqrt(2))')
    assert radsimp(e).expand(
    ) == -2 * 2**Rational(3, 4) - 2 * 2**Rational(1, 4) + 2 + 2 * sqrt(2)

    # issue 5986 (modifications to radimp didn't initially recognize this so
    # the test is included here)
    assert radsimp(1 / (-sqrt(5) / 2 - S.Half +
                        (-sqrt(5) / 2 - S.Half)**2)) == 1

    # from issue 5934
    eq = ((-240 * sqrt(2) * sqrt(sqrt(5) + 5) * sqrt(8 * sqrt(5) + 40) -
           360 * sqrt(2) * sqrt(-8 * sqrt(5) + 40) * sqrt(-sqrt(5) + 5) -
           120 * sqrt(10) * sqrt(-8 * sqrt(5) + 40) * sqrt(-sqrt(5) + 5) +
           120 * sqrt(2) * sqrt(-sqrt(5) + 5) * sqrt(8 * sqrt(5) + 40) +
           120 * sqrt(2) * sqrt(-8 * sqrt(5) + 40) * sqrt(sqrt(5) + 5) +
           120 * sqrt(10) * sqrt(-sqrt(5) + 5) * sqrt(8 * sqrt(5) + 40) +
           120 * sqrt(10) * sqrt(-8 * sqrt(5) + 40) * sqrt(sqrt(5) + 5)) /
          (-36000 - 7200 * sqrt(5) + (12 * sqrt(10) * sqrt(sqrt(5) + 5) +
                                      24 * sqrt(10) * sqrt(-sqrt(5) + 5))**2))
    assert radsimp(eq) is S.NaN  # it's 0/0

    # work with normal form
    e = 1 / sqrt(sqrt(7) / 7 + 2 * sqrt(2) + 3 * sqrt(3) + 5 * sqrt(5)) + 3
    assert radsimp(e) == (
        -sqrt(sqrt(7) + 14 * sqrt(2) + 21 * sqrt(3) + 35 * sqrt(5)) *
        (-11654899 * sqrt(35) - 1577436 * sqrt(210) - 1278438 * sqrt(15) -
         1346996 * sqrt(10) + 1635060 * sqrt(6) + 5709765 +
         7539830 * sqrt(14) + 8291415 * sqrt(21)) / 1300423175 + 3)

    # obey power rules
    base = sqrt(3) - sqrt(2)
    assert radsimp(1 / base**3) == (sqrt(3) + sqrt(2))**3
    assert radsimp(1 / (-base)**3) == -(sqrt(2) + sqrt(3))**3
    assert radsimp(1 / (-base)**x) == (-base)**(-x)
    assert radsimp(1 / base**x) == (sqrt(2) + sqrt(3))**x
    assert radsimp(root(1 / (-1 - sqrt(2)),
                        -x)) == (-1)**(-1 / x) * (1 + sqrt(2))**(1 / x)

    # recurse
    e = cos(1 / (1 + sqrt(2)))
    assert radsimp(e) == cos(-sqrt(2) + 1)
    assert radsimp(e / 2) == cos(-sqrt(2) + 1) / 2
    assert radsimp(1 / e) == 1 / cos(-sqrt(2) + 1)
    assert radsimp(2 / e) == 2 / cos(-sqrt(2) + 1)
    assert fraction(radsimp(e / sqrt(x))) == (sqrt(x) * cos(-sqrt(2) + 1), x)

    # test that symbolic denominators are not processed
    r = 1 + sqrt(2)
    assert radsimp(x / r, symbolic=False) == -x * (-sqrt(2) + 1)
    assert radsimp(x / (y + r), symbolic=False) == x / (y + 1 + sqrt(2))
    assert radsimp(x/(y + r)/r, symbolic=False) == \
        -x*(-sqrt(2) + 1)/(y + 1 + sqrt(2))

    # issue 7408
    eq = sqrt(x) / sqrt(y)
    assert radsimp(eq) == umul(sqrt(x), sqrt(y), 1 / y)
    assert radsimp(eq, symbolic=False) == eq

    # issue 7498
    assert radsimp(sqrt(x) / sqrt(y)**3) == umul(sqrt(x), sqrt(y**3), 1 / y**3)

    # for coverage
    eq = sqrt(x) / y**2
    assert radsimp(eq) == eq
Beispiel #7
0
def simplify(expr, ratio=1.7, measure=count_ops, rational=False):
    # type: (object, object, object, object) -> object
    """
    Simplifies the given expression.

    Simplification is not a well defined term and the exact strategies
    this function tries can change in the future versions of SymPy. If
    your algorithm relies on "simplification" (whatever it is), try to
    determine what you need exactly  -  is it powsimp()?, radsimp()?,
    together()?, logcombine()?, or something else? And use this particular
    function directly, because those are well defined and thus your algorithm
    will be robust.

    Nonetheless, especially for interactive use, or when you don't know
    anything about the structure of the expression, simplify() tries to apply
    intelligent heuristics to make the input expression "simpler".  For
    example:

    >>> from sympy import simplify, cos, sin
    >>> from sympy.abc import x, y
    >>> a = (x + x**2)/(x*sin(y)**2 + x*cos(y)**2)
    >>> a
    (x**2 + x)/(x*sin(y)**2 + x*cos(y)**2)
    >>> simplify(a)
    x + 1

    Note that we could have obtained the same result by using specific
    simplification functions:

    >>> from sympy import trigsimp, cancel
    >>> trigsimp(a)
    (x**2 + x)/x
    >>> cancel(_)
    x + 1

    In some cases, applying :func:`simplify` may actually result in some more
    complicated expression. The default ``ratio=1.7`` prevents more extreme
    cases: if (result length)/(input length) > ratio, then input is returned
    unmodified.  The ``measure`` parameter lets you specify the function used
    to determine how complex an expression is.  The function should take a
    single argument as an expression and return a number such that if
    expression ``a`` is more complex than expression ``b``, then
    ``measure(a) > measure(b)``.  The default measure function is
    :func:`count_ops`, which returns the total number of operations in the
    expression.

    For example, if ``ratio=1``, ``simplify`` output can't be longer
    than input.

    ::

        >>> from sympy import sqrt, simplify, count_ops, oo
        >>> root = 1/(sqrt(2)+3)

    Since ``simplify(root)`` would result in a slightly longer expression,
    root is returned unchanged instead::

       >>> simplify(root, ratio=1) == root
       True

    If ``ratio=oo``, simplify will be applied anyway::

        >>> count_ops(simplify(root, ratio=oo)) > count_ops(root)
        True

    Note that the shortest expression is not necessary the simplest, so
    setting ``ratio`` to 1 may not be a good idea.
    Heuristically, the default value ``ratio=1.7`` seems like a reasonable
    choice.

    You can easily define your own measure function based on what you feel
    should represent the "size" or "complexity" of the input expression.  Note
    that some choices, such as ``lambda expr: len(str(expr))`` may appear to be
    good metrics, but have other problems (in this case, the measure function
    may slow down simplify too much for very large expressions).  If you don't
    know what a good metric would be, the default, ``count_ops``, is a good
    one.

    For example:

    >>> from sympy import symbols, log
    >>> a, b = symbols('a b', positive=True)
    >>> g = log(a) + log(b) + log(a)*log(1/b)
    >>> h = simplify(g)
    >>> h
    log(a*b**(-log(a) + 1))
    >>> count_ops(g)
    8
    >>> count_ops(h)
    5

    So you can see that ``h`` is simpler than ``g`` using the count_ops metric.
    However, we may not like how ``simplify`` (in this case, using
    ``logcombine``) has created the ``b**(log(1/a) + 1)`` term.  A simple way
    to reduce this would be to give more weight to powers as operations in
    ``count_ops``.  We can do this by using the ``visual=True`` option:

    >>> print(count_ops(g, visual=True))
    2*ADD + DIV + 4*LOG + MUL
    >>> print(count_ops(h, visual=True))
    2*LOG + MUL + POW + SUB

    >>> from sympy import Symbol, S
    >>> def my_measure(expr):
    ...     POW = Symbol('POW')
    ...     # Discourage powers by giving POW a weight of 10
    ...     count = count_ops(expr, visual=True).subs(POW, 10)
    ...     # Every other operation gets a weight of 1 (the default)
    ...     count = count.replace(Symbol, type(S.One))
    ...     return count
    >>> my_measure(g)
    8
    >>> my_measure(h)
    14
    >>> 15./8 > 1.7 # 1.7 is the default ratio
    True
    >>> simplify(g, measure=my_measure)
    -log(a)*log(b) + log(a) + log(b)

    Note that because ``simplify()`` internally tries many different
    simplification strategies and then compares them using the measure
    function, we get a completely different result that is still different
    from the input expression by doing this.

    If rational=True, Floats will be recast as Rationals before simplification.
    If rational=None, Floats will be recast as Rationals but the result will
    be recast as Floats. If rational=False(default) then nothing will be done
    to the Floats.
    """
    expr = sympify(expr)

    try:
        return expr._eval_simplify(ratio=ratio, measure=measure)
    except AttributeError:
        pass

    original_expr = expr = signsimp(expr)

    from sympy.simplify.hyperexpand import hyperexpand
    from sympy.functions.special.bessel import BesselBase
    from sympy import Sum, Product

    if not isinstance(expr, Basic) or not expr.args:  # XXX: temporary hack
        return expr

    if not isinstance(expr, (Add, Mul, Pow, ExpBase)):
        if isinstance(expr, Function) and hasattr(expr, "inverse"):
            if len(expr.args) == 1 and len(expr.args[0].args) == 1 and \
               isinstance(expr.args[0], expr.inverse(argindex=1)):
                return simplify(expr.args[0].args[0], ratio=ratio,
                                measure=measure, rational=rational)
        return expr.func(*[simplify(x, ratio=ratio, measure=measure, rational=rational)
                         for x in expr.args])

    # TODO: Apply different strategies, considering expression pattern:
    # is it a purely rational function? Is there any trigonometric function?...
    # See also https://github.com/sympy/sympy/pull/185.

    def shorter(*choices):
        '''Return the choice that has the fewest ops. In case of a tie,
        the expression listed first is selected.'''
        if not has_variety(choices):
            return choices[0]
        return min(choices, key=measure)

    # rationalize Floats
    floats = False
    if rational is not False and expr.has(Float):
        floats = True
        expr = nsimplify(expr, rational=True)

    expr = bottom_up(expr, lambda w: w.normal())
    expr = Mul(*powsimp(expr).as_content_primitive())
    _e = cancel(expr)
    expr1 = shorter(_e, _mexpand(_e).cancel())  # issue 6829
    expr2 = shorter(together(expr, deep=True), together(expr1, deep=True))

    if ratio is S.Infinity:
        expr = expr2
    else:
        expr = shorter(expr2, expr1, expr)
    if not isinstance(expr, Basic):  # XXX: temporary hack
        return expr

    expr = factor_terms(expr, sign=False)

    # hyperexpand automatically only works on hypergeometric terms
    expr = hyperexpand(expr)

    expr = piecewise_fold(expr)

    if expr.has(BesselBase):
        expr = besselsimp(expr)

    if expr.has(TrigonometricFunction, HyperbolicFunction):
        expr = trigsimp(expr, deep=True)

    if expr.has(log):
        expr = shorter(expand_log(expr, deep=True), logcombine(expr))

    if expr.has(CombinatorialFunction, gamma):
        # expression with gamma functions or non-integer arguments is
        # automatically passed to gammasimp
        expr = combsimp(expr)

    if expr.has(Sum):
        expr = sum_simplify(expr)

    if expr.has(Product):
        expr = product_simplify(expr)

    short = shorter(powsimp(expr, combine='exp', deep=True), powsimp(expr), expr)
    short = shorter(short, cancel(short))
    short = shorter(short, factor_terms(short), expand_power_exp(expand_mul(short)))
    if short.has(TrigonometricFunction, HyperbolicFunction, ExpBase):
        short = exptrigsimp(short)

    # get rid of hollow 2-arg Mul factorization
    hollow_mul = Transform(
        lambda x: Mul(*x.args),
        lambda x:
        x.is_Mul and
        len(x.args) == 2 and
        x.args[0].is_Number and
        x.args[1].is_Add and
        x.is_commutative)
    expr = short.xreplace(hollow_mul)

    numer, denom = expr.as_numer_denom()
    if denom.is_Add:
        n, d = fraction(radsimp(1/denom, symbolic=False, max_terms=1))
        if n is not S.One:
            expr = (numer*n).expand()/d

    if expr.could_extract_minus_sign():
        n, d = fraction(expr)
        if d != 0:
            expr = signsimp(-n/(-d))

    if measure(expr) > ratio*measure(original_expr):
        expr = original_expr

    # restore floats
    if floats and rational is None:
        expr = nfloat(expr, exponent=False)

    return expr