Пример #1
0
def simplify(expr, *exprs, **kwargs):
    """Simplify the given expression[s]."""
    if exprs:
        return _coconut_tail_call(
            (tuple), (map)(lambda x: x.simplify(**kwargs), (expr, ) + exprs))
    else:
        return _coconut_tail_call(expr.simplify, **kwargs)
Пример #2
0
 def find_unification(self, other):
     if isinstance(other, Quantifier):
         return _coconut_tail_call(other.find_unification, self)
     elif isinstance(other, self.__class__):
         return _coconut_tail_call(self.elem.find_unification, other.elem)
     else:
         return None
Пример #3
0
 def resolve_against(self, other, **kwargs):
     if isinstance(other, Quantifier):
         resolution = self.elem.resolve_against(Not(other.elem).simplify(**kwargs), **kwargs)
         if resolution is None:
             return None
         elif isinstance(other, ForAll):  # don't pull an Exists out of a ForAll
             return _coconut_tail_call((other.change_elem), (self.change_elem)(resolution))
         else:
             return _coconut_tail_call((self.change_elem), (other.change_elem)(resolution))
     else:
         return _coconut_tail_call(super(Quantifier, self).resolve_against, other, **kwargs)
Пример #4
0
 def substitute(self, subs, **kwargs):
     if can_sub(kwargs):
         for var, sub in subs.items():
             if can_sub(kwargs) and isinstance(var, Term) and self.name == var.name:
                 do_sub(kwargs)
                 if isvar(self) or self == var:
                     return sub
                 else:
                     return _coconut_tail_call(self.rename, sub.name)
     if can_sub(kwargs):
         return _coconut_tail_call(self.substitute_elements, subs, **kwargs)
     return self
Пример #5
0
 def __mul__(self, other):
     """Scalar multiplication and dot product."""
     _coconut_match_to = other
     _coconut_match_check = False
     if _coconut.isinstance(_coconut_match_to, vector):
         other_pts = _coconut_match_to[0:]
         _coconut_match_check = True
     if _coconut_match_check:
         assert len(other_pts) == len(self.pts)
         return _coconut_tail_call((sum), map(_coconut.operator.mul, self.pts, other_pts))  # dot product
     else:
         return _coconut_tail_call((vector), *map(_coconut.functools.partial(_coconut.operator.mul, other), self.pts))  # scalar multiplication
Пример #6
0
 def __mul__(self, other):
     """Scalar multiplication and dot product."""
     _coconut_match_check = False
     _coconut_match_to = other
     if (_coconut.isinstance(_coconut_match_to, vector)) and (_coconut.len(_coconut_match_to) == 1):
         other_pts = _coconut_match_to[0]
         _coconut_match_check = True
     if _coconut_match_check:
         assert len(other_pts) == len(self.pts)
         raise _coconut_tail_call((sum), map(_coconut.operator.mul, self.pts, other_pts))  # dot product
     else:
         raise _coconut_tail_call((vector), *map(_coconut.functools.partial(_coconut.operator.mul, other), self.pts))  # scalar multiplication
Пример #7
0
def fit_with_max_bins(column, weight_column, max_bins, df):
    ix_map = index_map(df[column])
    if max_bins >= len(ix_map):
        return _coconut_tail_call(fit, column, df)
    else:
        f_weights = {
            f: np.sum(df[weight_column].values[ix])
            for f, ix in ix_map.items()
        }
        w_cutoff = ((list)((sorted)(f_weights.values())))[-(max_bins + 1)]
        selected_factors = [f for f, w in f_weights.items() if w > w_cutoff]
        return _coconut_tail_call(
            (Transformer),
            _coconut.functools.partial(transform, column, selected_factors))
def primes():
    def sieve(numbers):
        head = next(numbers)
        yield head
        yield from sieve((n for n in numbers if n % head))

    return _coconut_tail_call(sieve, count(2))
