コード例 #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)
コード例 #2
0
ファイル: utilsmath.py プロジェクト: ddoyen/maths-pl-bank
def str2finiteset(s, local_dict={}):
    """
    Convert a latex string into a finite set.
    """
    s = s.strip()
    if s == "\\emptyset":
        return EmptySet()
    pattern = re.compile(r'^\\{(.*)\\}$')
    if pattern.match(s) is not None:
        elements = str2expr(pattern.match(s).group(1))
        if type(elements) == tuple:
            return sp.FiniteSet(*elements)
        else:
            return sp.FiniteSet(elements)
コード例 #3
0
ファイル: utilsmath.py プロジェクト: ddoyen/maths-pl-bank
def str2interval(s, local_dict={}):
    """
    Convert a latex string into an interval.
    """
    s = s.strip()
    s = s.replace("\emptyset", "EmptySet()")
    s = s.replace("\R", "S.Reals")
    s = s.replace("\infty", "oo")
    pattern = re.compile(r'\\{(.*)\\}')
    if pattern.search(s) is not None:
        return sp.FiniteSet(str2expr(pattern.search(s).group(1)))
    pattern = re.compile(r'\\lbrack(.*),(.*)\\rbrack')
    if pattern.search(s) is not None:
        return sp.Interval(str2expr(pattern.search(s).group(1)),
                           str2expr(pattern.search(s).group(2)))
    pattern = re.compile(r'\\lbrack(.*),(.*)\\lbrack')
    if pattern.search(s) is not None:
        return sp.Interval.Ropen(str2expr(pattern.search(s).group(1)),
                                 str2expr(pattern.search(s).group(2)))
    pattern = re.compile(r'\\rbrack(.*),(.*)\\rbrack')
    if pattern.search(s) is not None:
        return sp.Interval.Lopen(str2expr(pattern.search(s).group(1)),
                                 str2expr(pattern.search(s).group(2)))
    pattern = re.compile(r'\\rbrack(.*),(.*)\\lbrack')
    if pattern.search(s) is not None:
        return sp.Interval.open(str2expr(pattern.search(s).group(1)),
                                str2expr(pattern.search(s).group(2)))
コード例 #4
0
ファイル: sets.py プロジェクト: o2edu/MathsExams
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)))
コード例 #5
0
def solve_rectangle_eqs(E, w, h, k):
    n_rect_vars = E.shape[1]
    # For a fully symbolic solution, uncomment next line and specify
    # symbols in solver:
    # w, h, k = sp.symbols('w h k')
    N = n_rect_vars//2
    dF = [0]*(3*N + 1)
    size_avg = w*h/N
    # c controls the relation between the two optimization criteria.
    c = 0.
    T = c*h*h
    # Factor for size
    Q = 1.
    # Add symbols (widths, heights, lambdas)
    W = sp.symbols('w:{}'.format(N), positive=True)
    H = sp.symbols('h:{}'.format(N), positive=True)
    L = sp.symbols('l:{}'.format(N + 1))
    # Create the expressions
    # dF/dw_i
    for i in range(N):
        dF[i] = 2*Q*H[i]*(W[i]*H[i] - size_avg)
        dF[i] += 2*T*(W[i] - k*H[i])
        for j in range(N + 1):
            dF[i] += L[j]*E[j, i]
    # dF/dh_i
    for i in range(N):
        dF[N + i] = 2*Q*W[i]*(W[i]*H[i] - size_avg)
        dF[N + i] += -2*T*k*(W[i] - k*H[i])
        for j in range(N + 1):
            dF[N + i] += L[j]*E[j, N + i]
    # dF/dl_j
    for j in range(N + 1):
        for i in range(N):
            dF[2*N + j] += E[j, i]*W[i] + E[j, N + i]*H[i]
    dF[2*N] += -w
    dF[2*N + 1] += -h
    # Solve the system
    symbols = []
    symbols.extend(W)
    symbols.extend(H)
    symbols.extend(L)
    # 1. nonlinsolve() if Q != 0
    # 2. linsolve() if Q == 0
    # 3. solve() seems to work better than nonlinsolve(), but only if
    #    you run sp.solve(dF), not sp.solve(dF, symbols), which is weird.
    #    To use it, convert solution to return a FiniteSet.
    # return sp.nonlinsolve(dF, symbols)
    # return sp.linsolve(dF, symbols)
    sol_dict = sp.solve(dF)
    if len(sol_dict) > 1:
        print('Warning: more than one solution')
    mat = get_matrix_from_solution(N, sol_dict[0])
    sol_ls = []
    for i in range(N):
        sol_ls.append(mat[0, i])
    for i in range(N):
        sol_ls.append(mat[1, i])
    return sp.FiniteSet(tuple(sol_ls))
