Beispiel #1
0
def test_sets():
    x = Integer(2)
    y = Integer(3)
    x1 = sympy.Integer(2)
    y1 = sympy.Integer(3)

    assert Interval(x, y) == Interval(x1, y1)
    assert Interval(x1, y) == Interval(x1, y1)
    assert Interval(x, y)._sympy_() == sympy.Interval(x1, y1)
    assert sympify(sympy.Interval(x1, y1)) == Interval(x, y)

    assert sympify(sympy.EmptySet()) == EmptySet()
    assert sympy.EmptySet() == EmptySet()._sympy_()

    assert FiniteSet(x, y) == FiniteSet(x1, y1)
    assert FiniteSet(x1, y) == FiniteSet(x1, y1)
    assert FiniteSet(x, y)._sympy_() == sympy.FiniteSet(x1, y1)
    assert sympify(sympy.FiniteSet(x1, y1)) == FiniteSet(x, y)

    x = Interval(1, 2)
    y = Interval(2, 3)
    x1 = sympy.Interval(1, 2)
    y1 = sympy.Interval(2, 3)

    assert Union(x, y) == Union(x1, y1)
    assert Union(x1, y) == Union(x1, y1)
    assert Union(x, y)._sympy_() == sympy.Union(x1, y1)
    assert sympify(sympy.Union(x1, y1)) == Union(x, y)

    assert Complement(x, y) == Complement(x1, y1)
    assert Complement(x1, y) == Complement(x1, y1)
    assert Complement(x, y)._sympy_() == sympy.Complement(x1, y1)
    assert sympify(sympy.Complement(x1, y1)) == Complement(x, y)
Beispiel #2
0
def sympy_solver(expr):
    # Sympy is buggy and slow.  Use Transforms.
    symbols = get_symbols(expr)
    if len(symbols) != 1:
        raise ValueError('Expression "%s" needs exactly one symbol.' %
                         (expr, ))

    if isinstance(expr, Relational):
        result = sympy.solveset(expr, domain=sympy.Reals)
    elif isinstance(expr, sympy.Or):
        subexprs = expr.args
        intervals = [sympy_solver(e) for e in subexprs]
        result = sympy.Union(*intervals)
    elif isinstance(expr, sympy.And):
        subexprs = expr.args
        intervals = [sympy_solver(e) for e in subexprs]
        result = sympy.Intersection(*intervals)
    elif isinstance(expr, sympy.Not):
        (notexpr, ) = expr.args
        interval = sympy_solver(notexpr)
        result = interval.complement(sympy.Reals)
    else:
        raise ValueError('Expression "%s" has unknown type.' % (expr, ))

    if isinstance(result, sympy.ConditionSet):
        raise ValueError('Expression "%s" is not invertible.' % (expr, ))

    return result
Beispiel #3
0
def transform_set(x, expr, sympy_set):
    """ Transform a sympy_set by an expression

    >>> x = sympy.Symbol('x')
    >>> domain = sympy.Interval(-sympy.pi / 4, -sympy.pi / 6, False, True) | sympy.Interval(sympy.pi / 6, sympy.pi / 4, True, False)
    >>> transform_set(x, -2 * x, domain)
    [-pi/2, -pi/3) U (pi/3, pi/2]
    """

    if isinstance(sympy_set, sympy.Union):
        return sympy.Union(
            transform_set(x, expr, arg) for arg in sympy_set.args)
    if isinstance(sympy_set, sympy.Intersection):
        return sympy.Intersection(
            transform_set(x, expr, arg) for arg in sympy_set.args)

    f = sympy.Lambda(x, expr)
    if isinstance(sympy_set, sympy.Interval):
        left, right = f(sympy_set.left), f(sympy_set.right)

        if left < right:
            new_left_open = sympy_set.left_open
            new_right_open = sympy_set.right_open
        else:
            new_left_open = sympy_set.right_open
            new_right_open = sympy_set.left_open

        return sympy.Interval(sympy.Min(left, right), sympy.Max(left, right),
                              new_left_open, new_right_open)

    if isinstance(sympy_set, sympy.FiniteSet):
        return sympy.FiniteSet(list(map(f, sympy_set)))