Пример #9
0
 def resolve_against(self, other, **kwargs):
     if isinstance(other, Eq):
         return _coconut_tail_call(other.resolve_against, self)
     elif isinstance(other, Or):
         not_other_ors = (map)(_coconut.operator.methodcaller("simplify", **kwargs), (map)(Not, other.ors))
         for i, x in enumerate(self.ors):
             if isinstance(x, Eq):
                 resolved_other = (x.paramodulant)(other)
                 return (Or)(*self.ors[:i] + self.ors[i + 1:] + resolved_other.ors)
             for j, y in enumerate(not_other_ors):
                 if isinstance(other.ors[j], Eq):
                     y = other.ors[j]
                     resolved_self = (y.paramodulant)(self)
                     return (Or)(*other.ors[:j] + other.ors[j + 1:] + resolved_self.ors)
                 subs = x.find_unification(y)
                 if subs is not None:
                     return (Or)(*(map)(_coconut.operator.methodcaller("substitute", subs, **kwargs), self.ors[:i] + self.ors[i + 1:] + other.ors[:j] + other.ors[j + 1:]))
     else:
         not_other = Not(other).simplify(**kwargs)
         for i, x in enumerate(self.ors):
             if isinstance(x, Eq):
                 return (x.paramodulant)((Or)(*self.ors[:i] + self.ors[i + 1:]))
             subs = x.find_unification(not_other)
             if subs is not None:
                 return (Or)(*(map)(_coconut.operator.methodcaller("substitute", subs, **kwargs), self.ors[:i] + self.ors[i + 1:]))
     return None
Пример #10
0
 def resolve_against(self, other, **kwargs):
     if isinstance(other, (Or, Eq)):
         return _coconut_tail_call(other.resolve_against, self, **kwargs)
     elif self.neg.find_unification(other) is not None:
         return bot
     else:
         return None
Пример #11
0
def forall_handle(*_coconut_match_to_args, **_coconut_match_to_kwargs):
    _coconut_match_check = False
    _coconut_FunctionMatchError = _coconut_get_function_match_error()
    if (_coconut.len(_coconut_match_to_args) <= 2) and (_coconut.sum(
        (_coconut.len(_coconut_match_to_args) > 0, "const"
         in _coconut_match_to_kwargs)) == 1) and (_coconut.sum(
             (_coconut.len(_coconut_match_to_args) > 1, "expr"
              in _coconut_match_to_kwargs)) == 1):
        _coconut_match_temp_0 = _coconut_match_to_args[0] if _coconut.len(
            _coconut_match_to_args) > 0 else _coconut_match_to_kwargs.pop(
                "const")
        _coconut_match_temp_1 = _coconut_match_to_args[1] if _coconut.len(
            _coconut_match_to_args) > 1 else _coconut_match_to_kwargs.pop(
                "expr")
        if not _coconut_match_to_kwargs:
            const = _coconut_match_temp_0
            expr = _coconut_match_temp_1
            _coconut_match_check = True
    if not _coconut_match_check:
        _coconut_match_val_repr = _coconut.repr(_coconut_match_to_args)
        _coconut_match_err = _coconut_FunctionMatchError(
            "pattern-matching failed for "
            "'match def forall_handle(const, expr) = ForAll(const, expr)'"
            " in " +
            (_coconut_match_val_repr if _coconut.len(_coconut_match_val_repr)
             <= 500 else _coconut_match_val_repr[:500] + "..."))
        _coconut_match_err.pattern = 'match def forall_handle(const, expr) = ForAll(const, expr)'
        _coconut_match_err.value = _coconut_match_to_args
        raise _coconut_match_err

    return _coconut_tail_call(ForAll, const, expr)
def primes():
    @_coconut_tco
    def sieve(*_coconut_match_to_args, **_coconut_match_to_kwargs):
        _coconut_match_check = False
        if (_coconut.len(_coconut_match_to_args)
                == 1) and (_coconut.isinstance(_coconut_match_to_args[0],
                                               _coconut.abc.Iterable)):
            tail = _coconut.iter(_coconut_match_to_args[0])
            _coconut_match_temp_0 = _coconut.tuple(
                _coconut_igetitem(tail, _coconut.slice(None, 1)))
            if (_coconut.len(_coconut_match_temp_0)
                    == 1) and (not _coconut_match_to_kwargs):
                head = _coconut_match_temp_0[0]
                _coconut_match_check = True
        if not _coconut_match_check:
            _coconut_match_err = _coconut_MatchError(
                "pattern-matching failed for "
                "'def sieve([head] :: tail):'"
                " in " + _coconut.repr(_coconut.repr(_coconut_match_to_args)))
            _coconut_match_err.pattern = 'def sieve([head] :: tail):'
            _coconut_match_err.value = _coconut_match_to_args
            raise _coconut_match_err

        return _coconut_tail_call(
            _coconut.itertools.chain.from_iterable,
            (f() for f in (lambda: [head],
                           lambda: sieve((n for n in tail if n % head)))))

    return _coconut_tail_call(sieve, count(2))