コード例 #6
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)
コード例 #7
0
 def meros(self, super, constraint):  #部分集合の生成
     emp = []
     x = self.x
     for i in super:
         x = x.subs(x, i)
         expr = eval(constraint)
         if expr == True:
             emp.append(i)
     return sp.FiniteSet(*emp)
コード例 #8
0
ファイル: functions.py プロジェクト: o2edu/MathsExams
def maximal_domain(expr, domain=sympy.Interval(-oo, oo)):
    ''' Return the maximal domain of an expression.

    >>> maximal_domain(sympy.log(x**2 - 1))
    (-oo, -1) U (1, oo)

    >>> maximal_domain(1 / (x**2 - 4))
    (-oo, -2) U (-2, 2) U (2, oo)

    >>> maximal_domain((x - 2) ** (sympy.Rational(3, 2)))
    (2, oo)
    '''

    # 4 possible scenarios:
    #       1. 1/(a) -- a != 0
    #       2. sqrt(b) -- b > 0
    #       3. log(c) -- c > 0
    #       4. tan(d) -- d != the solutions of tan

    for symbol in expr.free_symbols:
        if symbol == x:
            expr = expr.replace(x, sympy.Symbol('x', real=True))
        else:
            raise NotImplementedError('only x is currently supported - but that can be easily changed')

    powers = expr.find(sympy.Pow)
    # case 1
    for power in powers:
        if power.args[1] < 0:
            denominator = power.args[0]

            solution = sympy.solve(denominator)
            domain &= -sympy.FiniteSet(solution)

        # case 2
        if isinstance(power.args[1], sympy.Rational):
            if power.args[1].q % 2 != 0:
                continue

            sqrt_interior = power.args[0]

            solution = sympy.solve(sqrt_interior > 0)
            domain &= relation_to_interval(solution)

    # case 3
    logs = expr.find(sympy.log)
    for log in logs:
        interior = log.args[0]

        solution = sympy.solve(interior > 0)
        domain &= relation_to_interval(solution)

    # case 4
    if expr.find(sympy.tan) or expr.find(sympy.cot) or expr.find(sympy.sec) or expr.find(sympy.csc):
        raise NotImplementedError('tan/cot/sec/csc are not supported')

    return domain
コード例 #9
0
ファイル: equation.py プロジェクト: khoi-nguyen/mathsnuggets
 def correct(self):
     if not self.answer:
         return False
     # Prevent user from just copying the equation
     for sol in self.answer:
         if len(sol.atoms(sympy.Symbol)):
             return False
     solution = sympy.solveset(self.equation, self.x)
     sol_count = len(solution.args)
     return len(solution.intersect(
         sympy.FiniteSet(*self.answer)).args) >= sol_count
コード例 #10
0
ファイル: parameter.py プロジェクト: billdenney/pharmpy
    def parameter_space(self):
        """The parameter space set

        A fixed parameter will be constrained to one single value
        and non-fixed parameters will be constrained to an interval
        possibly open in one or both ends.
        """
        if self.fix:
            return sympy.FiniteSet(self.init)
        else:
            return sympy.Interval(self.lower, self.upper)
