def test_issue_9556(): x = Symbol('x') b = Symbol('b', positive=True) assert solveset(Abs(x) + 1, x, S.Reals) == EmptySet() assert solveset(Abs(x) + b, x, S.Reals) == EmptySet() assert solveset(Eq(b, -1), b, S.Reals) == EmptySet()
def test_issue_9522(): x = Symbol('x') expr1 = Eq(1 / (x**2 - 4) + x, 1 / (x**2 - 4) + 2) expr2 = Eq(1 / x + x, 1 / x) assert solveset(expr1, x, S.Reals) == EmptySet() assert solveset(expr2, x, S.Reals) == EmptySet()
def test_Complement(): assert Complement(Interval(1, 3), Interval(1, 2)) == Interval(2, 3, True) assert Complement(FiniteSet(1, 3, 4), FiniteSet(3, 4)) == FiniteSet(1) assert Complement(Union(Interval(0, 2), FiniteSet(2, 3, 4)), Interval(1, 3)) == \ Union(Interval(0, 1, False, True), FiniteSet(4)) assert not 3 in Complement(Interval(0, 5), Interval(1, 4), evaluate=False) assert -1 in Complement(S.Reals, S.Naturals, evaluate=False) assert not 1 in Complement(S.Reals, S.Naturals, evaluate=False) assert Complement(S.Integers, S.UniversalSet) == EmptySet() assert S.UniversalSet.complement(S.Integers) == EmptySet() assert (not 0 in S.Reals.intersect(S.Integers - FiniteSet(0))) assert S.EmptySet - S.Integers == S.EmptySet assert (S.Integers - FiniteSet(0)) - FiniteSet(1) == S.Integers - FiniteSet(0, 1) assert S.Reals - Union(S.Naturals, FiniteSet(pi)) == \ Intersection(S.Reals - S.Naturals, S.Reals - FiniteSet(pi)) # issue 12712 assert Complement(FiniteSet(x, y, 2), Interval(-10, 10)) == \ Complement(FiniteSet(x, y), Interval(-10, 10))
def _print_Piecewise(self, expr): # Filter out default zeros since they are implicit in a TDB filtered_args = [i for i in expr.args if not ((i.cond == S.true) and (i.expr == S.Zero))] exprs = [self._print(arg.expr) for arg in filtered_args] # Only a small subset of piecewise functions can be represented # Need to verify that each cond's highlim equals the next cond's lowlim # to_interval() is used instead of sympy.Relational.as_set() for performance reasons intervals = [to_interval(i.cond) for i in filtered_args] if (len(intervals) > 1) and Intersection(intervals) != EmptySet(): raise ValueError('Overlapping intervals cannot be represented: {}'.format(intervals)) if not isinstance(Union(intervals), Interval): raise ValueError('Piecewise intervals must be continuous') if not all([arg.cond.free_symbols == {v.T} for arg in filtered_args]): raise ValueError('Only temperature-dependent piecewise conditions are supported') # Sort expressions based on intervals sortindices = [i[0] for i in sorted(enumerate(intervals), key=lambda x:x[1].start)] exprs = [exprs[idx] for idx in sortindices] intervals = [intervals[idx] for idx in sortindices] if len(exprs) > 1: result = '{1} {0}; {2} Y'.format(exprs[0], self._print(intervals[0].start), self._print(intervals[0].end)) result += 'Y'.join([' {0}; {1} '.format(expr, self._print(i.end)) for i, expr in zip(intervals[1:], exprs[1:])]) result += 'N' else: result = '{0} {1}; {2} N'.format(self._print(intervals[0].start), exprs[0], self._print(intervals[0].end)) return result
def test_bool_as_set(): x = symbols('x') assert And(x <= 2, x >= -2).as_set() == Interval(-2, 2) assert Or(x >= 2, x <= -2).as_set() == Interval(-oo, -2) + Interval(2, oo) assert Not(x > 2).as_set() == Interval(-oo, 2) assert true.as_set() == S.UniversalSet assert false.as_set() == EmptySet()
def test_issue_9623(): n = Symbol('n') a = S.Reals b = Interval(0, oo) c = FiniteSet(n) assert Intersection(a, b, c) == Intersection(b, c) assert Intersection(Interval(1, 2), Interval(3, 4), FiniteSet(n)) == EmptySet()
def test_invert_real(): x = Symbol('x', real=True) x = Dummy(real=True) n = Symbol('n') d = Dummy() assert solveset(abs(x) - n, x) == solveset(abs(x) - d, x) == EmptySet() n = Symbol('n', real=True) assert invert_real(x + 3, y, x) == (x, FiniteSet(y - 3)) assert invert_real(x * 3, y, x) == (x, FiniteSet(y / 3)) assert invert_real(exp(x), y, x) == (x, FiniteSet(log(y))) assert invert_real(exp(3 * x), y, x) == (x, FiniteSet(log(y) / 3)) assert invert_real(exp(x + 3), y, x) == (x, FiniteSet(log(y) - 3)) assert invert_real(exp(x) + 3, y, x) == (x, FiniteSet(log(y - 3))) assert invert_real(exp(x) * 3, y, x) == (x, FiniteSet(log(y / 3))) assert invert_real(log(x), y, x) == (x, FiniteSet(exp(y))) assert invert_real(log(3 * x), y, x) == (x, FiniteSet(exp(y) / 3)) assert invert_real(log(x + 3), y, x) == (x, FiniteSet(exp(y) - 3)) assert invert_real(Abs(x), y, x) == (x, FiniteSet(-y, y)) assert invert_real(2**x, y, x) == (x, FiniteSet(log(y) / log(2))) assert invert_real(2**exp(x), y, x) == (x, FiniteSet(log(log(y) / log(2)))) assert invert_real(x**2, y, x) == (x, FiniteSet(sqrt(y), -sqrt(y))) assert invert_real(x**Rational(1, 2), y, x) == (x, FiniteSet(y**2)) raises(ValueError, lambda: invert_real(x, x, x)) raises(ValueError, lambda: invert_real(x**pi, y, x)) raises(ValueError, lambda: invert_real(S.One, y, x)) assert invert_real(x**31 + x, y, x) == (x**31 + x, FiniteSet(y)) assert invert_real(Abs(x**31 + x + 1), y, x) == (x**31 + x, FiniteSet(-y - 1, y - 1)) assert invert_real(tan(x), y, x) == \ (x, imageset(Lambda(n, n*pi + atan(y)), S.Integers)) assert invert_real(tan(exp(x)), y, x) == \ (x, imageset(Lambda(n, log(n*pi + atan(y))), S.Integers)) assert invert_real(cot(x), y, x) == \ (x, imageset(Lambda(n, n*pi + acot(y)), S.Integers)) assert invert_real(cot(exp(x)), y, x) == \ (x, imageset(Lambda(n, log(n*pi + acot(y))), S.Integers)) assert invert_real(tan(tan(x)), y, x) == \ (tan(x), imageset(Lambda(n, n*pi + atan(y)), S.Integers)) x = Symbol('x', positive=True) assert invert_real(x**pi, y, x) == (x, FiniteSet(y**(1 / pi)))
def test_linsolve(): x, y, z, u, v, w = symbols("x, y, z, u, v, w") x1, x2, x3, x4 = symbols('x1, x2, x3, x4') # Test for different input forms M = Matrix([[1, 2, 1, 1, 7], [1, 2, 2, -1, 12], [2, 4, 0, 6, 4]]) system1 = A, b = M[:, :-1], M[:, -1] Eqns = [ x1 + 2 * x2 + x3 + x4 - 7, x1 + 2 * x2 + 2 * x3 - x4 - 12, 2 * x1 + 4 * x2 + 6 * x4 - 4 ] sol = FiniteSet((-2 * x2 - 3 * x4 + 2, x2, 2 * x4 + 5, x4)) assert linsolve(M, (x1, x2, x3, x4)) == sol assert linsolve(Eqns, (x1, x2, x3, x4)) == sol assert linsolve(system1, (x1, x2, x3, x4)) == sol # raise ValueError if no symbols are given raises(ValueError, lambda: linsolve(system1)) # raise ValueError if, A & b is not given as tuple raises(ValueError, lambda: linsolve(A, b, x1, x2, x3, x4)) # raise ValueError for garbage value raises(ValueError, lambda: linsolve(Eqns[0], x1, x2, x3, x4)) # Fully symbolic test a, b, c, d, e, f = symbols('a, b, c, d, e, f') A = Matrix([[a, b], [c, d]]) B = Matrix([[e], [f]]) system2 = (A, B) sol = FiniteSet((-b * (f - c * e / a) / (a * (d - b * c / a)) + e / a, (f - c * e / a) / (d - b * c / a))) assert linsolve(system2, [x, y]) == sol # Test for Dummy Symbols issue #9667 x1 = Dummy('x1') x2 = Dummy('x2') x3 = Dummy('x3') x4 = Dummy('x4') assert linsolve(system1, x1, x2, x3, x4) == FiniteSet( (-2 * x2 - 3 * x4 + 2, x2, 2 * x4 + 5, x4)) # No solution A = Matrix([[1, 2, 3], [2, 4, 6], [3, 6, 9]]) b = Matrix([0, 0, 1]) assert linsolve((A, b), (x, y, z)) == EmptySet() # Issue #10121 - Assignment of free variables a, b, c, d, e = symbols('a, b, c, d, e') Augmatrix = Matrix([[0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0]]) assert linsolve(Augmatrix, a, b, c, d, e) == FiniteSet((a, 0, c, 0, e))
def check_ui_unordered_finite_set(self): a = self.ui.value.replace(" ", "") allowed = "-0123456789{}," nums = re.findall("[-\d]+", a) if len(re.findall(",", a)) != len(nums)-1: return False if not all(c in allowed for c in a): return False if a[0] != '{' or a[-1] != '}': return False num_count = 0 for i in range(len(nums)): if a[i] == ',' and not a.index(nums[num_count]) < i and a[i+1] == ',': return False num_count += 1 finite_set = EmptySet() for i in range(len(nums)): finite_set = finite_set.union(FiniteSet(int(nums[i]))) return True if finite_set == self.result else False
def test_no_sol(): assert solveset_real(4, x) == EmptySet() assert solveset_real(exp(x), x) == EmptySet() assert solveset_real(x**2 + 1, x) == EmptySet() assert solveset_real(-3 * a / sqrt(x), x) == EmptySet() assert solveset_real(1 / x, x) == EmptySet() assert solveset_real(-(1 + x)/(2 + x)**2 + 1/(2 + x), x) == \ EmptySet()
def get_sign(function): logs = search_for(function, _class=sympy.log, found=[]) if not logs: in1 = sympy.solve(function < 0) in2 = sympy.solve(function > 0) return (inequation_to_interval(in1), inequation_to_interval(in2)) else: for _func in logs: _logs = search_for(_func, sympy.log, []) if not _logs: negative = inequation_to_interval(sympy.solve(_func > 0)) negative = negative.intersect( inequation_to_interval(sympy.solve(_func < 1))) # print sympy.solve(_func > 1) positive = inequation_to_interval(sympy.solve(_func > 1)) break # FIXME: Y si hay más logaritmos? """ if positive.__class__ != EmptySet: positive -= Interval(positive.start, positive.start) positive -= Interval(positive.end, positive.end) if negative.__class__ != EmptySet: negative -= Interval(negative.start, negative.start) negative -= Interval(negative.end, negative.end) for root in get_roots(function): positive -= Interval(root, root) negative -= Interval(root, root) """ return ( negative or EmptySet(), positive or EmptySet(), )
def defragmentation(self, frg): flow_id = frg.flow_id total_size = frg.t_size fragments = list(msg for msg in self.store.items if msg.id == frg.id) defragment = EmptySet().union(Interval(frg.f_offset, frg.f_offset + frg.size) for frg in fragments) if defragment.measure == total_size: pkt = Packet(*fragments[0].make_args_for_defragment()) for frg in fragments: self.store.items.remove(frg) pkt.dfg_time = self.env.now logging.debug(self.env.now, pkt) return pkt
def test_issue_10326(): bad = [ EmptySet(), FiniteSet(1), Interval(1, 2), S.ComplexInfinity, S.ImaginaryUnit, S.Infinity, S.NaN, S.NegativeInfinity, ] interval = Interval(0, 5) for i in bad: assert i not in interval x = Symbol('x', real=True) nr = Symbol('nr', real=False) assert x + 1 in Interval(x, x + 4) assert nr not in Interval(x, x + 4) assert Interval(1, 2) in FiniteSet(Interval(0, 5), Interval(1, 2)) assert Interval(-oo, oo).contains(oo) is S.false assert Interval(-oo, oo).contains(-oo) is S.false
def put(self, pkt): if not self.selector or self.selector(pkt): now = self.env.now if self.rec_waits: self.waits.append(self.env.now - pkt.s_time) if self.rec_arrivals: if self.absolute_arrivals: self.arrivals.append(now) else: self.arrivals.append(now - self.last_arrival) self.last_arrival = now self.p_counters.fragments_rec += 1 self.bytes_rec += pkt.size self.store.put(pkt) if pkt.id not in self.packets_to_defragment: self.packets_to_defragment[pkt.id] = EmptySet() self.packets_to_defragment[pkt.id] = self.packets_to_defragment[pkt.id]\ .union(Interval(pkt.f_offset, pkt.f_offset + pkt.size)) if self.packets_to_defragment[pkt.id].measure == pkt.t_size: defragmented_pkt = self.defragmentation(pkt) self.p_counters.packets_rec += 1 self.check_dfg_pkt(defragmented_pkt)
def test_solve_lambert(): assert solveset_real(x * exp(x) - 1, x) == FiniteSet(LambertW(1)) assert solveset_real(x + 2**x, x) == \ FiniteSet(-LambertW(log(2))/log(2)) # issue 4739 assert solveset_real(exp(log(5) * x) - 2**x, x) == FiniteSet(0) ans = solveset_real(3 * x + 5 + 2**(-5 * x + 3), x) assert ans == FiniteSet(-Rational(5, 3) + LambertW(-10240 * 2**(S(1) / 3) * log(2) / 3) / (5 * log(2))) eq = 2 * (3 * x + 4)**5 - 6 * 7**(3 * x + 9) result = solveset_real(eq, x) ans = FiniteSet( (log(2401) + 5 * LambertW(-log(7**(7 * 3**Rational(1, 5) / 5)))) / (3 * log(7)) / -1) assert result == ans assert solveset_real(eq.expand(), x) == result assert solveset_real(5*x - 1 + 3*exp(2 - 7*x), x) == \ FiniteSet(Rational(1, 5) + LambertW(-21*exp(Rational(3, 5))/5)/7) assert solveset_real(2*x + 5 + log(3*x - 2), x) == \ FiniteSet(Rational(2, 3) + LambertW(2*exp(-Rational(19, 3))/3)/2) assert solveset_real(3*x + log(4*x), x) == \ FiniteSet(LambertW(Rational(3, 4))/3) assert solveset_complex(x**z*y**z - 2, z) == \ FiniteSet(log(2)/(log(x) + log(y))) assert solveset_real(x**x - 2) == FiniteSet(exp(LambertW(log(2)))) a = Symbol('a') assert solveset_real(-a * x + 2 * x * log(x), x) == FiniteSet(exp(a / 2)) a = Symbol('a', real=True) assert solveset_real(a/x + exp(x/2), x) == \ FiniteSet(2*LambertW(-a/2)) assert solveset_real((a/x + exp(x/2)).diff(x), x) == \ FiniteSet(4*LambertW(sqrt(2)*sqrt(a)/4)) assert solveset_real(1 / (1 / x - y + exp(y)), x) == EmptySet() # coverage test p = Symbol('p', positive=True) w = Symbol('w') assert solveset_real((1 / p + 1)**(p + 1), p) == EmptySet() assert solveset_real(tanh(x + 3) * tanh(x - 3) - 1, x) == EmptySet() assert solveset_real(2*x**w - 4*y**w, w) == \ solveset_real((x/y)**w - 2, w) assert solveset_real((x**2 - 2*x + 1).subs(x, log(x) + 3*x), x) == \ FiniteSet(LambertW(3*S.Exp1)/3) assert solveset_real((x**2 - 2*x + 1).subs(x, (log(x) + 3*x)**2 - 1), x) == \ FiniteSet(LambertW(3*exp(-sqrt(2)))/3, LambertW(3*exp(sqrt(2)))/3) assert solveset_real((x**2 - 2*x - 2).subs(x, log(x) + 3*x), x) == \ FiniteSet(LambertW(3*exp(1 + sqrt(3)))/3, LambertW(3*exp(-sqrt(3) + 1))/3) assert solveset_real(x*log(x) + 3*x + 1, x) == \ FiniteSet(exp(-3 + LambertW(-exp(3)))) eq = (x * exp(x) - 3).subs(x, x * exp(x)) assert solveset_real(eq, x) == \ FiniteSet(LambertW(3*exp(-LambertW(3)))) assert solveset_real(3*log(a**(3*x + 5)) + a**(3*x + 5), x) == \ FiniteSet(-((log(a**5) + LambertW(S(1)/3))/(3*log(a)))) p = symbols('p', positive=True) assert solveset_real(3*log(p**(3*x + 5)) + p**(3*x + 5), x) == \ FiniteSet( log((-3**(S(1)/3) - 3**(S(5)/6)*I)*LambertW(S(1)/3)**(S(1)/3)/(2*p**(S(5)/3)))/log(p), log((-3**(S(1)/3) + 3**(S(5)/6)*I)*LambertW(S(1)/3)**(S(1)/3)/(2*p**(S(5)/3)))/log(p), log((3*LambertW(S(1)/3)/p**5)**(1/(3*log(p)))),) # checked numerically # check collection b = Symbol('b') eq = 3 * log(a**(3 * x + 5)) + b * log(a**(3 * x + 5)) + a**(3 * x + 5) assert solveset_real( eq, x) == FiniteSet(-((log(a**5) + LambertW(1 / (b + 3))) / (3 * log(a)))) # issue 4271 assert solveset_real((a / x + exp(x / 2)).diff(x, 2), x) == FiniteSet(6 * LambertW( (-1)**(S(1) / 3) * a**(S(1) / 3) / 3)) assert solveset_real(x**3 - 3**x, x) == \ FiniteSet(-3/log(3)*LambertW(-log(3)/3)) assert solveset_real(x**2 - 2**x, x) == FiniteSet(2) assert solveset_real(-x**2 + 2**x, x) == FiniteSet(2) assert solveset_real(3**cos(x) - cos(x)**3) == FiniteSet( acos(-3 * LambertW(-log(3) / 3) / log(3))) assert solveset_real(4**(x / 2) - 2**(x / 3), x) == FiniteSet(0) assert solveset_real(5**(x / 2) - 2**(x / 3), x) == FiniteSet(0) b = sqrt(6) * sqrt(log(2)) / sqrt(log(5)) assert solveset_real(5**(x / 2) - 2**(3 / x), x) == FiniteSet(-b, b)
def test_no_sol_rational_extragenous(): assert solveset_real((x / (x + 1) + 3)**(-2), x) == EmptySet() assert solveset_real((x - 1) / (1 + 1 / (x - 1)), x) == EmptySet()
def test_solveset_real_gen_is_pow(): assert solveset_real(sqrt(1) + 1, x) == EmptySet()
def test_solve_mul(): assert solveset_real((a*x + b)*(exp(x) - 3), x) == \ FiniteSet(-b/a, log(3)) assert solveset_real((2 * x + 8) * (8 + exp(x)), x) == FiniteSet(S(-4)) assert solveset_real(x / log(x), x) == EmptySet()
def build_piecewise_matrix(sympy_obj, cur_exponents, low_temp, high_temp, output_matrix, symbol_matrix, param_symbols): if sympy_obj == v.T: sympy_obj = Mul(1.0, v.T) elif sympy_obj == v.P: sympy_obj = Mul(1.0, v.P) if isinstance(sympy_obj, (Float, Integer, Rational)) or \ (isinstance(sympy_obj, (log, exp)) and isinstance(sympy_obj.args[0], (Float, Integer, Rational))): result = float(sympy_obj) if result != 0.0: output_matrix.append([low_temp, high_temp] + list(cur_exponents) + [result]) elif isinstance(sympy_obj, Piecewise): piece_args = [i for i in sympy_obj.args if i.expr != S.Zero] intervals = [to_interval(i.cond) for i in piece_args] if (len(intervals) > 1) and Intersection(intervals) != EmptySet(): raise ValueError('Overlapping intervals cannot be represented: {}'.format(intervals)) if not isinstance(Union(intervals), Interval): raise ValueError('Piecewise intervals must be continuous') if not all([arg.cond.free_symbols == {v.T} for arg in piece_args]): raise ValueError('Only temperature-dependent piecewise conditions are supported') exprs = [arg.expr for arg in piece_args] for expr, invl in zip(exprs, intervals): lowlim = invl.args[0] if invl.args[0] > low_temp else low_temp highlim = invl.args[1] if invl.args[1] < high_temp else high_temp if highlim < lowlim: continue build_piecewise_matrix(expr, cur_exponents, float(lowlim), float(highlim), output_matrix, symbol_matrix, param_symbols) elif isinstance(sympy_obj, Symbol): if sympy_obj in param_symbols: symbol_matrix.append([low_temp, high_temp] + list(cur_exponents) + [param_symbols.index(sympy_obj)]) else: warnings.warn('Setting undefined symbol {0} to zero'.format(sympy_obj)) elif isinstance(sympy_obj, Add): sympy_obj = sympy_obj.expand() for arg in sympy_obj.args: build_piecewise_matrix(arg, cur_exponents, low_temp, high_temp, output_matrix, symbol_matrix, param_symbols) elif isinstance(sympy_obj, Mul): new_exponents = np.array(cur_exponents) remaining_argument = S.One num_piecewise = sum(isinstance(x, Piecewise) for x in sympy_obj.args) if num_piecewise == 1: collected_argument = S.One piecewise_elem = None for arg in sympy_obj.args: if isinstance(arg, Piecewise): piecewise_elem = arg elif isinstance(arg, (Float, Integer, Rational)): collected_argument *= float(arg) else: collected_argument *= arg remaining_argument = Piecewise(*[(collected_argument * expr, cond) for expr, cond in piecewise_elem.args]) else: for arg in sympy_obj.args: if isinstance(arg, Pow): if arg.base == v.T: new_exponents[1] += int(arg.exp) elif arg.base == v.P: new_exponents[0] += int(arg.exp) else: raise NotImplementedError elif arg == v.T: new_exponents[1] += 1 elif arg == v.P: new_exponents[0] += 1 elif arg == sympy_log(v.T): new_exponents[3] += 1 elif arg == sympy_log(v.P): new_exponents[2] += 1 else: remaining_argument *= arg if not isinstance(remaining_argument, Mul): build_piecewise_matrix(remaining_argument, new_exponents, low_temp, high_temp, output_matrix, symbol_matrix, param_symbols) else: raise NotImplementedError(sympy_obj, type(sympy_obj)) else: raise NotImplementedError
def test_issue_10931(): assert S.Integers - S.Integers == EmptySet() assert S.Integers - S.Reals == EmptySet()
def get_amps_direction(parent, irrep, irrep_amp, isos=None, k_params=None): if isos is None: close_after = True isos = iso.IsotropySession() else: close_after = False isos.values.update({'parent': parent, 'irrep': irrep}) isos.shows.update({'direction', 'subgroup'}) delay = None if k_params is not None: isos.values['kvalue'] = ','.join([str(len(k_params))] + k_params) delay = 1 sym_inequiv = isos.getDisplayData('ISOTROPY', delay=delay) isos.shows.clearAll() inequiv_dir_labels = [s['Dir'] for s in sym_inequiv] irrep_domains = {} for lbl in inequiv_dir_labels: # TODO: put this in to the loop below so we don't request lower sym domains than needed these_domains = iso.getDomains(parent, irrep, lbl, isos=isos, k_params=k_params) too_many_domains = False if len(these_domains) > 300: break # Sorry future me too_many_domains = True these_domains[0]['Dir'] = these_domains[0]['Dir'][-1] # hacky fix irrep_domains[lbl] = these_domains isos.shows.clearAll() isos.values.clearAll() if close_after: isos.__exit__(None, None, None) for lbl, domains in irrep_domains.items(): for domain in domains: syms = set() ddir = domain['Dir'] eqn_set = [] for pos_d, pos_a in zip(ddir, irrep_amp): pos_d_sym = parse_expr(pos_d, transformations=transformations) pos_a_sym = sympify(pos_a) syms.update(pos_d_sym.free_symbols) eqn_set.append(pos_d_sym - pos_a_sym) syms = list(syms) soln = linsolve(eqn_set, syms) if soln == EmptySet(): continue eqns = [ 0 == eqn.subs([(sy, val) for sy, val in zip(syms, list(soln)[0])]) for eqn in eqn_set ] if not all(eqns): continue var_vals = list(zip([str(s) for s in syms], list(soln)[0])) logger.debug(var_vals) return lbl, ddir, var_vals try: if too_many_domains: raise TooManyDomains() except Exception: raise OtherDirectionError()
def inequation_to_interval(inequation): """ Devuelve un intervalo a partir de una inequación Parte del supuesto de que de un lado de la inecuación se encuentra "x", sin operaciones. """ args = inequation.args less = [LessThan, StrictLessThan] greater = [GreaterThan, StrictGreaterThan] if inequation.__class__ in greater + less: # [StrictGreaterThan, GreaterThan, StrictLessThan, LessThan] inequation = _adapt(inequation) args = inequation.args a = args[0] b = args[1] if inequation.__class__ in greater: if inequation.__class__ == StrictGreaterThan: # Ejemplo: x > b # Intervalo: (b, +oo) return Interval.open(b, oo) elif inequation.__class__ == GreaterThan: # Ejemplo: x >= b # Intervalo: [b, +oo) return Interval(b, oo) # Cerrado por izquierda elif inequation.__class__ in less: if inequation.__class__ == StrictLessThan: # Ejemplo: x < b # Intervalo: (-oo, b) return Interval.open(-oo, b) elif inequation.__class__ == LessThan: # Ejemplo: x <= b # Intervalo: (-oo, b] return Interval(-oo, b) # Cerrado por derecha elif inequation.__class__ == And: # El primer valor en args siempre es una inequación _args = [] for arg in args: _args.append(_adapt(arg)) args = _args d = {1: [], 2: []} for arg in args: # FIXME: Y si hay otro And o un Or ? if arg.__class__ in less: d[1].append(inequation_to_interval(arg)) elif arg.__class__ in greater: d[2].append(inequation_to_interval(arg)) if d[1]: __less = True _less = d[1][0] for _i in d[1][1:]: _less = Interval.union(_less, _i) else: __less = False _less = EmptySet() if d[2]: __greater = True _greater = d[2][0] for _i in d[2][1:]: _greater = Interval.union(_greater, _i) else: __greater = False _greater = EmptySet() if __greater and __less: return _less.intersect(_greater) elif __less and not __greater: return _less elif __greater and not __less: return _greater elif inequation.__class__ == Or: interval = inequation_to_interval(args[0]) for arg in args[1:]: interval = Union(interval, inequation_to_interval(arg)) return interval elif inequation.__class__ == BooleanTrue: # Por ejemplo: 4 > 2, todos los x pertenecientes # a los reales cumplen esta inecuación return REALS elif inequation.__class__ == BooleanFalse: # Por ejemplo: 2 > 4, ningún x perteneciente a los # reales cumple con esta inecuación return EmptySet() else: print inequation, inequation.__class__
def intersection_sets(self, other): from sympy.solvers.diophantine import diophantine if self.base_set is S.Integers: g = None if isinstance(other, ImageSet) and other.base_set is S.Integers: g = other.lamda.expr m = other.lamda.variables[0] elif other is S.Integers: m = g = Dummy('x') if g is not None: f = self.lamda.expr n = self.lamda.variables[0] # Diophantine sorts the solutions according to the alphabetic # order of the variable names, since the result should not depend # on the variable name, they are replaced by the dummy variables # below a, b = Dummy('a'), Dummy('b') f, g = f.subs(n, a), g.subs(m, b) solns_set = diophantine(f - g) if solns_set == set(): return EmptySet() solns = list(diophantine(f - g)) if len(solns) != 1: return # since 'a' < 'b', select soln for n nsol = solns[0][0] t = nsol.free_symbols.pop() return imageset(Lambda(n, f.subs(a, nsol.subs(t, n))), S.Integers) if other == S.Reals: from sympy.solvers.solveset import solveset_real from sympy.core.function import expand_complex if len(self.lamda.variables) > 1: return None f = self.lamda.expr n = self.lamda.variables[0] n_ = Dummy(n.name, real=True) f_ = f.subs(n, n_) re, im = f_.as_real_imag() im = expand_complex(im) return imageset(Lambda(n_, re), self.base_set.intersect(solveset_real(im, n_))) elif isinstance(other, Interval): from sympy.solvers.solveset import (invert_real, invert_complex, solveset) f = self.lamda.expr n = self.lamda.variables[0] base_set = self.base_set new_inf, new_sup = None, None new_lopen, new_ropen = other.left_open, other.right_open if f.is_real: inverter = invert_real else: inverter = invert_complex g1, h1 = inverter(f, other.inf, n) g2, h2 = inverter(f, other.sup, n) if all(isinstance(i, FiniteSet) for i in (h1, h2)): if g1 == n: if len(h1) == 1: new_inf = h1.args[0] if g2 == n: if len(h2) == 1: new_sup = h2.args[0] # TODO: Design a technique to handle multiple-inverse # functions # Any of the new boundary values cannot be determined if any(i is None for i in (new_sup, new_inf)): return range_set = S.EmptySet if all(i.is_real for i in (new_sup, new_inf)): # this assumes continuity of underlying function # however fixes the case when it is decreasing if new_inf > new_sup: new_inf, new_sup = new_sup, new_inf new_interval = Interval(new_inf, new_sup, new_lopen, new_ropen) range_set = base_set.intersect(new_interval) else: if other.is_subset(S.Reals): solutions = solveset(f, n, S.Reals) if not isinstance(range_set, (ImageSet, ConditionSet)): range_set = solutions.intersect(other) else: return if range_set is S.EmptySet: return S.EmptySet elif isinstance(range_set, Range) and range_set.size is not S.Infinity: range_set = FiniteSet(*list(range_set)) if range_set is not None: return imageset(Lambda(n, f), range_set) return else: return
def test_diagram(): A = Object("A") B = Object("B") C = Object("C") f = NamedMorphism(A, B, "f") g = NamedMorphism(B, C, "g") id_A = IdentityMorphism(A) id_B = IdentityMorphism(B) empty = EmptySet() # Test the addition of identities. d1 = Diagram([f]) assert d1.objects == FiniteSet(A, B) assert d1.hom(A, B) == (FiniteSet(f), empty) assert d1.hom(A, A) == (FiniteSet(id_A), empty) assert d1.hom(B, B) == (FiniteSet(id_B), empty) assert d1 == Diagram([id_A, f]) assert d1 == Diagram([f, f]) # Test the addition of composites. d2 = Diagram([f, g]) homAC = d2.hom(A, C)[0] assert d2.objects == FiniteSet(A, B, C) assert g * f in d2.premises.keys() assert homAC == FiniteSet(g * f) # Test equality, inequality and hash. d11 = Diagram([f]) assert d1 == d11 assert d1 != d2 assert hash(d1) == hash(d11) d11 = Diagram({f: "unique"}) assert d1 != d11 # Make sure that (re-)adding composites (with new properties) # works as expected. d = Diagram([f, g], {g * f: "unique"}) assert d.conclusions == Dict({g * f: FiniteSet("unique")}) # Check the hom-sets when there are premises and conclusions. assert d.hom(A, C) == (FiniteSet(g * f), FiniteSet(g * f)) d = Diagram([f, g], [g * f]) assert d.hom(A, C) == (FiniteSet(g * f), FiniteSet(g * f)) # Check how the properties of composite morphisms are computed. d = Diagram({f: ["unique", "isomorphism"], g: "unique"}) assert d.premises[g * f] == FiniteSet("unique") # Check that conclusion morphisms with new objects are not allowed. d = Diagram([f], [g]) assert d.conclusions == Dict({}) # Test an empty diagram. d = Diagram() assert d.premises == Dict({}) assert d.conclusions == Dict({}) assert d.objects == empty # Check a SymPy Dict object. d = Diagram(Dict({f: FiniteSet("unique", "isomorphism"), g: "unique"})) assert d.premises[g * f] == FiniteSet("unique") # Check the addition of components of composite morphisms. d = Diagram([g * f]) assert f in d.premises assert g in d.premises # Check subdiagrams. d = Diagram([f, g], {g * f: "unique"}) d1 = Diagram([f]) assert d.is_subdiagram(d1) assert not d1.is_subdiagram(d) d = Diagram([NamedMorphism(B, A, "f'")]) assert not d.is_subdiagram(d1) assert not d1.is_subdiagram(d) d1 = Diagram([f, g], {g * f: ["unique", "something"]}) assert not d.is_subdiagram(d1) assert not d1.is_subdiagram(d) d = Diagram({f: "blooh"}) d1 = Diagram({f: "bleeh"}) assert not d.is_subdiagram(d1) assert not d1.is_subdiagram(d) d = Diagram([f, g], {f: "unique", g * f: "veryunique"}) d1 = d.subdiagram_from_objects(FiniteSet(A, B)) assert d1 == Diagram([f], {f: "unique"}) raises(ValueError, lambda: d.subdiagram_from_objects(FiniteSet(A, Object("D")))) raises(ValueError, lambda: Diagram({IdentityMorphism(A): "unique"}))
def __init__(self, env, config): Thread.__init__(self) self.env = env self.ev_wait = ThEvent() self.ev_th_wait = ThEvent() self.end_flag = False self.cur_time = 0 self.devices = None self.name = "CommonObserver" obs_conf = config["observers"] self.time_ranges_to_show = dict() # словарь содержит операции, ассоциированные с обозревателем # по ключам: # flow - диаграммы потоков # packets - мониторинг пакетов # traffic_utilization - мониторинг утилизации ресурсов и буфферов # total_per_flow_performance - интегральная оценка по потокам # по значениям - кортеж: # (проверка на соответствие условиям события, метод получения результата) observer_dict = { "flow": 0, "power": 0, "packets": (self.packets_matcher, self.packets_res_make), "traffic_utilization": ((self.traffic_utilization_matcher, self.buffer_utilization_matcher), self.traffic_utilization_res_make), "buffers": 0, "mass": 0, "total_per_flow_performance": () } # первые помещуются в match_conditions. # Наблюдатель прогоняет матчеры для сохранения результата self.match_conditions = list() # вторые используются для подготовки результата и его вывода # Наблюдатель прогоняет мэйкеры для обработки результата self.result_makers = list() # показывает, какие из наблюдений актуальны в симуляции self.observers_active = dict() for obs_name in obs_conf: cur_obs_conf = obs_conf[obs_name] if cur_obs_conf["report"]: self.observers_active[obs_name] = cur_obs_conf["output"] if cur_obs_conf["report"] and "time_ranges" in cur_obs_conf: time_ranges = cur_obs_conf["time_ranges"] self.time_ranges_to_show[obs_name] = EmptySet().union( Interval(i[0], i[1]) for i in time_ranges) matcher = observer_dict[obs_name][0] if isinstance(matcher, collections.Iterable): self.match_conditions.extend(matcher) else: self.match_conditions.append(matcher) res_maker = observer_dict[obs_name][1] self.result_makers.append(res_maker) if len(self.time_ranges_to_show) > 0: self.time_horizon = max( list( max(self.time_ranges_to_show[i].boundary) for i in self.time_ranges_to_show)) self.time_horizon = max(config["horizon"], self.time_horizon) else: self.time_horizon = config["horizon"] # это буфер для новых данных, # потом обрабатываются в отдельном потоке и удаляются self.new_data = list() # _raw - сырые данные, полученные от матчеров # _result - обработанный и причёсанный результат # traffic_utilization self.traf_mon_raw = dict() self.traf_mon_result = dict() self.buffer_result = dict() # packets self.packets_raw = dict() self.packets_result = dict() # total_per_flow_performance self.global_flow_result = dict() self.flow_class = dict() self.flow_distance = dict()
def intersection_sets(self, other): from sympy.solvers.diophantine import diophantine # Only handle the straight-forward univariate case if (len(self.lamda.variables) > 1 or self.lamda.signature != self.lamda.variables): return None base_set = self.base_sets[0] if base_set is S.Integers: g = None if isinstance(other, ImageSet) and other.base_sets == (S.Integers, ): g = other.lamda.expr m = other.lamda.variables[0] elif other is S.Integers: m = g = Dummy('x') if g is not None: f = self.lamda.expr n = self.lamda.variables[0] # Diophantine sorts the solutions according to the alphabetic # order of the variable names, since the result should not depend # on the variable name, they are replaced by the dummy variables # below a, b = Dummy('a'), Dummy('b') fa, ga = f.subs(n, a), g.subs(m, b) solns = list(diophantine(fa - ga)) if not solns: return EmptySet() if len(solns) != 1: return nsol = solns[0][0] # since 'a' < 'b', nsol is first t = nsol.free_symbols.pop() # diophantine supplied symbol nsol = nsol.subs(t, n) if nsol != n: # if nsol == n and we know were are working with # a base_set of Integers then this was an unevaluated # ImageSet representation of Integers, otherwise # it is a new ImageSet intersection with a subset # of integers nsol = f.subs(n, nsol) return imageset(Lambda(n, nsol), S.Integers) if other == S.Reals: from sympy.solvers.solveset import solveset_real from sympy.core.function import expand_complex f = self.lamda.expr n = self.lamda.variables[0] n_ = Dummy(n.name, real=True) f_ = f.subs(n, n_) re, im = f_.as_real_imag() im = expand_complex(im) re = re.subs(n_, n) im = im.subs(n_, n) ifree = im.free_symbols lam = Lambda(n, re) if not im: # allow re-evaluation # of self in this case to make # the result canonical pass elif im.is_zero is False: return S.EmptySet elif ifree != {n}: return None else: # univarite imaginary part in same variable base_set = base_set.intersect(solveset_real(im, n)) return imageset(lam, base_set) elif isinstance(other, Interval): from sympy.solvers.solveset import (invert_real, invert_complex, solveset) f = self.lamda.expr n = self.lamda.variables[0] new_inf, new_sup = None, None new_lopen, new_ropen = other.left_open, other.right_open if f.is_real: inverter = invert_real else: inverter = invert_complex g1, h1 = inverter(f, other.inf, n) g2, h2 = inverter(f, other.sup, n) if all(isinstance(i, FiniteSet) for i in (h1, h2)): if g1 == n: if len(h1) == 1: new_inf = h1.args[0] if g2 == n: if len(h2) == 1: new_sup = h2.args[0] # TODO: Design a technique to handle multiple-inverse # functions # Any of the new boundary values cannot be determined if any(i is None for i in (new_sup, new_inf)): return range_set = S.EmptySet if all(i.is_real for i in (new_sup, new_inf)): # this assumes continuity of underlying function # however fixes the case when it is decreasing if new_inf > new_sup: new_inf, new_sup = new_sup, new_inf new_interval = Interval(new_inf, new_sup, new_lopen, new_ropen) range_set = base_set.intersect(new_interval) else: if other.is_subset(S.Reals): solutions = solveset(f, n, S.Reals) if not isinstance(range_set, (ImageSet, ConditionSet)): range_set = solutions.intersect(other) else: return if range_set is S.EmptySet: return S.EmptySet elif isinstance(range_set, Range) and range_set.size is not S.Infinity: range_set = FiniteSet(*list(range_set)) if range_set is not None: return imageset(Lambda(n, f), range_set) return else: return
def intersection_sets(self, other): from sympy.solvers.diophantine import diophantine # Only handle the straight-forward univariate case if (len(self.lamda.variables) > 1 or self.lamda.signature != self.lamda.variables): return None base_set = self.base_sets[0] # Intersection between ImageSets with Integers as base set # For {f(n) : n in Integers} & {g(m) : m in Integers} we solve the # diophantine equations f(n)=g(m). # If the solutions for n are {h(t) : t in Integers} then we return # {f(h(t)) : t in integers}. if base_set is S.Integers: gm = None if isinstance(other, ImageSet) and other.base_sets == (S.Integers,): gm = other.lamda.expr m = other.lamda.variables[0] elif other is S.Integers: m = gm = Dummy('x') if gm is not None: fn = self.lamda.expr n = self.lamda.variables[0] solns = list(diophantine(fn - gm, syms=(n, m))) if len(solns) == 0: return EmptySet() elif len(solns) != 1: return else: soln, solm = solns[0] (t,) = soln.free_symbols expr = fn.subs(n, soln.subs(t, n)) return imageset(Lambda(n, expr), S.Integers) if other == S.Reals: from sympy.solvers.solveset import solveset_real from sympy.core.function import expand_complex f = self.lamda.expr n = self.lamda.variables[0] n_ = Dummy(n.name, real=True) f_ = f.subs(n, n_) re, im = f_.as_real_imag() im = expand_complex(im) re = re.subs(n_, n) im = im.subs(n_, n) ifree = im.free_symbols lam = Lambda(n, re) if not im: # allow re-evaluation # of self in this case to make # the result canonical pass elif im.is_zero is False: return S.EmptySet elif ifree != {n}: return None else: # univarite imaginary part in same variable base_set = base_set.intersect(solveset_real(im, n)) return imageset(lam, base_set) elif isinstance(other, Interval): from sympy.solvers.solveset import (invert_real, invert_complex, solveset) f = self.lamda.expr n = self.lamda.variables[0] new_inf, new_sup = None, None new_lopen, new_ropen = other.left_open, other.right_open if f.is_real: inverter = invert_real else: inverter = invert_complex g1, h1 = inverter(f, other.inf, n) g2, h2 = inverter(f, other.sup, n) if all(isinstance(i, FiniteSet) for i in (h1, h2)): if g1 == n: if len(h1) == 1: new_inf = h1.args[0] if g2 == n: if len(h2) == 1: new_sup = h2.args[0] # TODO: Design a technique to handle multiple-inverse # functions # Any of the new boundary values cannot be determined if any(i is None for i in (new_sup, new_inf)): return range_set = S.EmptySet if all(i.is_real for i in (new_sup, new_inf)): # this assumes continuity of underlying function # however fixes the case when it is decreasing if new_inf > new_sup: new_inf, new_sup = new_sup, new_inf new_interval = Interval(new_inf, new_sup, new_lopen, new_ropen) range_set = base_set.intersect(new_interval) else: if other.is_subset(S.Reals): solutions = solveset(f, n, S.Reals) if not isinstance(range_set, (ImageSet, ConditionSet)): range_set = solutions.intersect(other) else: return if range_set is S.EmptySet: return S.EmptySet elif isinstance(range_set, Range) and range_set.size is not S.Infinity: range_set = FiniteSet(*list(range_set)) if range_set is not None: return imageset(Lambda(n, f), range_set) return else: return