Пример #13
0
def factorial(n, acc=1):
    """Compute n! where n is an integer >= 0."""
    def _coconut_mock_func(n, acc=1): return n, acc
    while True:
        _coconut_match_to = n
        _coconut_case_check_2 = False
        if _coconut_match_to == 0:
            _coconut_case_check_2 = True
        if _coconut_case_check_2:
            return acc
        if not _coconut_case_check_2:
            if _coconut.isinstance(_coconut_match_to, int):
                _coconut_case_check_2 = True
            if _coconut_case_check_2 and not (n > 0):
                _coconut_case_check_2 = False
            if _coconut_case_check_2:
                try:
                    _coconut_is_recursive = factorial is _coconut_recursive_func_4
                except _coconut.NameError:
                    _coconut_is_recursive = False
                if _coconut_is_recursive:
                    n, acc = _coconut_mock_func(n - 1, acc * n)
                    continue
                else:
                    return _coconut_tail_call(factorial, n - 1, acc * n)

        if not _coconut_case_check_2:
            raise TypeError("the argument to factorial must be an integer >= 0")

# Test cases:
        return None
Пример #14
0
 def dedupe(self):
     """Removes duplicate elements from a boolean operator."""
     elems = []
     for x in self.elems:
         if x not in elems:
             elems.append(x)
     return _coconut_tail_call(self.__class__, *elems)
Пример #15
0
def call(action, item):
    """Call an action on the tokens in item."""
    @_coconut_tco
    def parse_action(o, l, tokens):
        return _coconut_tail_call(action, *tokens)

    return _coconut_tail_call(attach, parse_action, item)
def primes():
    def sieve(numbers):
        head = next(numbers)
        yield head
        yield from sieve(filter(lambda x: x % head, numbers))

    return _coconut_tail_call(sieve, count(2))
    def sieve(*_coconut_match_to_args, **_coconut_match_to_kwargs):
        _coconut_match_check = False
        if (_coconut.len(_coconut_match_to_args)
                == 1) and (_coconut.isinstance(_coconut_match_to_args[0],
                                               _coconut.abc.Iterable)):
            xs = _coconut.iter(_coconut_match_to_args[0])
            _coconut_match_temp_0 = _coconut.tuple(
                _coconut_igetitem(xs, _coconut.slice(None, 1)))
            if (_coconut.len(_coconut_match_temp_0)
                    == 1) and (not _coconut_match_to_kwargs):
                x = _coconut_match_temp_0[0]
                _coconut_match_check = True
        if not _coconut_match_check:
            _coconut_match_err = _coconut_MatchError(
                "pattern-matching failed for "
                "'def sieve([x] :: xs) = [x] :: sieve(n for n in xs if n % x)'"
                " in " + _coconut.repr(_coconut.repr(_coconut_match_to_args)))
            _coconut_match_err.pattern = 'def sieve([x] :: xs) = [x] :: sieve(n for n in xs if n % x)'
            _coconut_match_err.value = _coconut_match_to_args
            raise _coconut_match_err

        return _coconut_tail_call(
            _coconut.itertools.chain.from_iterable,
            (f()
             for f in (lambda: [x], lambda: sieve((n for n in xs if n % x)))))
Пример #18
0
def factorial(n, acc=1):
    def _coconut_mock_func(n, acc=1): return n, acc
    while True:
        """Compute n! where n is an integer >= 0."""
        _coconut_match_check = False
        _coconut_match_to = n
        if (_coconut_match_to == 0):
            _coconut_match_check = True
        if _coconut_match_check:
            return acc
        if not _coconut_match_check:
            _coconut_match_to = n
            if (_coconut.isinstance(_coconut_match_to, int)):
                if (n > 0):
                    _coconut_match_check = True
            if _coconut_match_check:
                if factorial is _coconut_recursive_func_3:
                    n, acc = _coconut_mock_func(n - 1, acc * n)
                    continue
                else:
                    raise _coconut_tail_call(factorial, n - 1, acc * n)

        if not _coconut_match_check:
            raise TypeError("the argument to factorial must be an integer >= 0")