コード例 #11
0
    def __init__(self, *items, name='noName'):
        '''
        Init a relation object.

        parameters:
          items: 2-tuple list define the relation
          name:this is an optional argument,you can give name to the relation
        returns
           a relation object  
        example:
           Relation.setA(1,2,3)
           r1  = Relation((1,2),(2,3),name = "simple relation')

        '''
        #if sympy.Eq(self.A,sympy.EmptySet):
        #    print('empty A')
        #    self.setA(1,2,3,4)
        if len(items) == 0:
            sympy.FiniteSet(('xxx', 'xxx'))
        else:
            sympy.FiniteSet(self, *items)
        self.name = name
コード例 #12
0
ファイル: piecewise.py プロジェクト: o2edu/MathsExams
    def __init__(self, part):
        self.num_lines, self.num_marks = 3, 1
        self._qp = copy.deepcopy(part._qp)

        self._qp['domain'] = sympy.Interval(-sympy.oo, sympy.oo)
        for piecewise_part in self._qp['equation'].args:
            expr = piecewise_part[0]

            self._qp['domain'] &= functions.maximal_domain(
                expr, self._qp['domain'])

            if expr.find(
                    sympy.Abs
            ):  # an absolute value is not differentiable at its vertex
                match = expr.match(coeff0 * sympy.Abs(coeff1 * x - coeff2) +
                                   coeff3)
                self._qp['domain'] -= sympy.FiniteSet(match[coeff2] /
                                                      match[coeff1])

        # a piecewise function is not differentiable at the meeting points of the subparts (unless the same y-coordinate
        # and the same derivative is approached from both sides, which it is guaranteed not to)
        middle = self._qp['equation'].args[0].args[1].rhs
        self._qp['domain'] -= sympy.FiniteSet(middle)
コード例 #13
0
def closest(sample_args, count=None):
    """Ask for the closest to a given value in a list."""
    sample_args = sample_args()
    context = composition.Context()

    entropy, sample_args = sample_args.peel()
    if count is None:
        count = random.randint(*_closest_count_range(entropy))

    display_multichoice = random.choice([False, True])
    if display_multichoice:
        _mark_choice_letters_used(count, context)

    entropy_target, entropy_list = entropy * np.random.dirichlet([1, count])
    target = integer_or_rational_or_decimal(entropy_target)

    while True:
        value_entropies = entropy_list * np.random.dirichlet(np.ones(count))
        value_entropies = np.maximum(1, value_entropies)
        values = [
            integer_or_rational_or_decimal(ent) for ent in value_entropies
        ]
        differences = [abs(sympy.sympify(value) - target) for value in values]
        if len(sympy.FiniteSet(
                *differences)) == count:  # all differences unique
            break

    target_and_entities = context.sample(sample_args, [target] + values)
    target = target_and_entities[0]
    entities = target_and_entities[1:]

    min_difference = min(differences)
    answer_index = differences.index(min_difference)
    answer = entities[answer_index]
    adjective = random.choice([
        'terdekat',
    ])

    if display_multichoice:
        return _closest_multichoice_question(context=context,
                                             entities=entities,
                                             target=target,
                                             adjective=adjective,
                                             answer=answer)
    else:
        return _closest_in_list_question(context=context,
                                         entities=entities,
                                         target=target,
                                         adjective=adjective,
                                         answer=answer)
コード例 #14
0
    def setA(cls, *items):
        """
        This is a class method. Set discourse

        Parameters:
            items: lists of elements of set
        Returns:
            no return
        """
        cls.A = sympy.FiniteSet(*items)
        cls.id2items = {}
        num = 0
        for i in cls.A:
            cls.id2items[num] = i
            num = num + 1