Beispiel #4
0
    def axvspan(self, axes=None, phase_offsets=[0], **kwargs):
        """ Overlay range on matplotlib axes. 
            N.B. set phase_offsets=[0,1] to overlay on
            phaseogram that varies from 0 to 2 the phase
            range both on the 0-1 and the 1-2 part of the plot. """
        import pylab as P
        if axes is None: axes=P.gca()
        label=kwargs.pop('label',None)

        if phase_offsets != [0] and phase_offsets !=0:
            # kind of ugly, but create a larger PhaseRange object
            # temporarily with the offsets. This allows for
            # merging needed offsets.
            # (a) create a giant list of all phases
            all_phases = reduce(add,[[[a+o,b+o] for a,b in self.tolist(dense=False)] for o in phase_offsets])
            # (b) turn the list of ranges into a sympy object
            interval = sympy.Union([sympy.Interval(a,b) for a,b in all_phases])
            # (c) cretae a temporary phase range object which spans all intervals
            temp = PhaseRange()
            temp.range = interval
        else:
            temp=self

        ret = []
        for a,b in temp.tolist(dense=False):
            ret.append(axes.axvspan(a, b, label=label, **kwargs))
            label=None
        return ret
Beispiel #5
0
def test_sets():
    x = Integer(2)
    y = Integer(3)
    x1 = sympy.Integer(2)
    y1 = sympy.Integer(3)

    assert Interval(x, y) == Interval(x1, y1)
    assert Interval(x1, y) == Interval(x1, y1)
    assert Interval(x, y)._sympy_() == sympy.Interval(x1, y1)
    assert sympify(sympy.Interval(x1, y1)) == Interval(x, y)

    assert sympify(sympy.S.EmptySet) == EmptySet()
    assert sympy.S.EmptySet == EmptySet()._sympy_()

    assert sympify(sympy.S.UniversalSet) == UniversalSet()
    assert sympy.S.UniversalSet == UniversalSet()._sympy_()

    assert sympify(sympy.S.Reals) == Reals()
    assert sympy.S.Reals == Reals()._sympy_()

    assert sympify(sympy.S.Rationals) == Rationals()
    assert sympy.S.Rationals == Rationals()._sympy_()

    assert sympify(sympy.S.Integers) == Integers()
    assert sympy.S.Integers == Integers()._sympy_()

    assert FiniteSet(x, y) == FiniteSet(x1, y1)
    assert FiniteSet(x1, y) == FiniteSet(x1, y1)
    assert FiniteSet(x, y)._sympy_() == sympy.FiniteSet(x1, y1)
    assert sympify(sympy.FiniteSet(x1, y1)) == FiniteSet(x, y)

    x = Interval(1, 2)
    y = Interval(2, 3)
    x1 = sympy.Interval(1, 2)
    y1 = sympy.Interval(2, 3)

    assert Union(x, y) == Union(x1, y1)
    assert Union(x1, y) == Union(x1, y1)
    assert Union(x, y)._sympy_() == sympy.Union(x1, y1)
    assert sympify(sympy.Union(x1, y1)) == Union(x, y)

    assert Complement(x, y) == Complement(x1, y1)
    assert Complement(x1, y) == Complement(x1, y1)
    assert Complement(x, y)._sympy_() == sympy.Complement(x1, y1)
    assert sympify(sympy.Complement(x1, y1)) == Complement(x, y)
Beispiel #6
0
 def test_comparison_not_equal(self):
     comparison = Comparison(
         content="the distance between $place1 and $place2 was",
         sign="!=",
         expression=Q_("20 miles"),
     )
     assert comparison.interval == sympy.Union(
         Interval(0, 20, right_open=True), Interval(20, oo, left_open=True)
     )
Beispiel #7
0
def scale_union_of_intervals(ranges: sympy.Union,
                             scalar: Union[int, float]) -> sympy.Union:
    """
    Scale up union of several intervals by multiplying by a scalar.

    Used for converting the units of a UnitRange.
    """
    scaled_intervals = [
        scale_interval(interval=interval, scalar=scalar)
        for interval in ranges.args
    ]
    return sympy.Union(*scaled_intervals)
Beispiel #8
0
    def __init__(self, *args):
        if len(args) == 1 and isinstance(args[0], PhaseRange):

            self.range = copy.deepcopy(args[0].range)
            return

        if len(args) == 1 and np.alltrue(len(i) == 2 for i in args):
            args = args[0]

        if len(args) == 2 and \
           isinstance(args[0],numbers.Real) and \
           isinstance(args[1],numbers.Real):
            args = [list(args)]

        ranges = []

        for range in args:

            if range[0] not in PhaseRange.allowed_phase_input or \
               range[1] not in PhaseRange.allowed_phase_input:
                raise Exception(
                    "Error, phase range %s is outside allowed range." %
                    str(range))

            if np.allclose(range[0]-range[1],1) or \
               np.allclose(range[1]-range[0],1):
                range = [0, 1]
            else:
                for i in [0, 1]:
                    if range[i] != 1: range[i] %= 1

            if range[0] > range[1]:
                # worry about wraping phase ranges, for example [0.6, 0.2] -> [0,0.2]U[0.6,1]
                if range[1] == 0:
                    ranges.append(sympy.Interval(range[0], 1))
                else:
                    ranges += [
                        sympy.Interval(0, range[1]),
                        sympy.Interval(range[0], 1)
                    ]
            else:
                ranges.append(sympy.Interval(*range))

        self.range = sympy.Union(*ranges)