# Test cases:
        return None
Пример #19
0
 def make_free_in(self, other):
     """Makes self free in other."""
     var = self.var
     newvar = var.prime()
     while other != other.substitute({var: newvar}):
         var, newvar = newvar, newvar.prime()
     return _coconut_tail_call(self.change_var, var)
Пример #20
0
def transform(means, stds, df):
    feature_columns = [c for c in df if 'feat:' in c]
    features = df[feature_columns].values.astype('float32')
    normalised = (features - means) / stds
    return _coconut_tail_call(
        df.assign, **{f: x
                      for f, x in zip(feature_columns, normalised.T)})
Пример #21
0
 def find_unification(self, other):
     """Find a substitution in self that would make self into other."""
     if isinstance(other, Quantifier):
         return _coconut_tail_call(other.find_unification, self)
     elif self == other:
         return {}
     else:
         return None
Пример #22
0
 def resolve_against(self, other, **kwargs):
     """Attempt to perform a resolution against other else None."""
     if isinstance(other, (Not, Or, Eq)):
         return _coconut_tail_call(other.resolve_against, self, **kwargs)
     elif (self.find_unification)(Not(other).simplify(**kwargs)) is not None:
         return bot
     else:
         return None
Пример #23
0
 def resolve(self, **kwargs):
     inner_kwargs = self.inner_kwargs(kwargs)
     variables = inner_kwargs.get("variables")
     if variables is None:
         skolem_elem = self.elem
     else:
         skolem_var = Func(self.var.name, *variables)
         skolem_elem = self.elem.substitute({self.var: skolem_var})
     return _coconut_tail_call(Exists(self.var, skolem_elem.resolve(**inner_kwargs)).simplify, dnf=False, **kwargs)
Пример #24
0
 def merge(self):
     """Merges nested copies of a boolean operator."""
     elems = []
     for x in self.elems:
         if isinstance(x, self.__class__):
             elems.extend(x.merge().elems)
         else:
             elems.append(x)
     return _coconut_tail_call(self.__class__, *elems)
Пример #25
0
 def prenex(self, **kwargs):
     """Pulls quantifiers out."""
     for i, x in enumerate(self.elems):
         if isinstance(x, Quantifier) and self.can_prenex(x, **kwargs):
             elems = self.elems[:i] + self.elems[i + 1:]
             free_x = x.make_free_in(self.__class__(*elems))
             elems += (free_x.elem,)
             return _coconut_tail_call(free_x.change_elem(self.__class__(*elems)).simplify, **kwargs)
     return self
Пример #26
0
 def distribute(self, dnf=False, **kwargs):
     """If this And contains an Or, distribute into it."""
     kwargs["dnf"] = dnf
     if dnf:
         for i, x in enumerate(self.ands):
             if isinstance(x, Or):
                 ors = ((And)(*(y,) + self.ands[:i] + self.ands[i + 1:]) for y in x.ors)
                 return _coconut_tail_call(Or(*ors).simplify, **kwargs)
     return self
Пример #27
0
 def distribute(self, dnf=False, **kwargs):
     """If this Or contains an And, distribute into it."""
     kwargs["dnf"] = dnf
     if not dnf:
         for i, x in enumerate(self.ors):
             if isinstance(x, And):
                 ands = ((Or)(*(y,) + self.ors[:i] + self.ors[i + 1:]) for y in x.ands)
                 return _coconut_tail_call(And(*ands).simplify, **kwargs)
     return self
def primes():
    @_coconut_tco
    def sieve(numbers):
        head = next(numbers)
        return _coconut_tail_call(
            _coconut.itertools.chain.from_iterable,
            (f() for f in (lambda: [head],
                           lambda: sieve((n for n in numbers if n % head)))))

    return _coconut_tail_call(sieve, count(2))
Пример #29
0
 def __new__(cls, *pts):
     """Create a new vector from the given pts."""
     _coconut_match_to = pts
     _coconut_match_check = False
     if (_coconut.isinstance(_coconut_match_to, _coconut.abc.Sequence)) and (_coconut.len(_coconut_match_to) == 1) and (_coconut.isinstance(_coconut_match_to[0], vector)):
         v = _coconut_match_to[0]
         _coconut_match_check = True
     if _coconut_match_check:
         return v  # vector(v) where v is a vector should return v
     else:
         return _coconut_tail_call(makedata, cls, *pts)  # accesses base constructor