コード例 #15
0
def concept_solution(request, concept_id):
    """
    Retrieve, update or delete a code concept.
    """
    # Functions of request.query_params: https://kite.com/python/docs/django.http.QueryDict
    hypothesis_str = request.query_params.get('hypothesis')
    goal_str = request.query_params.get('goal')

    try:
        concept = Concept.objects.get(pk=concept_id)
    except Concept.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)
    
    local_vars = {}
    for attribute in concept.attributes.get_queryset():
        symbol = attribute.symbol
        local_vars[symbol] = sympy.symbols(symbol)
    
    equations = sympy.FiniteSet()
    for eq in concept.equations.get_queryset():
        equations += sympy.FiniteSet(sympy.sympify(eq.syntax,local_vars))

    hypothesis = sympy.FiniteSet(*sympy.sympify(hypothesis_str, locals=local_vars))
    goal = sympy.FiniteSet(*sympy.sympify(goal_str, locals=local_vars))

    known, solution, giaThuyet = kernel.SuyDienTien(hypothesis, goal, TapDangThuc=equations)

    return Response({
        "hypothesis": hypothesis_str,
        "goal": goal_str,
        "solution": [{
            step[0]:str(step[1]),
            step[2]:str(step[3]),
            step[4]:str(step[5])
        } for step in solution]
    })
コード例 #16
0
ファイル: st.py プロジェクト: aemi-dev/ter_ecosys
 def __call__(self, spec, instance):
     args = dict(zip(self.parameters, instance.arguments))
     args[_THISLOC] = sympy.Symbol(instance.name)
     return self.__class__(
         name=instance.name,
         parameters=[],
         variables=[v.subs(args) for v in self.variables],
         constraints=[c.subs(args) for c in self.constraints],
         rules=[r.subs(args) for r in self.rules],
         labels=subs(
             sympy.FiniteSet(self.name)
             | self.labels
             | instance.labels, args),
         decl=self,
         instance=instance,
         specification=spec)
コード例 #17
0
def _unique_values(entropy, only_integers=False, count=None):
    """Generates unique values."""
    if count is None:
        count = random.randint(*_sort_count_range(entropy))

    if only_integers:
        sampler = functools.partial(number.integer, signed=True)
    else:
        sampler = integer_or_rational_or_decimal

    for _ in range(1000):
        entropies = entropy * np.random.dirichlet(np.ones(count))
        entropies = np.maximum(1, entropies)
        values = [sampler(ent) for ent in entropies]
        if len(sympy.FiniteSet(*values)) == len(values):
            return values
    raise ValueError(
        'Could not generate {} unique values with entropy={}'.format(
            count, entropy))
コード例 #18
0
ファイル: parameter.py プロジェクト: pharmpy/pharmpy
    def parameter_space(self):
        """The parameter space set

        A fixed parameter will be constrained to one single value
        and non-fixed parameters will be constrained to an interval
        possibly open in one or both ends.

        Examples
        --------

        >>> import sympy
        >>> from pharmpy import Parameter
        >>> par = Parameter("x", 1, lower=0, upper=10)
        >>> sympy.pprint(par.parameter_space)
        [0, 10]

        >>> par.fix = True
        >>> sympy.pprint(par.parameter_space)
        {1}
        """
        if self.fix:
            return sympy.FiniteSet(self.init)
        else:
            return sympy.Interval(self.lower, self.upper)
コード例 #19
0
 def olokliro(self, object=[]):  #(全体)集合の生成
     return sp.FiniteSet(*object)
コード例 #20
0
ファイル: test_parameter.py プロジェクト: stellabelin/pharmpy
def test_parameter_space():
    p1 = Parameter('Y', 9, fix=True)
    assert p1.parameter_space == sympy.FiniteSet(9)
    p2 = Parameter('X', 10, lower=0, upper=15)
    assert p2.parameter_space == sympy.Interval(0, 15)
コード例 #21
0
ファイル: utilsmath.py プロジェクト: ddoyen/maths-pl-bank
def rand_finiteset(n, items, excluded_values=[]):
    """
    Generate a random finite set.
    """
    return sp.FiniteSet(*list_randitem_norep(n, items, excluded_values=[]))