Beispiel #9
0
    def rules_conditions_union(self, rules):
        """
        Returns the union (OR) of the conditions of rules.

        We have to go through this alembic'ed function in order to merge
        ranges (for example port ranges) as an high level rule (for example,
        allow port 1 to 31766) are broken down into a multitude of hard to read
        flow rules. Return them in DNF notation, as it looks nicer to read.
        """
        ored, range_accumulator = self.rule_conditions_or(rules)

        for key_name, ranges in range_accumulator.items():
            closed_interval = close_intervals(sm.Union(*ranges))

            ored = ored.replace(
                sm.Symbol(key_name),
                closed_interval.as_relational(
                    sm.Symbol(key_name.partition("__range_")[2])))
        return sm.to_dnf(ored)
Beispiel #10
0
 def interval(self) -> Union[FiniteSet, Interval, sympy.Union]:
     """Get the range that the Comparison may refer to."""
     if self.sign == "==":
         return FiniteSet(self.magnitude)
     elif ">" in self.sign:
         return Interval(self.magnitude,
                         oo,
                         left_open=bool("=" not in self.sign))
     elif "<" in self.sign:
         return Interval(
             self.lower_bound,
             self.magnitude,
             right_open=bool("=" not in self.sign),
         )
     # self.sign == "!="
     return sympy.Union(
         Interval(self.lower_bound, self.magnitude, right_open=True),
         Interval(self.magnitude, oo, left_open=True),
     )
def compare_sequences(
        target, interpreted):  # Calculate average difference in semitones
    x, y = sym.symbols('x y')
    f, g = sym.symbols('target interpreted', cls=sym.Function)

    # Target/Interpreted are lists of Note objects
    trg = [(note.midi, note.start, note.end) for note in target]
    terp = [(note.midi, note.start, note.end) for note in interpreted]

    trg_funcs = [(note[0], sym.And(note[1] <= x, x <= note[2]))
                 for note in trg]
    terp_funcs = [(note[0], sym.And(note[1] <= x, x <= note[2]))
                  for note in terp]

    f = sym.Piecewise(*trg_funcs)
    g = sym.Piecewise(*terp_funcs)

    def check_cont(f1, f2, y):
        # XOR for two given functions for a given x
        if bool(f1.subs(x, y) == sym.nan) != bool(f2.subs(x, y) == sym.nan):
            return y
        elif f1.subs(x, y) == sym.nan and f2.subs(x, y) == sym.nan:
            return y
        else:
            return None

    def find_disconts(f1, f2, end):
        values = []
        for x_val in np.arange(0, end + .01, .01):
            if check_cont(f1, f2, x_val):
                values.append(round(x_val, 3))
        return values

    def convert_to_intervals(points):
        end = 0
        ret = []
        while len(points):
            if round(points[end] - points[0], 2) == end/100 and \
               end != len(points) - 1:
                end += 1
            elif end == len(points) - 1:
                ret.append(points[0:end + 1])
                del points[0:end + 1]
            else:
                ret.append(points[0:end])
                del points[0:end]
                end = 0

        ret = [(round((ls[0] - .01), 2), round((ls[-1] + .01), 2))
               for ls in ret]

        return ret

    vals = find_disconts(f, g,
                         trg[-1][2])  # List of all points of discontinuity
    int_vals = convert_to_intervals(
        vals)  # List form intervals of discontinuity

    # Interval form discontinuities
    val_form = sym.Union(*[sym.Interval(spc[0], spc[1]) for spc in int_vals])
    full_domain = sym.Interval(0, trg[-1][2])
    final_domain = full_domain - val_form

    if int_vals:
        discont_domain = sum([spc[1] - spc[0] for spc in int_vals])
        total_length = trg[-1][2]
        cont_domain = total_length - discont_domain

        total = 0
        for sub in final_domain.args:
            total += sym.integrate(np.abs(f - g), (x, sub.left, sub.right))

        mu = total / cont_domain
    else:
        mu = sym.integrate(np.abs(f - g), (x, 0, trg[-1][1])) / trg[-1][1]

    print(f"μ = {mu}")
    return mu