Пример #30
0
 def substitute_elements(self, subs, **kwargs):
     if not can_sub(kwargs):
         return self
     _coconut_match_to = subs
     _coconut_match_check = False
     if _coconut.isinstance(_coconut_match_to, _coconut.abc.Mapping):
         _coconut_match_temp_0 = _coconut_match_to.get(self.proposition(), _coconut_sentinel)
         if _coconut_match_temp_0 is not _coconut_sentinel:
             sub = _coconut_match_temp_0
             _coconut_match_check = True
     if _coconut_match_check:
         assert isinstance(sub, Atom), sub
         do_sub(kwargs)
         name = sub.name
     else:
         name = self.name
     if can_sub(kwargs):
         return _coconut_tail_call(Pred, name, *map(_coconut.operator.methodcaller("substitute", subs, **kwargs), self.args))
     else:
         return _coconut_tail_call(Pred, name, *self.args)
Пример #31
0
    def resolve(self, nonempty_universe=True, debug=False, **kwargs):
        """Performs all possible resolutions within the And."""
        kwargs["nonempty_universe"], kwargs["debug"] = nonempty_universe, debug
        resolved = super(And, self).resolve(**kwargs)
        if not isinstance(resolved, And):
            log_simplification(self, resolved, **kwargs)
            return resolved
        clauses = (list)(resolved.ands)
        quantifiers = []
        if not nonempty_universe and not self.admits_empty_universe():
            blank = Exists.blank(top)
            (quantifiers.append)(blank.change_elem)
            kwargs = (blank.inner_kwargs)(kwargs)
        prev_clause_len = 1
        while prev_clause_len < len(clauses):
            prev_clause_len = len(clauses)
# reversed ensures conclusions get tested first
            for i in (reversed)(range(1, len(clauses))):
                x = clauses[i]
                for y in clauses[:i + 1]:  # allow resolution of a clause against itself
                    resolution = x.resolve_against(y)
                    if resolution is not None:
                        resolution = resolution.simplify(dnf=False, **kwargs)
                        if debug:
                            print(x, "+", y, "=>", resolution)
                        new_quantifiers = []
                        inner_kwargs = kwargs
                        while isinstance(resolution, Quantifier) and self.can_prenex(resolution, **kwargs):
                            (new_quantifiers.append)(resolution.change_elem)
                            inner_kwargs = (resolution.inner_kwargs)(inner_kwargs)
                            resolution = resolution.elem
                        if isinstance(resolution, And):
                            new_clauses = resolution.ands
                        else:
                            new_clauses = (resolution,)
                        novel = False
                        for new_clause in new_clauses:
                            if new_clause == bot:
                                clauses = [bot]
                                novel = True
                                break
                            elif new_clause != top and new_clause not in clauses:
                                clauses.append(new_clause)
                                novel = True
                        if novel:
                            quantifiers.extend(new_quantifiers)
                            kwargs = inner_kwargs
                            if clauses == [bot]:
                                break
                if clauses == [bot]:
                    break
        resolved = reduce(_coconut_pipe, [And(*clauses)] + quantifiers)
        log_simplification(self, resolved, **kwargs)
        return _coconut_tail_call(resolved.simplify, dnf=False, **kwargs)
Пример #32
0
 def __new__(cls, *elems):
     if not elems:
         if cls.identity is None:
             raise TypeError(cls.__name__ + " requires at least one argument")
         else:
             return cls.identity
     elif len(elems) == 1:
         assert wff(elems[0]), elems[0]
         return elems[0]  # sometimes returns an instance of cls
     else:
         return _coconut_tail_call(super(BinaryOp, cls).__new__, cls)