コード例 #22
0
ファイル: Model.py プロジェクト: MikaZeilstra/ModellingArch
    def calculate_transitions(self, data : dict[list[float], list[float]], FixedTransitions=None, InitialGuessInterval= (0,10),LowerBoundTransitionRates = 1e-10,MaxTries=50 ) -> dict[sp.Symbol,float]:
        if FixedTransitions is None:
            FixedTransitions = {}

        # Find the charactertic polynomial
        cPoly = self.M.charpoly().expr

        # Get the lambda symbol
        lam = cPoly.free_symbols.difference(sp.FiniteSet(*self.Transitions)).pop()

        # Substitute the lambdas for the known values and scale affected transition rates to the given value
        filledLambdas = []
        for Intensity in data.keys():
            ExtraCPoly = copy.deepcopy(cPoly)
            for i in range(len(Intensity)):
                ExtraCPoly = ExtraCPoly.subs(zip(self.LightDependentTransitions[i], map(lambda x: Intensity[i] * x, self.LightDependentTransitions[i])))

            filledLambdas += list(map(lambda x: ExtraCPoly.subs(lam, x), data[Intensity]))

        # Store the actual symbol instead of reference in Fixed ks
        for i in range(len(filledLambdas)):
            filledLambdas[i] = filledLambdas[i].subs(FixedTransitions.items())
        
        
        # Use set subtraction to get the symbols for which need to be solved
        UnkownK = [k for k in self.Transitions if k not in FixedTransitions.keys()]
        NumberOfUnkownTransitions = len(UnkownK)

        # Export system to list of functions
        def func(fun):
            return lambda x: fun(*x)

        NonlinearSystem = []
        for exp in filledLambdas:
            NonlinearSystem.append(func(sp.lambdify(UnkownK, exp)))

        # Setup the variables needed to loop
        Tries = 0
        Rates = {"success": False, "active_mask": [-1]}

        # Try and find a solution with new random starting points 10 times. a solution is reject if the bounds are active (active_mask) this means the solution is either on or lower than th given lower bound
        while (((not (all([x == 0 for x in Rates['active_mask']]))) or (not Rates["success"])) and (Tries < MaxTries)):
            Rates = opt.least_squares(fun=lambda num: list(map(lambda x: x(num), NonlinearSystem)),
                                      x0=np.random.rand((NumberOfUnkownTransitions)) * (InitialGuessInterval[1] - InitialGuessInterval[0]) +InitialGuessInterval[0],
                                      bounds=(LowerBoundTransitionRates, np.inf))
            Tries += 1

        # Print the solution if found otherwise error
        if (Tries >= MaxTries):
            # If we havenot find a solution throw an error and show the last Rates Object.
            print(Rates)
            raise RuntimeError("Could not solve for the transition rates in " + str(
                MaxTries) + " tries with given constraints Not all in bounds was " + str(
                (not (all([x == 0 for x in Rates['active_mask']])))))

        print("Found transition rates in " + str(Tries) + " tries.")
        # The k values are the value of x in the Rates object. These values are the free transition rates in order with the known transition rates removed
        print(Rates)

        # Setup list of the transition rates
        self.TransitionRates = dict(zip(UnkownK, Rates['x'])) | FixedTransitions

        print("Transitions : " + str(self.TransitionRates))
        return self.TransitionRates
