def test_slow_general_univariate(): r = RootOf(x**5 - x**2 + 1, 0) assert solve(sqrt(x) + 1/root(x, 3) > 1) == \ Or(And(S(0) < x, x < r**6), And(r**6 < x, x < oo))
def as_boolean(self): return And(self.fulldomain.as_boolean(), self.condition)
def BayesTest(A, B): assert P(A, B) == P(And(A, B)) / P(B) assert P(A, B) == P(B, A) * P(A) / P(B)
def test_Union_as_relational(): x = Symbol('x') assert (Interval(0, 1) + FiniteSet(2)).as_relational(x) == \ Or(And(Le(0, x), Le(x, 1)), Eq(x, 2)) assert (Interval(0, 1, True, True) + FiniteSet(1)).as_relational(x) == \ And(Lt(0, x), Le(x, 1))
def test_issue_10248(): assert list(Intersection(S.Reals, FiniteSet(x))) == [And(x < oo, x > -oo)]
def test_count_ops_visual(): ADD, MUL, POW, SIN, COS, EXP, AND, D, G = symbols( 'Add Mul Pow sin cos exp And Derivative Integral'.upper()) DIV, SUB, NEG = symbols('DIV SUB NEG') LT, LE, GT, GE, EQ, NE = symbols('LT LE GT GE EQ NE') NOT, OR, AND, XOR, IMPLIES, EQUIVALENT, _ITE, BASIC, TUPLE = symbols( 'Not Or And Xor Implies Equivalent ITE Basic Tuple'.upper()) def count(val): return count_ops(val, visual=True) assert count(7) is S.Zero assert count(S(7)) is S.Zero assert count(-1) == NEG assert count(-2) == NEG assert count(S(2) / 3) == DIV assert count(pi / 3) == DIV assert count(-pi / 3) == DIV + NEG assert count(I - 1) == SUB assert count(1 - I) == SUB assert count(1 - 2 * I) == SUB + MUL assert count(x) is S.Zero assert count(-x) == NEG assert count(-2 * x / 3) == NEG + DIV + MUL assert count(1 / x) == DIV assert count(1 / (x * y)) == DIV + MUL assert count(-1 / x) == NEG + DIV assert count(-2 / x) == NEG + DIV assert count(x / y) == DIV assert count(-x / y) == NEG + DIV assert count(x**2) == POW assert count(-x**2) == POW + NEG assert count(-2 * x**2) == POW + MUL + NEG assert count(x + pi / 3) == ADD + DIV assert count(x + S(1) / 3) == ADD + DIV assert count(x + y) == ADD assert count(x - y) == SUB assert count(y - x) == SUB assert count(-1 / (x - y)) == DIV + NEG + SUB assert count(-1 / (y - x)) == DIV + NEG + SUB assert count(1 + x**y) == ADD + POW assert count(1 + x + y) == 2 * ADD assert count(1 + x + y + z) == 3 * ADD assert count(1 + x**y + 2 * x * y + y**2) == 3 * ADD + 2 * POW + 2 * MUL assert count(2 * z + y + x + 1) == 3 * ADD + MUL assert count(2 * z + y**17 + x + 1) == 3 * ADD + MUL + POW assert count(2 * z + y**17 + x + sin(x)) == 3 * ADD + POW + MUL + SIN assert count(2 * z + y**17 + x + sin(x**2)) == 3 * ADD + MUL + 2 * POW + SIN assert count(2 * z + y**17 + x + sin(x**2) + exp(cos(x))) == 4 * ADD + MUL + 2 * POW + EXP + COS + SIN assert count(Derivative(x, x)) == D assert count(Integral(x, x) + 2 * x / (1 + x)) == G + DIV + MUL + 2 * ADD assert count(Basic()) is S.Zero assert count({x + 1: sin(x)}) == ADD + SIN assert count([x + 1, sin(x) + y, None]) == ADD + SIN + ADD assert count({x + 1: sin(x), y: cos(x) + 1}) == SIN + COS + 2 * ADD assert count({}) is S.Zero assert count([x + 1, sin(x) * y, None]) == SIN + ADD + MUL assert count([]) is S.Zero assert count(Basic()) == 0 assert count(Basic(Basic(), Basic(x, x + y))) == ADD + 2 * BASIC assert count(Basic(x, x + y)) == ADD + BASIC assert [count(Rel(x, y, op)) for op in '< <= > >= == <> !='.split() ] == [LT, LE, GT, GE, EQ, NE, NE] assert count(Or(x, y)) == OR assert count(And(x, y)) == AND assert count(Or(x, Or(y, And(z, a)))) == AND + OR assert count(Nor(x, y)) == NOT + OR assert count(Nand(x, y)) == NOT + AND assert count(Xor(x, y)) == XOR assert count(Implies(x, y)) == IMPLIES assert count(Equivalent(x, y)) == EQUIVALENT assert count(ITE(x, y, z)) == _ITE assert count([Or(x, y), And(x, y), Basic(x + y)]) == ADD + AND + BASIC + OR assert count(Basic(Tuple(x))) == BASIC + TUPLE #It checks that TUPLE is counted as an operation. assert count(Eq(x + y, S(2))) == ADD + EQ
def write_tdb(dbf, fd, groupby='subsystem', if_incompatible='warn'): """ Write a TDB file from a pycalphad Database object. The goal is to produce TDBs that conform to the most restrictive subset of database specifications. Some of these can be adjusted for automatically, such as the Thermo-Calc line length limit of 78. Others require changing the database in non-trivial ways, such as the maximum length of function names (8). The default is to warn the user when attempting to write an incompatible database and the user must choose whether to warn and write the file anyway or to fix the incompatibility. Currently the supported compatibility fixes are: - Line length <= 78 characters (Thermo-Calc) - Function names <= 8 characters (Thermo-Calc) The current unsupported fixes include: - Keyword length <= 2000 characters (Thermo-Calc) - Element names <= 2 characters (Thermo-Calc) - Phase names <= 24 characters (Thermo-Calc) Other TDB compatibility issues required by Thermo-Calc or other software should be reported to the issue tracker. Parameters ---------- dbf : Database A pycalphad Database. fd : file-like File descriptor. groupby : ['subsystem', 'phase'], optional Desired grouping of parameters in the file. if_incompatible : string, optional ['raise', 'warn', 'fix'] Strategy if the database does not conform to the most restrictive database specification. The 'warn' option (default) will write out the incompatible database with a warning. The 'raise' option will raise a DatabaseExportError. The 'ignore' option will write out the incompatible database silently. The 'fix' option will rectify the incompatibilities e.g. through name mangling. """ # Before writing anything, check that the TDB is valid and take the appropriate action if not if if_incompatible not in ['warn', 'raise', 'ignore', 'fix']: raise ValueError( 'Incorrect options passed to \'if_invalid\'. Valid args are \'raise\', \'warn\', or \'fix\'.' ) # Handle function names > 8 characters long_function_names = {k for k in dbf.symbols.keys() if len(k) > 8} if len(long_function_names) > 0: if if_incompatible == 'raise': raise DatabaseExportError( 'The following function names are beyond the 8 character TDB limit: {}. Use the keyword argument \'if_incompatible\' to control this behavior.' .format(long_function_names)) elif if_incompatible == 'fix': # if we are going to make changes, make the changes to a copy and leave the original object untouched dbf = deepcopy( dbf) # TODO: if we do multiple fixes, we should only copy once symbol_name_map = {} for name in long_function_names: hashed_name = 'F' + str( hashlib.md5(name.encode('UTF-8')).hexdigest()).upper( )[:7] # this is implictly upper(), but it is explicit here symbol_name_map[name] = hashed_name _apply_new_symbol_names(dbf, symbol_name_map) elif if_incompatible == 'warn': warnings.warn( 'Ignoring that the following function names are beyond the 8 character TDB limit: {}. Use the keyword argument \'if_incompatible\' to control this behavior.' .format(long_function_names)) # Begin constructing the written database writetime = datetime.datetime.now() maxlen = 78 output = "" # Comment header block # Import here to prevent circular imports from pycalphad import __version__ output += ("$" * maxlen) + "\n" output += "$ Date: {}\n".format(writetime.strftime("%Y-%m-%d %H:%M")) output += "$ Components: {}\n".format(', '.join(sorted(dbf.elements))) output += "$ Phases: {}\n".format(', '.join(sorted(dbf.phases.keys()))) output += "$ Generated by {} (pycalphad {})\n".format( getpass.getuser(), __version__) output += ("$" * maxlen) + "\n\n" for element in sorted(dbf.elements): output += "ELEMENT {0} BLANK 0 0 0 !\n".format(element.upper()) if len(dbf.elements) > 0: output += "\n" for species in sorted(dbf.species, key=lambda s: s.name): if species.name not in dbf.elements: # construct the charge part of the specie if species.charge != 0: if species.charge > 0: charge_sign = '+' else: charge_sign = '' charge = '/{}{}'.format(charge_sign, species.charge) else: charge = '' species_constituents = ''.join([ '{}{}'.format(el, val) for el, val in sorted(species.constituents.items(), key=lambda t: t[0]) ]) output += "SPECIES {0} {1}{2} !\n".format(species.name.upper(), species_constituents, charge) if len(dbf.species) > 0: output += "\n" # Write FUNCTION block for name, expr in sorted(dbf.symbols.items()): if not isinstance(expr, Piecewise): # Non-piecewise exprs need to be wrapped to print # Otherwise TC's TDB parser will complain expr = Piecewise((expr, And(v.T >= 1, v.T < 10000))) expr = TCPrinter().doprint(expr).upper() if ';' not in expr: expr += '; N' output += "FUNCTION {0} {1} !\n".format(name.upper(), expr) output += "\n" # Boilerplate code output += "TYPE_DEFINITION % SEQ * !\n" output += "DEFINE_SYSTEM_DEFAULT ELEMENT 2 !\n" default_elements = [ i.upper() for i in sorted(dbf.elements) if i.upper() == 'VA' or i.upper() == '/-' ] if len(default_elements) > 0: output += 'DEFAULT_COMMAND DEFINE_SYSTEM_ELEMENT {} !\n'.format( ' '.join(default_elements)) output += "\n" typedef_chars = list("^&*()'ABCDEFGHIJKLMNOPQSRTUVWXYZ")[::-1] # Write necessary TYPE_DEF based on model hints typedefs = defaultdict(lambda: ["%"]) for name, phase_obj in sorted(dbf.phases.items()): model_hints = phase_obj.model_hints.copy() possible_options = set(phase_options.keys()).intersection(model_hints) # Phase options are handled later for option in possible_options: del model_hints[option] if ('ordered_phase' in model_hints.keys()) and (model_hints['ordered_phase'] == name): new_char = typedef_chars.pop() typedefs[name].append(new_char) typedefs[model_hints['disordered_phase']].append(new_char) output += 'TYPE_DEFINITION {} GES AMEND_PHASE_DESCRIPTION {} DISORDERED_PART {} !\n'\ .format(new_char, model_hints['ordered_phase'].upper(), model_hints['disordered_phase'].upper()) del model_hints['ordered_phase'] del model_hints['disordered_phase'] if ('disordered_phase' in model_hints.keys()) and (model_hints['disordered_phase'] == name): # We handle adding the correct typedef when we write the ordered phase del model_hints['ordered_phase'] del model_hints['disordered_phase'] if 'ihj_magnetic_afm_factor' in model_hints.keys(): new_char = typedef_chars.pop() typedefs[name].append(new_char) output += 'TYPE_DEFINITION {} GES AMEND_PHASE_DESCRIPTION {} MAGNETIC {} {} !\n'\ .format(new_char, name.upper(), model_hints['ihj_magnetic_afm_factor'], model_hints['ihj_magnetic_structure_factor']) del model_hints['ihj_magnetic_afm_factor'] del model_hints['ihj_magnetic_structure_factor'] if len(model_hints) > 0: # Some model hints were not properly consumed raise ValueError( 'Not all model hints are supported: {}'.format(model_hints)) # Perform a second loop now that all typedefs / model hints are consistent for name, phase_obj in sorted(dbf.phases.items()): # model_hints may also contain "phase options", e.g., ionic liquid model_hints = phase_obj.model_hints.copy() name_with_options = str(name.upper()) possible_options = set(phase_options.keys()).intersection( model_hints.keys()) if len(possible_options) > 0: name_with_options += ':' for option in possible_options: name_with_options += phase_options[option] output += "PHASE {0} {1} {2} {3} !\n".format( name_with_options, ''.join(typedefs[name]), len(phase_obj.sublattices), ' '.join([str(i) for i in phase_obj.sublattices])) constituents = ':'.join([ ','.join([spec.name for spec in sorted(subl)]) for subl in phase_obj.constituents ]) output += "CONSTITUENT {0} :{1}: !\n".format(name_with_options, constituents) output += "\n" # PARAMETERs by subsystem param_sorted = defaultdict(lambda: list()) paramtuple = namedtuple('ParamTuple', [ 'phase_name', 'parameter_type', 'complexity', 'constituent_array', 'parameter_order', 'diffusing_species', 'parameter', 'reference' ]) for param in dbf._parameters.all(): if groupby == 'subsystem': components = set() for subl in param['constituent_array']: components |= set(subl) if param['diffusing_species'] != Species(None): components |= {param['diffusing_species']} # Wildcard operator is not a component components -= {'*'} desired_active_pure_elements = [ list(x.constituents.keys()) for x in components ] components = set([ el.upper() for constituents in desired_active_pure_elements for el in constituents ]) # Remove vacancy if it's not the only component (pure vacancy endmember) if len(components) > 1: components -= {'VA'} components = tuple(sorted([c.upper() for c in components])) grouping = components elif groupby == 'phase': grouping = param['phase_name'].upper() else: raise ValueError( 'Unknown groupby attribute \'{}\''.format(groupby)) # We use the complexity parameter to help with sorting the parameters logically param_sorted[grouping].append( paramtuple(param['phase_name'], param['parameter_type'], sum([len(i) for i in param['constituent_array']]), param['constituent_array'], param['parameter_order'], param['diffusing_species'], param['parameter'], param['reference'])) def write_parameter(param_to_write): constituents = ':'.join([ ','.join(sorted([i.name.upper() for i in subl])) for subl in param_to_write.constituent_array ]) # TODO: Handle references paramx = param_to_write.parameter if not isinstance(paramx, Piecewise): # Non-piecewise parameters need to be wrapped to print correctly # Otherwise TC's TDB parser will fail paramx = Piecewise((paramx, And(v.T >= 1, v.T < 10000))) exprx = TCPrinter().doprint(paramx).upper() if ';' not in exprx: exprx += '; N' if param_to_write.diffusing_species != Species(None): ds = "&" + param_to_write.diffusing_species.name else: ds = "" return "PARAMETER {}({}{},{};{}) {} !\n".format( param_to_write.parameter_type.upper(), param_to_write.phase_name.upper(), ds, constituents, param_to_write.parameter_order, exprx) if groupby == 'subsystem': for num_species in range(1, 5): subsystems = list( itertools.combinations( sorted([i.name.upper() for i in dbf.species]), num_species)) for subsystem in subsystems: parameters = sorted(param_sorted[subsystem]) if len(parameters) > 0: output += "\n\n" output += "$" * maxlen + "\n" output += "$ {}".format('-'.join(sorted(subsystem)).center( maxlen, " ")[2:-1]) + "$\n" output += "$" * maxlen + "\n" output += "\n" for parameter in parameters: output += write_parameter(parameter) # Don't generate combinatorics for multi-component subsystems or we'll run out of memory if len(dbf.species) > 4: subsystems = [k for k in param_sorted.keys() if len(k) > 4] for subsystem in subsystems: parameters = sorted(param_sorted[subsystem]) for parameter in parameters: output += write_parameter(parameter) elif groupby == 'phase': for phase_name in sorted(dbf.phases.keys()): parameters = sorted(param_sorted[phase_name]) if len(parameters) > 0: output += "\n\n" output += "$" * maxlen + "\n" output += "$ {}".format(phase_name.upper().center( maxlen, " ")[2:-1]) + "$\n" output += "$" * maxlen + "\n" output += "\n" for parameter in parameters: output += write_parameter(parameter) else: raise ValueError('Unknown groupby attribute {}'.format(groupby)) # Reflow text to respect character limit per line fd.write(reflow_text(output, linewidth=maxlen))
def test_reduce_inequalities_multivariate(): assert reduce_inequalities([Ge(x**2, 1), Ge(y**2, 1)]) == \ And(And(Or(Le(re(x), -1), Ge(re(x), 1)), Eq(im(x), 0)), And(Or(Le(re(y), -1), Ge(re(y), 1)), Eq(im(y), 0)))
def test_issue_3244(): eq = -3 * x**2 / 2 - 45 * x / 4 + S(33) / 2 > 0 assert reduce_inequalities(eq, Q.real(x)) == \ And(x < -S(15)/4 + sqrt(401)/4, -sqrt(401)/4 - S(15)/4 < x)
def test_reduce_poly_inequalities_complex_relational(): cond = Eq(im(x), 0) assert reduce_rational_inequalities([[Eq(x**2, 0)]], x, relational=True) == And( Eq(re(x), 0), cond) assert reduce_rational_inequalities([[Le(x**2, 0)]], x, relational=True) == And( Eq(re(x), 0), cond) assert reduce_rational_inequalities([[Lt(x**2, 0)]], x, relational=True) is False assert reduce_rational_inequalities([[Ge(x**2, 0)]], x, relational=True) == cond assert reduce_rational_inequalities([[Gt(x**2, 0)]], x, relational=True) == \ And(Or(Lt(re(x), 0), Gt(re(x), 0)), cond) assert reduce_rational_inequalities([[Ne(x**2, 0)]], x, relational=True) == \ And(Or(Lt(re(x), 0), Gt(re(x), 0)), cond) assert reduce_rational_inequalities([[Eq(x**2, 1)]], x, relational=True) == \ And(Or(Eq(re(x), -1), Eq(re(x), 1)), cond) assert reduce_rational_inequalities([[Le(x**2, 1)]], x, relational=True) == \ And(And(Le(-1, re(x)), Le(re(x), 1)), cond) assert reduce_rational_inequalities([[Lt(x**2, 1)]], x, relational=True) == \ And(And(Lt(-1, re(x)), Lt(re(x), 1)), cond) assert reduce_rational_inequalities([[Ge(x**2, 1)]], x, relational=True) == \ And(Or(Le(re(x), -1), Ge(re(x), 1)), cond) assert reduce_rational_inequalities([[Gt(x**2, 1)]], x, relational=True) == \ And(Or(Lt(re(x), -1), Gt(re(x), 1)), cond) assert reduce_rational_inequalities([[Ne(x**2, 1)]], x, relational=True) == \ And(Or(Lt(re(x), -1), And(Lt(-1, re(x)), Lt(re(x), 1)), Gt(re(x), 1)), cond) assert reduce_rational_inequalities([[Le(x**2, 1.0)]], x, relational=True) == \ And(And(Le(-1.0, re(x)), Le(re(x), 1.0)), cond) assert reduce_rational_inequalities([[Lt(x**2, 1.0)]], x, relational=True) == \ And(And(Lt(-1.0, re(x)), Lt(re(x), 1.0)), cond) assert reduce_rational_inequalities([[Ge(x**2, 1.0)]], x, relational=True) == \ And(Or(Le(re(x), -1.0), Ge(re(x), 1.0)), cond) assert reduce_rational_inequalities([[Gt(x**2, 1.0)]], x, relational=True) == \ And(Or(Lt(re(x), -1.0), Gt(re(x), 1.0)), cond) assert reduce_rational_inequalities([[Ne(x**2, 1.0)]], x, relational=True) == \ And(Or(Lt(re(x), -1.0), And(Lt(-1.0, re(x)), Lt(re(x), 1.0)), Gt(re(x), 1.0)), cond)
def test_reduce_inequalities_assume(): assert reduce_inequalities([Le(x**2, 1), Q.real(x)]) == And(Le(-1, x), Le(x, 1)) assert reduce_inequalities([Le(x**2, 1)], Q.real(x)) == And(Le(-1, x), Le(x, 1))
def test_reduce_poly_inequalities_real_relational(): with assuming(Q.real(x), Q.real(y)): assert reduce_rational_inequalities([[Eq(x**2, 0)]], x, relational=True) == Eq(x, 0) assert reduce_rational_inequalities([[Le(x**2, 0)]], x, relational=True) == Eq(x, 0) assert reduce_rational_inequalities( [[Lt(x**2, 0)]], x, relational=True) is False assert reduce_rational_inequalities( [[Ge(x**2, 0)]], x, relational=True) is True assert reduce_rational_inequalities([[Gt(x**2, 0)]], x, relational=True) == Or( Lt(x, 0), Gt(x, 0)) assert reduce_rational_inequalities([[Ne(x**2, 0)]], x, relational=True) == Or( Lt(x, 0), Gt(x, 0)) assert reduce_rational_inequalities([[Eq(x**2, 1)]], x, relational=True) == Or( Eq(x, -1), Eq(x, 1)) assert reduce_rational_inequalities([[Le(x**2, 1)]], x, relational=True) == And( Le(-1, x), Le(x, 1)) assert reduce_rational_inequalities([[Lt(x**2, 1)]], x, relational=True) == And( Lt(-1, x), Lt(x, 1)) assert reduce_rational_inequalities([[Ge(x**2, 1)]], x, relational=True) == Or( Le(x, -1), Ge(x, 1)) assert reduce_rational_inequalities([[Gt(x**2, 1)]], x, relational=True) == Or( Lt(x, -1), Gt(x, 1)) assert reduce_rational_inequalities([[Ne(x**2, 1)]], x, relational=True) == Or( Lt(x, -1), And(Lt(-1, x), Lt(x, 1)), Gt(x, 1)) assert reduce_rational_inequalities([[Le(x**2, 1.0)]], x, relational=True) == And( Le(-1.0, x), Le(x, 1.0)) assert reduce_rational_inequalities([[Lt(x**2, 1.0)]], x, relational=True) == And( Lt(-1.0, x), Lt(x, 1.0)) assert reduce_rational_inequalities([[Ge(x**2, 1.0)]], x, relational=True) == Or( Le(x, -1.0), Ge(x, 1.0)) assert reduce_rational_inequalities([[Gt(x**2, 1.0)]], x, relational=True) == Or( Lt(x, -1.0), Gt(x, 1.0)) assert reduce_rational_inequalities([[Ne(x**2, 1.0)]], x, relational=True) == \ Or(Lt(x, -1.0), And(Lt(-1.0, x), Lt(x, 1.0)), Gt(x, 1.0))
def test_plot_and_save_1(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') y = Symbol('y') with TemporaryDirectory(prefix='sympy_') as tmpdir: ### # Examples from the 'introduction' notebook ### p = plot(x, legend=True, label='f1') p = plot(x * sin(x), x * cos(x), label='f2') p.extend(p) p[0].line_color = lambda a: a p[1].line_color = 'b' p.title = 'Big title' p.xlabel = 'the x axis' p[1].label = 'straight line' p.legend = True p.aspect_ratio = (1, 1) p.xlim = (-15, 20) filename = 'test_basic_options_and_colors.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p.extend(plot(x + 1)) p.append(plot(x + 3, x**2)[1]) filename = 'test_plot_extend_append.png' p.save(os.path.join(tmpdir, filename)) p[2] = plot(x**2, (x, -2, 3)) filename = 'test_plot_setitem.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot(sin(x), (x, -2 * pi, 4 * pi)) filename = 'test_line_explicit.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot(sin(x)) filename = 'test_line_default_range.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot((x**2, (x, -5, 5)), (x**3, (x, -3, 3))) filename = 'test_line_multiple_range.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() raises(ValueError, lambda: plot(x, y)) #Piecewise plots p = plot(Piecewise((1, x > 0), (0, True)), (x, -1, 1)) filename = 'test_plot_piecewise.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot(Piecewise((x, x < 1), (x**2, True)), (x, -3, 3)) filename = 'test_plot_piecewise_2.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() # test issue 7471 p1 = plot(x) p2 = plot(3) p1.extend(p2) filename = 'test_horizontal_line.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() # test issue 10925 f = Piecewise((-1, x < -1), (x, And(-1 <= x, x < 0)), \ (x**2, And(0 <= x, x < 1)), (x**3, x >= 1)) p = plot(f, (x, -3, 3)) filename = 'test_plot_piecewise_3.png' p.save(os.path.join(tmpdir, filename)) p._backend.close()
def test_issue_8545(): eq = 1 - x - abs(1 - x) ans = And(Lt(1, x), Lt(x, oo)) assert reduce_abs_inequality(eq, '<', x) == ans eq = 1 - x - sqrt((1 - x)**2) assert reduce_inequalities(eq < 0) == ans
def test_issue_11045(): assert integrate(1 / (x * sqrt(x**2 - 1)), (x, 1, 2)) == pi / 3 # handle And with Or arguments assert Piecewise((1, And(Or(x < 1, x > 3), x < 2)), (0, True)).integrate( (x, 0, 3)) == 1 # hidden false assert Piecewise((1, x > 1), (2, x > x + 1), (3, True)).integrate( (x, 0, 3)) == 5 # targetcond is Eq assert Piecewise((1, x > 1), (2, Eq(1, x)), (3, True)).integrate( (x, 0, 4)) == 6 # And has Relational needing to be solved assert Piecewise((1, And(2 * x > x + 1, x < 2)), (0, True)).integrate( (x, 0, 3)) == 1 # Or has Relational needing to be solved assert Piecewise((1, Or(2 * x > x + 2, x < 1)), (0, True)).integrate( (x, 0, 3)) == 2 # ignore hidden false (handled in canonicalization) assert Piecewise((1, x > 1), (2, x > x + 1), (3, True)).integrate( (x, 0, 3)) == 5 # watch for hidden True Piecewise assert Piecewise((2, Eq(1 - x, x * (1 / x - 1))), (0, True)).integrate( (x, 0, 3)) == 6 # overlapping conditions of targetcond are recognized and ignored; # the condition x > 3 will be pre-empted by the first condition assert Piecewise((1, Or(x < 1, x > 2)), (2, x > 3), (3, True)).integrate( (x, 0, 4)) == 6 # convert Ne to Or assert Piecewise((1, Ne(x, 0)), (2, True)).integrate((x, -1, 1)) == 2 # no default but well defined assert Piecewise((x, (x > 1) & (x < 3)), (1, (x < 4))).integrate( (x, 1, 4)) == 5 p = Piecewise((x, (x > 1) & (x < 3)), (1, (x < 4))) nan = Undefined i = p.integrate((x, 1, y)) assert i == Piecewise( (y - 1, y < 1), (Min(3, y)**2 / 2 - Min(3, y) + Min(4, y) - 1 / 2, y <= Min(4, y)), (nan, True)) assert p.integrate((x, 1, -1)) == i.subs(y, -1) assert p.integrate((x, 1, 4)) == 5 assert p.integrate((x, 1, 5)) == nan # handle Not p = Piecewise((1, x > 1), (2, Not(And(x > 1, x < 3))), (3, True)) assert p.integrate((x, 0, 3)) == 4 # handle updating of int_expr when there is overlap p = Piecewise((1, And(5 > x, x > 1)), (2, Or(x < 3, x > 7)), (4, x < 8)) assert p.integrate((x, 0, 10)) == 20 # And with Eq arg handling assert Piecewise((1, x < 1), (2, And(Eq(x, 3), x > 1))).integrate( (x, 0, 3)) == S.NaN assert Piecewise((1, x < 1), (2, And(Eq(x, 3), x > 1)), (3, True)).integrate((x, 0, 3)) == 7 assert Piecewise((1, x < 0), (2, And(Eq(x, 3), x < 1)), (3, True)).integrate((x, -1, 1)) == 4 # middle condition doesn't matter: it's a zero width interval assert Piecewise((1, x < 1), (2, Eq(x, 3) & (y < x)), (3, True)).integrate( (x, 0, 3)) == 7
from sympy import symbols from sympy import plot_implicit from sympy import And x, y = symbols('x, y') print("EJERCICIOS \n ") print("1. \n 2x+y <5") plot_implicit(2*x + y < 5, (x,0,8), (y,0,8)) print("2. \n y <= 5") plot_implicit(y <= 5, (x,0,8), (y,0,8)) print("3. \n 2(2x-y)<2(x+y)-4") plot_implicit(2*x - 4*y < -4, (x,-8,8), (y,-6,8)) print("4. \n 2x+y > 3 \n 2y-1 > 0 \n x >= y") plot_implicit(And(2*x + y > 3, 2*y -1 > 0, x >= y), (x,-8,8), (y,-8,8)) print("5. \n 2x+3y <= 60 \n x >= 0 \n y >= 0") plot_implicit(And(2*x + 3*y <=60, x >= 0, y >= 0), (x,-10,35), (y,-10,25))
def test_issue_10122(): assert solve(abs(x) + abs(x - 1) - 1 > 0, x) == Or(And(-oo < x, x < 0), And(S.One < x, x < oo))
def delta(self, l, X): v = True for i in self.formulas: v = And(v, i.delta(l, X)) return v
def as_boolean(self): return Or( *[And(*[Eq(sym, val) for sym, val in item]) for item in self])
def delta(self, l, X): f, g = self.formulas[0:2] f, g = f.delta(l, X), g.delta(l, X) return Or(And(f, g), And(Not(f), Not(g)))
def plot_and_save(name): tmp_file = TmpFileManager.tmp_file x = Symbol('x') y = Symbol('y') z = Symbol('z') ### # Examples from the 'introduction' notebook ### p = plot(x) p = plot(x * sin(x), x * cos(x)) p.extend(p) p[0].line_color = lambda a: a p[1].line_color = 'b' p.title = 'Big title' p.xlabel = 'the x axis' p[1].label = 'straight line' p.legend = True p.aspect_ratio = (1, 1) p.xlim = (-15, 20) p.save(tmp_file('%s_basic_options_and_colors' % name)) p._backend.close() p.extend(plot(x + 1)) p.append(plot(x + 3, x**2)[1]) p.save(tmp_file('%s_plot_extend_append' % name)) p[2] = plot(x**2, (x, -2, 3)) p.save(tmp_file('%s_plot_setitem' % name)) p._backend.close() p = plot(sin(x), (x, -2 * pi, 4 * pi)) p.save(tmp_file('%s_line_explicit' % name)) p._backend.close() p = plot(sin(x)) p.save(tmp_file('%s_line_default_range' % name)) p._backend.close() p = plot((x**2, (x, -5, 5)), (x**3, (x, -3, 3))) p.save(tmp_file('%s_line_multiple_range' % name)) p._backend.close() raises(ValueError, lambda: plot(x, y)) #Piecewise plots p = plot(Piecewise((1, x > 0), (0, True)), (x, -1, 1)) p.save(tmp_file('%s_plot_piecewise' % name)) p._backend.close() p = plot(Piecewise((x, x < 1), (x**2, True)), (x, -3, 3)) p.save(tmp_file('%s_plot_piecewise_2' % name)) p._backend.close() # test issue 7471 p1 = plot(x) p2 = plot(3) p1.extend(p2) p.save(tmp_file('%s_horizontal_line' % name)) p._backend.close() # test issue 10925 f = Piecewise((-1, x < -1), (x, And(-1 <= x, x < 0)), \ (x**2, And(0 <= x, x < 1)), (x**3, x >= 1)) p = plot(f, (x, -3, 3)) p.save(tmp_file('%s_plot_piecewise_3' % name)) p._backend.close() #parametric 2d plots. #Single plot with default range. plot_parametric(sin(x), cos(x)).save(tmp_file()) #Single plot with range. p = plot_parametric(sin(x), cos(x), (x, -5, 5)) p.save(tmp_file('%s_parametric_range' % name)) p._backend.close() #Multiple plots with same range. p = plot_parametric((sin(x), cos(x)), (x, sin(x))) p.save(tmp_file('%s_parametric_multiple' % name)) p._backend.close() #Multiple plots with different ranges. p = plot_parametric((sin(x), cos(x), (x, -3, 3)), (x, sin(x), (x, -5, 5))) p.save(tmp_file('%s_parametric_multiple_ranges' % name)) p._backend.close() #depth of recursion specified. p = plot_parametric(x, sin(x), depth=13) p.save(tmp_file('%s_recursion_depth' % name)) p._backend.close() #No adaptive sampling. p = plot_parametric(cos(x), sin(x), adaptive=False, nb_of_points=500) p.save(tmp_file('%s_adaptive' % name)) p._backend.close() #3d parametric plots p = plot3d_parametric_line(sin(x), cos(x), x) p.save(tmp_file('%s_3d_line' % name)) p._backend.close() p = plot3d_parametric_line((sin(x), cos(x), x, (x, -5, 5)), (cos(x), sin(x), x, (x, -3, 3))) p.save(tmp_file('%s_3d_line_multiple' % name)) p._backend.close() p = plot3d_parametric_line(sin(x), cos(x), x, nb_of_points=30) p.save(tmp_file('%s_3d_line_points' % name)) p._backend.close() # 3d surface single plot. p = plot3d(x * y) p.save(tmp_file('%s_surface' % name)) p._backend.close() # Multiple 3D plots with same range. p = plot3d(-x * y, x * y, (x, -5, 5)) p.save(tmp_file('%s_surface_multiple' % name)) p._backend.close() # Multiple 3D plots with different ranges. p = plot3d((x * y, (x, -3, 3), (y, -3, 3)), (-x * y, (x, -3, 3), (y, -3, 3))) p.save(tmp_file('%s_surface_multiple_ranges' % name)) p._backend.close() # Single Parametric 3D plot p = plot3d_parametric_surface(sin(x + y), cos(x - y), x - y) p.save(tmp_file('%s_parametric_surface' % name)) p._backend.close() # Multiple Parametric 3D plots. p = plot3d_parametric_surface( (x * sin(z), x * cos(z), z, (x, -5, 5), (z, -5, 5)), (sin(x + y), cos(x - y), x - y, (x, -5, 5), (y, -5, 5))) p.save(tmp_file('%s_parametric_surface' % name)) p._backend.close() # Single Contour plot. p = plot_contour(sin(x) * sin(y), (x, -5, 5), (y, -5, 5)) p.save(tmp_file('%s_contour_plot' % name)) p._backend.close() # Multiple Contour plots with same range. p = plot_contour(x**2 + y**2, x**3 + y**3, (x, -5, 5), (y, -5, 5)) p.save(tmp_file('%s_contour_plot' % name)) p._backend.close() # Multiple Contour plots with different range. p = plot_contour((x**2 + y**2, (x, -5, 5), (y, -5, 5)), (x**3 + y**3, (x, -3, 3), (y, -3, 3))) p.save(tmp_file('%s_contour_plot' % name)) p._backend.close() ### # Examples from the 'colors' notebook ### p = plot(sin(x)) p[0].line_color = lambda a: a p.save(tmp_file('%s_colors_line_arity1' % name)) p[0].line_color = lambda a, b: b p.save(tmp_file('%s_colors_line_arity2' % name)) p._backend.close() p = plot(x * sin(x), x * cos(x), (x, 0, 10)) p[0].line_color = lambda a: a p.save(tmp_file('%s_colors_param_line_arity1' % name)) p[0].line_color = lambda a, b: a p.save(tmp_file('%s_colors_param_line_arity2a' % name)) p[0].line_color = lambda a, b: b p.save(tmp_file('%s_colors_param_line_arity2b' % name)) p._backend.close() p = plot3d_parametric_line( sin(x) + 0.1 * sin(x) * cos(7 * x), cos(x) + 0.1 * cos(x) * cos(7 * x), 0.1 * sin(7 * x), (x, 0, 2 * pi)) p[0].line_color = lambdify_(x, sin(4 * x)) p.save(tmp_file('%s_colors_3d_line_arity1' % name)) p[0].line_color = lambda a, b: b p.save(tmp_file('%s_colors_3d_line_arity2' % name)) p[0].line_color = lambda a, b, c: c p.save(tmp_file('%s_colors_3d_line_arity3' % name)) p._backend.close() p = plot3d(sin(x) * y, (x, 0, 6 * pi), (y, -5, 5)) p[0].surface_color = lambda a: a p.save(tmp_file('%s_colors_surface_arity1' % name)) p[0].surface_color = lambda a, b: b p.save(tmp_file('%s_colors_surface_arity2' % name)) p[0].surface_color = lambda a, b, c: c p.save(tmp_file('%s_colors_surface_arity3a' % name)) p[0].surface_color = lambdify_((x, y, z), sqrt((x - 3 * pi)**2 + y**2)) p.save(tmp_file('%s_colors_surface_arity3b' % name)) p._backend.close() p = plot3d_parametric_surface(x * cos(4 * y), x * sin(4 * y), y, (x, -1, 1), (y, -1, 1)) p[0].surface_color = lambda a: a p.save(tmp_file('%s_colors_param_surf_arity1' % name)) p[0].surface_color = lambda a, b: a * b p.save(tmp_file('%s_colors_param_surf_arity2' % name)) p[0].surface_color = lambdify_((x, y, z), sqrt(x**2 + y**2 + z**2)) p.save(tmp_file('%s_colors_param_surf_arity3' % name)) p._backend.close() ### # Examples from the 'advanced' notebook ### # XXX: This raises the warning "The evaluation of the expression is # problematic. We are trying a failback method that may still work. Please # report this as a bug." It has to use the fallback because using evalf() # is the only way to evaluate the integral. We should perhaps just remove # that warning. with warnings.catch_warnings(record=True) as w: i = Integral(log((sin(x)**2 + 1) * sqrt(x**2 + 1)), (x, 0, y)) p = plot(i, (y, 1, 5)) p.save(tmp_file('%s_advanced_integral' % name)) p._backend.close() # Make sure no other warnings were raised for i in w: assert issubclass(i.category, UserWarning) assert "The evaluation of the expression is problematic" in str( i.message) s = Sum(1 / x**y, (x, 1, oo)) p = plot(s, (y, 2, 10)) p.save(tmp_file('%s_advanced_inf_sum' % name)) p._backend.close() p = plot(Sum(1 / x, (x, 1, y)), (y, 2, 10), show=False) p[0].only_integers = True p[0].steps = True p.save(tmp_file('%s_advanced_fin_sum' % name)) p._backend.close() ### # Test expressions that can not be translated to np and generate complex # results. ### plot(sin(x) + I * cos(x)).save(tmp_file()) plot(sqrt(sqrt(-x))).save(tmp_file()) plot(LambertW(x)).save(tmp_file()) plot(sqrt(LambertW(x))).save(tmp_file()) #Characteristic function of a StudentT distribution with nu=10 plot((meijerg( ((1 / 2, ), ()), ((5, 0, 1 / 2), ()), 5 * x**2 * exp_polar(-I * pi) / 2) + meijerg( ((1 / 2, ), ()), ((5, 0, 1 / 2), ()), 5 * x**2 * exp_polar(I * pi) / 2)) / (48 * pi), (x, 1e-6, 1e-2)).save(tmp_file())
def test_meijerint(): from sympy import symbols, expand, arg s, t, mu = symbols('s t mu', real=True) assert integrate( meijerg([], [], [0], [], s * t) * meijerg([], [], [mu / 2], [-mu / 2], t**2 / 4), (t, 0, oo)).is_Piecewise s = symbols('s', positive=True) assert integrate(x**s*meijerg([[], []], [[0], []], x), (x, 0, oo)) == \ gamma(s + 1) assert integrate(x**s * meijerg([[], []], [[0], []], x), (x, 0, oo), meijerg=True) == gamma(s + 1) assert isinstance( integrate(x**s * meijerg([[], []], [[0], []], x), (x, 0, oo), meijerg=False), Integral) assert meijerint_indefinite(exp(x), x) == exp(x) # TODO what simplifications should be done automatically? # This tests "extra case" for antecedents_1. a, b = symbols('a b', positive=True) assert simplify(meijerint_definite(x**a, x, 0, b)[0]) == \ b**(a + 1)/(a + 1) # This tests various conditions and expansions: meijerint_definite((x + 1)**3 * exp(-x), x, 0, oo) == (16, True) # Again, how about simplifications? sigma, mu = symbols('sigma mu', positive=True) i, c = meijerint_definite(exp(-((x - mu) / (2 * sigma))**2), x, 0, oo) assert simplify(i) == sqrt(pi) * sigma * (2 - erfc(mu / (2 * sigma))) assert c == True i, _ = meijerint_definite(exp(-mu * x) * exp(sigma * x), x, 0, oo) # TODO it would be nice to test the condition assert simplify(i) == 1 / (mu - sigma) # Test substitutions to change limits assert meijerint_definite(exp(x), x, -oo, 2) == (exp(2), True) # Note: causes a NaN in _check_antecedents assert expand(meijerint_definite(exp(x), x, 0, I)[0]) == exp(I) - 1 assert expand(meijerint_definite(exp(-x), x, 0, x)[0]) == \ 1 - exp(-exp(I*arg(x))*abs(x)) # Test -oo to oo assert meijerint_definite(exp(-x**2), x, -oo, oo) == (sqrt(pi), True) assert meijerint_definite(exp(-abs(x)), x, -oo, oo) == (2, True) assert meijerint_definite(exp(-(2*x - 3)**2), x, -oo, oo) == \ (sqrt(pi)/2, True) assert meijerint_definite(exp(-abs(2 * x - 3)), x, -oo, oo) == (1, True) assert meijerint_definite( exp(-((x - mu) / sigma)**2 / 2) / sqrt(2 * pi * sigma**2), x, -oo, oo) == (1, True) assert meijerint_definite(sinc(x)**2, x, -oo, oo) == (pi, True) # Test one of the extra conditions for 2 g-functinos assert meijerint_definite(exp(-x) * sin(x), x, 0, oo) == (S.Half, True) # Test a bug def res(n): return (1 / (1 + x**2)).diff(x, n).subs(x, 1) * (-1)**n for n in range(6): assert integrate(exp(-x)*sin(x)*x**n, (x, 0, oo), meijerg=True) == \ res(n) # This used to test trigexpand... now it is done by linear substitution assert simplify(integrate(exp(-x) * sin(x + a), (x, 0, oo), meijerg=True)) == sqrt(2) * sin(a + pi / 4) / 2 # Test the condition 14 from prudnikov. # (This is besselj*besselj in disguise, to stop the product from being # recognised in the tables.) a, b, s = symbols('a b s') from sympy import And, re assert meijerint_definite(meijerg([], [], [a/2], [-a/2], x/4) *meijerg([], [], [b/2], [-b/2], x/4)*x**(s - 1), x, 0, oo) == \ (4*2**(2*s - 2)*gamma(-2*s + 1)*gamma(a/2 + b/2 + s) /(gamma(-a/2 + b/2 - s + 1)*gamma(a/2 - b/2 - s + 1) *gamma(a/2 + b/2 - s + 1)), And(0 < -2*re(4*s) + 8, 0 < re(a/2 + b/2 + s), re(2*s) < 1)) # test a bug assert integrate(sin(x**a)*sin(x**b), (x, 0, oo), meijerg=True) == \ Integral(sin(x**a)*sin(x**b), (x, 0, oo)) # test better hyperexpand assert integrate(exp(-x**2)*log(x), (x, 0, oo), meijerg=True) == \ (sqrt(pi)*polygamma(0, S.Half)/4).expand() # Test hyperexpand bug. from sympy import lowergamma n = symbols('n', integer=True) assert simplify(integrate(exp(-x)*x**n, x, meijerg=True)) == \ lowergamma(n + 1, x) # Test a bug with argument 1/x alpha = symbols('alpha', positive=True) assert meijerint_definite((2 - x)**alpha*sin(alpha/x), x, 0, 2) == \ (sqrt(pi)*alpha*gamma(alpha + 1)*meijerg(((), (alpha/2 + S.Half, alpha/2 + 1)), ((0, 0, S.Half), (Rational(-1, 2),)), alpha**2/16)/4, True) # test a bug related to 3016 a, s = symbols('a s', positive=True) assert simplify(integrate(x**s*exp(-a*x**2), (x, -oo, oo))) == \ a**(-s/2 - S.Half)*((-1)**s + 1)*gamma(s/2 + S.Half)/2
def test_Intersection_as_relational(): x = Symbol('x') assert (Intersection(Interval(0, 1), FiniteSet(2), evaluate=False).as_relational(x) == And( And(Le(0, x), Le(x, 1)), Eq(x, 2)))
def test_manualintegrate_inversetrig(): # atan assert manualintegrate(exp(x) / (1 + exp(2 * x)), x) == atan(exp(x)) assert manualintegrate(1 / (4 + 9 * x**2), x) == atan(3 * x / 2) / 6 assert manualintegrate(1 / (16 + 16 * x**2), x) == atan(x) / 16 assert manualintegrate(1 / (4 + x**2), x) == atan(x / 2) / 2 assert manualintegrate(1 / (1 + 4 * x**2), x) == atan(2 * x) / 2 assert manualintegrate(1/(a + b*x**2), x) == \ Piecewise((atan(x/sqrt(a/b))/(b*sqrt(a/b)), a/b > 0), \ (-acoth(x/sqrt(-a/b))/(b*sqrt(-a/b)), And(a/b < 0, x**2 > -a/b)), \ (-atanh(x/sqrt(-a/b))/(b*sqrt(-a/b)), And(a/b < 0, x**2 < -a/b))) assert manualintegrate(1/(4 + b*x**2), x) == \ Piecewise((atan(x/(2*sqrt(1/b)))/(2*b*sqrt(1/b)), 4/b > 0), \ (-acoth(x/(2*sqrt(-1/b)))/(2*b*sqrt(-1/b)), And(4/b < 0, x**2 > -4/b)), \ (-atanh(x/(2*sqrt(-1/b)))/(2*b*sqrt(-1/b)), And(4/b < 0, x**2 < -4/b))) assert manualintegrate(1/(a + 4*x**2), x) == \ Piecewise((atan(2*x/sqrt(a))/(2*sqrt(a)), a/4 > 0), \ (-acoth(2*x/sqrt(-a))/(2*sqrt(-a)), And(a/4 < 0, x**2 > -a/4)), \ (-atanh(2*x/sqrt(-a))/(2*sqrt(-a)), And(a/4 < 0, x**2 < -a/4))) assert manualintegrate(1 / (4 + 4 * x**2), x) == atan(x) / 4 # asin assert manualintegrate(1 / sqrt(1 - x**2), x) == asin(x) assert manualintegrate(1 / sqrt(4 - 4 * x**2), x) == asin(x) / 2 assert manualintegrate(3 / sqrt(1 - 9 * x**2), x) == asin(3 * x) assert manualintegrate(1 / sqrt(4 - 9 * x**2), x) == asin(3 * x / 2) / 3 # asinh assert manualintegrate(1/sqrt(x**2 + 1), x) == \ asinh(x) assert manualintegrate(1/sqrt(x**2 + 4), x) == \ asinh(x/2) assert manualintegrate(1/sqrt(4*x**2 + 4), x) == \ asinh(x)/2 assert manualintegrate(1/sqrt(4*x**2 + 1), x) == \ asinh(2*x)/2 assert manualintegrate(1/sqrt(a*x**2 + 1), x) == \ Piecewise((sqrt(-1/a)*asin(x*sqrt(-a)), a < 0), (sqrt(1/a)*asinh(sqrt(a)*x), a > 0)) assert manualintegrate(1/sqrt(a + x**2), x) == \ Piecewise((asinh(x*sqrt(1/a)), a > 0), (acosh(x*sqrt(-1/a)), a < 0)) # acosh assert manualintegrate(1/sqrt(x**2 - 1), x) == \ acosh(x) assert manualintegrate(1/sqrt(x**2 - 4), x) == \ acosh(x/2) assert manualintegrate(1/sqrt(4*x**2 - 4), x) == \ acosh(x)/2 assert manualintegrate(1/sqrt(9*x**2 - 1), x) == \ acosh(3*x)/3 assert manualintegrate(1/sqrt(a*x**2 - 4), x) == \ Piecewise((sqrt(1/a)*acosh(sqrt(a)*x/2), a > 0)) assert manualintegrate(1/sqrt(-a + 4*x**2), x) == \ Piecewise((asinh(2*x*sqrt(-1/a))/2, -a > 0), (acosh(2*x*sqrt(1/a))/2, -a < 0)) # piecewise assert manualintegrate(1/sqrt(a-b*x**2), x) == \ Piecewise((sqrt(a/b)*asin(x*sqrt(b/a))/sqrt(a), And(-b < 0, a > 0)), (sqrt(-a/b)*asinh(x*sqrt(-b/a))/sqrt(a), And(-b > 0, a > 0)), (sqrt(a/b)*acosh(x*sqrt(b/a))/sqrt(-a), And(-b > 0, a < 0))) assert manualintegrate(1/sqrt(a + b*x**2), x) == \ Piecewise((sqrt(-a/b)*asin(x*sqrt(-b/a))/sqrt(a), And(a > 0, b < 0)), (sqrt(a/b)*asinh(x*sqrt(b/a))/sqrt(a), And(a > 0, b > 0)), (sqrt(-a/b)*acosh(x*sqrt(-b/a))/sqrt(-a), And(a < 0, b > 0)))
def newtons_method(expr, wrt, atol=1e-12, delta=None, debug=False, itermax=None, counter=None): """ Generates an AST for Newton-Raphson method (a root-finding algorithm). Returns an abstract syntax tree (AST) based on ``sympy.codegen.ast`` for Netwon's method of root-finding. Parameters ========== expr : expression wrt : Symbol With respect to, i.e. what is the variable. atol : number or expr Absolute tolerance (stopping criterion) delta : Symbol Will be a ``Dummy`` if ``None``. debug : bool Whether to print convergence information during iterations itermax : number or expr Maximum number of iterations. counter : Symbol Will be a ``Dummy`` if ``None``. Examples ======== >>> from sympy import symbols, cos >>> from sympy.codegen.ast import Assignment >>> from sympy.codegen.algorithms import newtons_method >>> x, dx, atol = symbols('x dx atol') >>> expr = cos(x) - x**3 >>> algo = newtons_method(expr, x, atol, dx) >>> algo.has(Assignment(dx, -expr/expr.diff(x))) True References ========== .. [1] https://en.wikipedia.org/wiki/Newton%27s_method """ if delta is None: delta = Dummy() Wrapper = Scope name_d = 'delta' else: Wrapper = lambda x: x name_d = delta.name delta_expr = -expr / expr.diff(wrt) whl_bdy = [ Assignment(delta, delta_expr), AddAugmentedAssignment(wrt, delta) ] if debug: prnt = Print([wrt, delta], r"{0}=%12.5g {1}=%12.5g\n".format(wrt.name, name_d)) whl_bdy = [whl_bdy[0], prnt] + whl_bdy[1:] req = Gt(Abs(delta), atol) declars = [Declaration(Variable(delta, type=real, value=oo))] if itermax is not None: counter = counter or Dummy(integer=True) v_counter = Variable.deduced(counter, 0) declars.append(Declaration(v_counter)) whl_bdy.append(AddAugmentedAssignment(counter, 1)) req = And(req, Lt(counter, itermax)) whl = While(req, CodeBlock(*whl_bdy)) blck = declars + [whl] return Wrapper(CodeBlock(*blck))
def test_piecewise(): # Test canonicalization assert Piecewise((x, x < 1), (0, True)) == Piecewise((x, x < 1), (0, True)) assert Piecewise((x, x < 1), (0, True), (1, True)) == \ Piecewise((x, x < 1), (0, True)) assert Piecewise((x, x < 1), (0, False), (-1, 1 > 2)) == \ Piecewise((x, x < 1)) assert Piecewise((x, x < 1), (0, x < 1), (0, True)) == \ Piecewise((x, x < 1), (0, True)) assert Piecewise((x, x < 1), (0, x < 2), (0, True)) == \ Piecewise((x, x < 1), (0, True)) assert Piecewise((x, x < 1), (x, x < 2), (0, True)) == \ Piecewise((x, Or(x < 1, x < 2)), (0, True)) assert Piecewise((x, x < 1), (x, x < 2), (x, True)) == x assert Piecewise((x, True)) == x # False condition is never retained assert Piecewise((x, False)) == Piecewise( (x, False), evaluate=False) == Piecewise() raises(TypeError, lambda: Piecewise(x)) assert Piecewise((x, 1)) == x # 1 and 0 are accepted as True/False raises(TypeError, lambda: Piecewise((x, 2))) raises(TypeError, lambda: Piecewise((x, x**2))) raises(TypeError, lambda: Piecewise(([1], True))) assert Piecewise(((1, 2), True)) == Tuple(1, 2) cond = (Piecewise((1, x < 0), (2, True)) < y) assert Piecewise((1, cond)) == Piecewise((1, ITE(x < 0, y > 1, y > 2))) assert Piecewise((1, x > 0), (2, And(x <= 0, x > -1))) == Piecewise( (1, x > 0), (2, x > -1)) # Test subs p = Piecewise((-1, x < -1), (x**2, x < 0), (log(x), x >= 0)) p_x2 = Piecewise((-1, x**2 < -1), (x**4, x**2 < 0), (log(x**2), x**2 >= 0)) assert p.subs(x, x**2) == p_x2 assert p.subs(x, -5) == -1 assert p.subs(x, -1) == 1 assert p.subs(x, 1) == log(1) # More subs tests p2 = Piecewise((1, x < pi), (-1, x < 2 * pi), (0, x > 2 * pi)) p3 = Piecewise((1, Eq(x, 0)), (1 / x, True)) p4 = Piecewise((1, Eq(x, 0)), (2, 1 / x > 2)) assert p2.subs(x, 2) == 1 assert p2.subs(x, 4) == -1 assert p2.subs(x, 10) == 0 assert p3.subs(x, 0.0) == 1 assert p4.subs(x, 0.0) == 1 f, g, h = symbols('f,g,h', cls=Function) pf = Piecewise((f(x), x < -1), (f(x) + h(x) + 2, x <= 1)) pg = Piecewise((g(x), x < -1), (g(x) + h(x) + 2, x <= 1)) assert pg.subs(g, f) == pf assert Piecewise((1, Eq(x, 0)), (0, True)).subs(x, 0) == 1 assert Piecewise((1, Eq(x, 0)), (0, True)).subs(x, 1) == 0 assert Piecewise((1, Eq(x, y)), (0, True)).subs(x, y) == 1 assert Piecewise((1, Eq(x, z)), (0, True)).subs(x, z) == 1 assert Piecewise((1, Eq(exp(x), cos(z))), (0, True)).subs(x, z) == \ Piecewise((1, Eq(exp(z), cos(z))), (0, True)) p5 = Piecewise((0, Eq(cos(x) + y, 0)), (1, True)) assert p5.subs(y, 0) == Piecewise((0, Eq(cos(x), 0)), (1, True)) assert Piecewise((-1, y < 1), (0, x < 0), (1, Eq(x, 0)), (2, True)).subs(x, 1) == Piecewise((-1, y < 1), (2, True)) assert Piecewise((1, Eq(x**2, -1)), (2, x < 0)).subs(x, I) == 1 # Test evalf assert p.evalf() == p assert p.evalf(subs={x: -2}) == -1 assert p.evalf(subs={x: -1}) == 1 assert p.evalf(subs={x: 1}) == log(1) # Test doit f_int = Piecewise((Integral(x, (x, 0, 1)), x < 1)) assert f_int.doit() == Piecewise((1 / 2, x < 1)) # Test differentiation f = x fp = x * p dp = Piecewise((0, x < -1), (2 * x, x < 0), (1 / x, x >= 0)) fp_dx = x * dp + p assert diff(p, x) == dp assert diff(f * p, x) == fp_dx # Test simple arithmetic assert x * p == fp assert x * p + p == p + x * p assert p + f == f + p assert p + dp == dp + p assert p - dp == -(dp - p) # Test power dp2 = Piecewise((0, x < -1), (4 * x**2, x < 0), (1 / x**2, x >= 0)) assert dp**2 == dp2 # Test _eval_interval f1 = x * y + 2 f2 = x * y**2 + 3 peval = Piecewise((f1, x < 0), (f2, x > 0)) peval_interval = f1.subs(x, 0) - f1.subs(x, -1) + f2.subs(x, 1) - f2.subs( x, 0) assert peval._eval_interval(x, 0, 0) == 0 assert peval._eval_interval(x, -1, 1) == peval_interval peval2 = Piecewise((f1, x < 0), (f2, True)) assert peval2._eval_interval(x, 0, 0) == 0 assert peval2._eval_interval(x, 1, -1) == -peval_interval assert peval2._eval_interval(x, -1, -2) == f1.subs(x, -2) - f1.subs(x, -1) assert peval2._eval_interval(x, -1, 1) == peval_interval assert peval2._eval_interval(x, None, 0) == peval2.subs(x, 0) assert peval2._eval_interval(x, -1, None) == -peval2.subs(x, -1) # Test integration assert p.integrate() == Piecewise((-x, x < -1), (x**3 / 3 + 4 / 3, x < 0), (x * log(x) - x + 4 / 3, True)) p = Piecewise((x, x < 1), (x**2, -1 <= x), (x, 3 < x)) assert integrate(p, (x, -2, 2)) == 5 / 6.0 assert integrate(p, (x, 2, -2)) == -5 / 6.0 p = Piecewise((0, x < 0), (1, x < 1), (0, x < 2), (1, x < 3), (0, True)) assert integrate(p, (x, -oo, oo)) == 2 p = Piecewise((x, x < -10), (x**2, x <= -1), (x, 1 < x)) assert integrate(p, (x, -2, 2)) == Undefined # Test commutativity assert isinstance(p, Piecewise) and p.is_commutative is True
def as_boolean(self): return And(*[domain.as_boolean() for domain in self.domains])
def test_piecewise_solve(): abs2 = Piecewise((-x, x <= 0), (x, x > 0)) f = abs2.subs(x, x - 2) assert solve(f, x) == [2] assert solve(f - 1, x) == [1, 3] f = Piecewise(((x - 2)**2, x >= 0), (1, True)) assert solve(f, x) == [2] g = Piecewise(((x - 5)**5, x >= 4), (f, True)) assert solve(g, x) == [2, 5] g = Piecewise(((x - 5)**5, x >= 4), (f, x < 4)) assert solve(g, x) == [2, 5] g = Piecewise(((x - 5)**5, x >= 2), (f, x < 2)) assert solve(g, x) == [5] g = Piecewise(((x - 5)**5, x >= 2), (f, True)) assert solve(g, x) == [5] g = Piecewise(((x - 5)**5, x >= 2), (f, True), (10, False)) assert solve(g, x) == [5] g = Piecewise(((x - 5)**5, x >= 2), (-x + 2, x - 2 <= 0), (x - 2, x - 2 > 0)) assert solve(g, x) == [5] # if no symbol is given the piecewise detection must still work assert solve(Piecewise((x - 2, x > 2), (2 - x, True)) - 3) == [-1, 5] f = Piecewise(((x - 2)**2, x >= 0), (0, True)) raises(NotImplementedError, lambda: solve(f, x)) def nona(ans): return list(filter(lambda x: x is not S.NaN, ans)) p = Piecewise((x**2 - 4, x < y), (x - 2, True)) ans = solve(p, x) assert nona([i.subs(y, -2) for i in ans]) == [2] assert nona([i.subs(y, 2) for i in ans]) == [-2, 2] assert nona([i.subs(y, 3) for i in ans]) == [-2, 2] assert ans == [ Piecewise((-2, y > -2), (S.NaN, True)), Piecewise((2, y <= 2), (S.NaN, True)), Piecewise((2, y > 2), (S.NaN, True)) ] # issue 6060 absxm3 = Piecewise((x - 3, S(0) <= x - 3), (3 - x, S(0) > x - 3)) assert solve(absxm3 - y, x) == [ Piecewise((-y + 3, -y < 0), (S.NaN, True)), Piecewise((y + 3, y >= 0), (S.NaN, True)) ] p = Symbol('p', positive=True) assert solve(absxm3 - p, x) == [-p + 3, p + 3] # issue 6989 f = Function('f') assert solve(Eq(-f(x), Piecewise((1, x > 0), (0, True))), f(x)) == \ [Piecewise((-1, x > 0), (0, True))] # issue 8587 f = Piecewise((2 * x**2, And(S(0) < x, x < 1)), (2, True)) assert solve(f - 1) == [1 / sqrt(2)]
def test_reduce_inequalities_boolean(): assert reduce_inequalities([Eq(x**2, 0), True]) == And(Eq(re(x), 0), Eq(im(x), 0)) assert reduce_inequalities([Eq(x**2, 0), False]) == False
def test_solve_univariate_inequality(): assert isolve(x**2 >= 4, x, relational=False) == Union(Interval(-oo, -2), Interval(2, oo)) assert isolve(x**2 >= 4, x) == Or(And(Le(2, x), Lt(x, oo)), And(Le(x, -2), Lt(-oo, x))) assert isolve((x - 1)*(x - 2)*(x - 3) >= 0, x, relational=False) == \ Union(Interval(1, 2), Interval(3, oo)) assert isolve((x - 1)*(x - 2)*(x - 3) >= 0, x) == \ Or(And(Le(1, x), Le(x, 2)), And(Le(3, x), Lt(x, oo))) # issue 2785: assert isolve(x**3 - 2*x - 1 > 0, x, relational=False) == \ Union(Interval(-1, -sqrt(5)/2 + S(1)/2, True, True), Interval(S(1)/2 + sqrt(5)/2, oo, True, True)) # issue 2794: assert isolve(x**3 - x**2 + x - 1 > 0, x, relational=False) == \ Interval(1, oo, True) # XXX should be limited in domain, e.g. between 0 and 2*pi assert isolve(sin(x) < S.Half, x) == \ Or(And(-oo < x, x < pi/6), And(5*pi/6 < x, x < oo)) assert isolve(sin(x) > S.Half, x) == And(pi / 6 < x, x < 5 * pi / 6) # numerical testing in valid() is needed assert isolve(x**7 - x - 2 > 0, x) == \ And(RootOf(x**7 - x - 2, 0) < x, x < oo) # handle numerator and denominator; although these would be handled as # rational inequalities, these test confirm that the right thing is done # when the domain is EX (e.g. when 2 is replaced with sqrt(2)) assert isolve(1 / (x - 2) > 0, x) == And(S(2) < x, x < oo) den = ((x - 1) * (x - 2)).expand() assert isolve((x - 1)/den <= 0, x) == \ Or(And(-oo < x, x < 1), And(S(1) < x, x < 2))