Пример #33
0
    def angle(*_coconut_match_to):
        _coconut_match_check = False
        if (_coconut.len(_coconut_match_to) == 2) and (_coconut.isinstance(_coconut_match_to[1], vector)):
            self = _coconut_match_to[0]
            other = _coconut_match_to[1]
            _coconut_match_check = True
        if not _coconut_match_check:
            _coconut_match_err = _coconut_MatchError("pattern-matching failed for " "'def angle(self, other is vector) = math.acos(self.unit() * other.unit())'" " in " + _coconut.repr(_coconut.repr(_coconut_match_to)))
            _coconut_match_err.pattern = 'def angle(self, other is vector) = math.acos(self.unit() * other.unit())'
            _coconut_match_err.value = _coconut_match_to
            raise _coconut_match_err

        raise _coconut_tail_call(math.acos, self.unit() * other.unit())
Пример #34
0
def factorial(*_coconut_match_to):
    _coconut_match_check = False
    if (_coconut.len(_coconut_match_to) == 1) and (_coconut.isinstance(_coconut_match_to[0], int)):
        n = _coconut_match_to[0]
        if (n > 0):
            _coconut_match_check = True
    if not _coconut_match_check:
        _coconut_match_err = _coconut_MatchError("pattern-matching failed for " "'def factorial(n is int if n > 0) ='" " in " + _coconut.repr(_coconut.repr(_coconut_match_to)))
        _coconut_match_err.pattern = 'def factorial(n is int if n > 0) ='
        _coconut_match_err.value = _coconut_match_to
        raise _coconut_match_err

    """Compute n! where n is an integer >= 0."""
    raise _coconut_tail_call(reduce, _coconut.operator.mul, range(1, n + 1))
Пример #35
0
    def __sub__(self, other):
        """Subtract one vector from another."""
        _coconut_match_check = False
        _coconut_match_to = other
        if (_coconut.isinstance(_coconut_match_to, vector)) and (_coconut.len(_coconut_match_to) == 1):
            other_pts = _coconut_match_to[0]
            _coconut_match_check = True
        if not _coconut_match_check:
            _coconut_match_err = _coconut_MatchError("pattern-matching failed for " "'vector(other_pts) = other'" " in " + _coconut.repr(_coconut.repr(_coconut_match_to)))
            _coconut_match_err.pattern = 'vector(other_pts) = other'
            _coconut_match_err.value = _coconut_match_to
            raise _coconut_match_err

        assert len(other_pts) == len(self.pts)
        raise _coconut_tail_call((vector), *map(_coconut_minus, self.pts, other_pts))
Пример #36
0
def factorial(n):
    """Compute n! where n is an integer >= 0."""
    _coconut_match_check = False
    _coconut_match_to = n
    if (_coconut_match_to == 0):
        _coconut_match_check = True
    if _coconut_match_check:
        return 1
    if not _coconut_match_check:
        _coconut_match_to = n
        if (_coconut.isinstance(_coconut_match_to, int)):
            if (n > 0):
                _coconut_match_check = True
        if _coconut_match_check:
            raise _coconut_tail_call(reduce, _coconut.operator.mul, range(1, n + 1))
    if not _coconut_match_check:
        raise TypeError("the argument to factorial must be an integer >= 0")
Пример #37
0
 def __abs__(self):
     """Return the magnitude of the vector."""
     raise _coconut_tail_call(((lambda s: s**0.5)), (sum)(map(lambda x: x**2, self.pts)))
Пример #38
0
 def __truediv__(self, other):
     raise _coconut_tail_call((vector), *map(lambda x: x / other, self.pts))
Пример #39
0
 def __new__(cls, *pts):
     """Create a new vector from the given pts."""
     if len(pts) == 1 and (isinstance)(pts[0], vector):
         return pts[0]  # vector(v) where v is a vector should return v
     else:
         raise _coconut_tail_call((datamaker(cls)), (tuple)(pts))  # accesses base constructor
Пример #40
0
def vector_field():
    raise _coconut_tail_call(map, lambda xy: vector(*xy), linearized_plane())
Пример #41
0
def linearized_plane(n=0):
    raise _coconut_tail_call(_coconut.itertools.chain.from_iterable, (_coconut_lazy_item() for _coconut_lazy_item in (lambda: diagonal_line(n), lambda: linearized_plane(n + 1))))
Пример #42
0
def diagonal_line(n):
    raise _coconut_tail_call(map, lambda i: (i, n - i), range(n + 1))
Пример #43
0
 def __neg__(self):
     """Retrieve the negative of the vector."""
     raise _coconut_tail_call((vector), *map(_coconut_minus, self.pts))