コード例 #23
0
class Relation(sympy.FiniteSet):
    """
    Define Relation class inherited from FinitSet.
    @author hawksoft
    """
    A = sympy.FiniteSet()
    id2items = {}

    @classmethod
    def setA(cls, *items):
        """
        This is a class method. Set discourse

        Parameters:
            items: lists of elements of set
        Returns:
            no return
        """
        cls.A = sympy.FiniteSet(*items)
        cls.id2items = {}
        num = 0
        for i in cls.A:
            cls.id2items[num] = i
            num = num + 1

    @classmethod
    def getUniversal(cls):
        """
        This is a class method. Get the Universal Relation on the discourse.

        Parameters:
            none.
        Returns:
            Return the universal relation on discourse.
        """
        temp = cls.A * cls.A
        l = []
        for i in temp:
            l.append(i)
        return Relation(*l, name='Universal Relation')

    @classmethod
    def getIdentity(cls):
        """
        This is a class method. Get the Identity Relation on the discourse.

        Parameters:
            none.
        Returns:
            Return the identity relation on discourse.
        """
        l = []
        for i in range(0, len(cls.id2items)):
            item = (cls.id2items[i], cls.id2items[i])
            l.append(item)
        return Relation(*l)

    def __init__(self, *items, name='noName'):
        '''
        Init a relation object.

        parameters:
          items: 2-tuple list define the relation
          name:this is an optional argument,you can give name to the relation
        returns
           a relation object  
        example:
           Relation.setA(1,2,3)
           r1  = Relation((1,2),(2,3),name = "simple relation')

        '''
        #if sympy.Eq(self.A,sympy.EmptySet):
        #    print('empty A')
        #    self.setA(1,2,3,4)
        if len(items) == 0:
            sympy.FiniteSet(('xxx', 'xxx'))
        else:
            sympy.FiniteSet(self, *items)
        self.name = name

    def drawGraphbyGraphviz(self):
        '''
        Draw relation graph by using graphviz package. Do not use it.
        '''
        g = gz.Graph(format='png')
        for i in self.C:
            g.node(str(i))
        l = []
        for i in self:
            l.append(str(i[0]) + str(i[1]))
        g.edges(l)
        #print(g.source)
        g.render('./test', view=True)

    def drawDigraphbyGraphviz(self):
        '''
        Draw relation graph by using graphviz package. Do not use it.
        '''
        g = gz.Digraph(format='png')
        for i in self.A:
            g.node(str(i))
        l = []
        for i in self:
            l.append(str(i[0]) + str(i[1]))
        g.edges(l)
        #print(g.source)
        g.render('./test', view=True)

    def showSet(self):
        '''
        This method show relation as a set

        Parameters:
          None.
        Returns:
          None.
        '''
        sympy.pprint(self)

    def showGraph(self):
        '''
        This method show relation as a graph.

        Parameters:
          None.
        Returns:
          None.
        '''
        g = networkx.DiGraph()
        listNode = [self.id2items[i] for i in self.id2items]
        g.add_nodes_from(listNode)
        listEdge = []
        for i in range(len(self.id2items)):
            for j in range(len(self.id2items)):
                item = (self.id2items[i], self.id2items[j])
                if self.contains(item) == True:
                    listEdge.append(item)
        g.add_edges_from(listEdge)
        plt.subplot(111)
        networkx.draw(g, with_labels=True, font_weight='bold')
        plt.show()

    def showMatrix(self):
        '''
        This method show relation as a matrix.

        Parameters:
          None.
        Returns:
          None.
        '''
        self.toMatrix()
        sympy.pprint(self.matrix)

    def toMatrix(self):
        if self.is_empty:
            matrix = sympy.zeros(len(len(self.id2itmes), len(self.id2itmes)))
        else:
            mat = []
            for i in range(0, len(self.id2items)):
                line = []
                for j in range(0, len(self.id2items)):
                    item = (self.id2items[i], self.id2items[j])
                    if self.contains(item) == True:
                        line.append(1)
                    else:
                        line.append(0)
                mat.append(line)
        self.matrix = sympy.Matrix(mat)
        return self.matrix

    def fromMatrix(self, matrix):
        l = []
        for i in range(0, len(self.id2items)):
            rows = matrix.row(i)
            for j in range(0, len(self.id2items)):
                if rows[j] == 1:
                    item = (self.id2items[i], self.id2items[j])
                    l.append(item)
        if len(l) == 0:
            l.append(('xxx', 'xxx'))
        return Relation(*l)

    def __add__(self, adds):
        '''
        Return a new relation which is self union with adds.
        '''
        temp = self.union(adds)
        l = []
        for i in temp:
            l.append(i)
        if len(l) == 0:
            l.append(('xxx', 'xxx'))
        result = Relation(*l)
        return result

    def __sub__(self, subs):
        '''
        Return a new relation which is self sub subs.
        '''
        temp = sympy.Complement(self, subs)
        l = []
        for i in temp:
            l.append(i)
        if len(l) == 0:
            l.append(('xxx', 'xxx'))
        result = Relation(*l)
        return result

    def __pow__(self, num):
        '''
        Return a new relation which is self's power.
        
        Parameters
          num: the exponents
        '''
        mat = self.toMatrix()
        if num == -1:
            mat = mat.T
        else:
            mat = mat**num
        return self.fromMatrix(mat)

    def intersect(self, other):
        temp = self.intersect(other)
        print(temp)
        l = []
        for i in temp:
            l.append(i)
        if len(l) == 0:
            l.append(('xxx', 'xxx'))
        result = Relation(*l)
        return result

    def reflectiveClosure(self):
        '''
        Return the reflectiveClosure
        '''
        return self + self.getIdentity()

    def symmetricClosure(self):
        '''
        Return the symmetricClosure
        '''
        return self + self**-1

    def transitiveClosure(self):
        '''
        Return the transitiveClosure
        '''
        temp = self
        for i in range(2, len(self.id2items)):
            temp1 = temp**i
            temp = temp + temp1
        return temp
コード例 #24
0
def symlabels (labels=None) :
    if labels :
        return sympy.FiniteSet(*(sympy.Symbol(l) if isinstance(l, str) else l
                                 for l in labels))
    else :
        return sympy.EmptySet
コード例 #25
0
ファイル: indices.py プロジェクト: QAlgebra/qalgebra
 def piecewise_one(self, expr):
     return Piecewise(
         (1, sympy.FiniteSet(*list(self.range)).contains(expr)), (0, True)
     )
コード例 #26
0
ファイル: indices.py プロジェクト: QAlgebra/qalgebra
 def piecewise_one(self, expr):
     return Piecewise(
         (1, sympy.FiniteSet(*self.values).contains(expr)), (0, True)
     )
コード例 #27
0
def polynomial_roots(value, sample_args, context=None):
    """E.g., "Solve 2*x**2 - 18 = 0."."""
    del value  # not currently used
    # is_question = context is None
    if context is None:
        context = composition.Context()

    entropy, sample_args = sample_args.peel()
    scale_entropy = min(entropy / 2, 1)

    roots = _sample_roots(entropy - scale_entropy)
    solutions = sorted(list(sympy.FiniteSet(*roots)))
    coeffs = _polynomial_coeffs_with_roots(roots, scale_entropy)
    (polynomial_entity, ) = context.sample(sample_args,
                                           [composition.Polynomial(coeffs)])

    if random.choice([False, True]):
        # Ask for explicit roots.
        if len(solutions) == 1:
            answer = solutions[0]
        else:
            answer = display.NumberList(solutions)

        if polynomial_entity.has_expression():
            equality = ops.Eq(polynomial_entity.expression, 0)
            variable = polynomial_entity.polynomial_variables[0]
        else:
            variable = sympy.Symbol(context.pop())
            equality = ops.Eq(polynomial_entity.handle.apply(variable), 0)
        template = random.choice([
            'Misalkan {equality}. Berapakah {variable}?',
            'Misalkan {equality}. Hitung {variable}.',
            'Misalkan {equality}. Berapakah {variable}?',
            'Misalkan {equality}. Hitung {variable}.',
            'Berapakah {variable} dalam {equality}?',
            'Selesaikan {equality} untuk {variable}.',
            'Temukan {variable} sehingga {equality}.',
            'Temukan {variable}, mengingat {equality}.',
            'Tentukan {variable} sehingga {equality}.',
            'Tentukan {variable}, mengingat bahwa {equality}.',
            'Selesaikan {equality}.'
        ])
        return example.Problem(question=example.question(context,
                                                         template,
                                                         equality=equality,
                                                         variable=variable),
                               answer=answer)
    else:
        if polynomial_entity.has_expression():
            expression = polynomial_entity.expression
            variable = polynomial_entity.polynomial_variables[0]
        else:
            variable = sympy.Symbol(context.pop())
            expression = polynomial_entity.handle.apply(variable)
        factored = sympy.factor(
            polynomials.coefficients_to_polynomial(coeffs, variable))
        template = random.choice([
            'Faktor dari {expression}.',
        ])
        return example.Problem(question=example.question(
            context, template, expression=expression),
                               answer=factored)