Exemplo n.º 1
0
def progFecthAnnot(arm, cart):
    # The variables:
    A_a, A_b, A_c = sp.symbols('A_a, A_b, A_c')
    C_x, C_y, C_theta = sp.symbols('C_x, C_y, C_theta')
    return {
        "A0":
        sp.true,
        "A1":
        sp.true,
        "A2":
        sp.true,
        "C0":
        sp.And(sp.Eq(C_x, 0), sp.Eq(C_y, 0), sp.Eq(C_theta, 0)),
        "C1":
        sp.And(sp.Eq(A_a, arm.maxAngleAB), sp.Eq(A_b, arm.minAngleAB),
               sp.Eq(A_c, 0), C_x >= 0, C_x <= 2, sp.Eq(C_y, 0)),
        "C2":
        sp.And(sp.Eq(A_a, arm.maxAngleAB), sp.Eq(A_b, arm.minAngleAB),
               sp.Eq(A_c, 0), sp.Eq(C_x, 2), sp.Eq(C_y, 0)),
        "C3":
        sp.And(sp.Eq(C_x, 2), sp.Eq(C_y, 0)),
        "C4":
        sp.And(sp.Eq(A_a, arm.maxAngleAB), sp.Eq(A_b, arm.minAngleAB),
               sp.Eq(A_c, 0), C_x >= 0, C_x <= 2, sp.Eq(C_y, 0))
    }
Exemplo n.º 2
0
def update_I(kb, kb_symbols, data_q, undefined, possible_states):
    del_I = []
    for place in kb:
        i, j, n, s = place.split(sep='_')
        if s == 'I':
            i, j, n = int(i), int(j), int(n)
            pattern = '{}_{}_*'.format(i, j)
            for state in undefined:
                if re.match(pattern, state):
                    i_s, j_s, n_s = state.split(sep='_')
                    if int(n_s) > n:
                        del_I.append(state)
                        new_symbol = state + '_I'
                        data_q.append(new_symbol)
                        kb.append(new_symbol)
                        new_symbol = sympy.symbols(new_symbol)
                        kb_symbols = sympy.And(kb_symbols, new_symbol)
                        for p in possible_states:
                            if p != 'I':
                                not_symbol = state + '_' + p
                                data_q.append('~' + not_symbol)
                                not_symbol = sympy.symbols(not_symbol)
                                kb_symbols = sympy.And(kb_symbols, ~not_symbol)
    undefined = [ele for ele in undefined if ele not in del_I]
    return kb_symbols, undefined
Exemplo n.º 3
0
def spreader(kb_symbols, undefined, kb, row_num, col_num, data_q, possible_states, police_num):
    undefined_sort = sorted(undefined)
    for u in range(len(undefined_sort)-1):
        i, j, n = undefined_sort[u].split(sep='_')
        i, j, n = int(i), int(j), int(n)
        pattern = '{}_{}_{}'.format(i, j, n+1)
        if undefined_sort[u+1] == pattern:
            infected_by_u = False
            if i > 0:
                infected_by_u = neigh_by_neigh(kb, i-1, j, n + 1, 'down', police_num, row_num, col_num, undefined)
            if not infected_by_u and i < row_num - 1:
                infected_by_u = neigh_by_neigh(kb, i+1, j, n + 1, 'up', police_num, row_num, col_num, undefined)
            if not infected_by_u and j > 0:
                infected_by_u = neigh_by_neigh(kb, i, j-1, n + 1, 'left', police_num, row_num, col_num, undefined)
            if not infected_by_u and j < col_num - 1:
                infected_by_u = neigh_by_neigh(kb, i, j + 1, n + 1, 'right', police_num, row_num, col_num, undefined)
            if infected_by_u:
                symbol = undefined_sort[u] + '_S'
                undefined.remove(undefined_sort[u])
                data_q.append(symbol)
                kb.append(symbol)
                symbol = sympy.symbols(symbol)
                kb_symbols = sympy.And(kb_symbols, symbol)
                if police_num > 0:
                    notq = undefined_sort[u+1] + '_Q'
                    data_q.append('~' + notq)
                    notq = sympy.symbols(notq)
                    kb_symbols = sympy.And(kb_symbols, ~notq)
                for p in possible_states:
                    if p != 'S':
                        not_symbol = undefined_sort[u] + '_' + p
                        data_q.append('~' + not_symbol)
                        not_symbol = sympy.symbols(not_symbol)
                        kb_symbols = sympy.And(kb_symbols, ~not_symbol)
    return kb_symbols
Exemplo n.º 4
0
def set_dtbs_error(model):
    """Dynamic transform both sides"""
    theta_as_stdev(model)
    set_weighted_error_model(model)
    stats, y, f = _preparations(model)
    tbs_lambda = Parameter('tbs_lambda', 1)
    tbs_zeta = Parameter('tbs_zeta', 0.001)
    model.parameters.append(tbs_lambda)
    model.parameters.append(tbs_zeta)
    lam = tbs_lambda.symbol
    zeta = tbs_zeta.symbol

    for i, s in enumerate(stats):
        if isinstance(s, Assignment) and s.symbol == sympy.Symbol('W'):
            break

    stats.insert(i + 1, Assignment('W', (f ** zeta) * sympy.Symbol('W')))
    ipred = sympy.Piecewise(
        ((f ** lam - 1) / lam, sympy.And(sympy.Ne(lam, 0), sympy.Ne(f, 0))),
        (sympy.log(f), sympy.And(sympy.Eq(lam, 0), sympy.Ne(f, 0))),
        (-1 / lam, sympy.And(sympy.Eq(lam, 0), sympy.Eq(f, 0))),
        (-1000000000, True),
    )
    stats.insert(i + 2, Assignment('IPRED', ipred))
    yexpr = stats.find_assignment(y.name)
    yexpr.subs({f: sympy.Symbol('IPRED')})

    obs = sympy.Piecewise(
        (sympy.log(y), sympy.Eq(lam, 0)), ((y ** lam - 1) / lam, sympy.Ne(lam, 0))
    )
    model.observation_transformation = obs

    return model
Exemplo n.º 5
0
    def _interpolation_indices(self, variables, offset=0):
        """
        Generate interpolation indices for the DiscreteFunctions in ``variables``.
        """
        index_matrix, points = self._index_matrix(offset)

        idx_subs = []
        for i, idx in enumerate(index_matrix):
            # Introduce ConditionalDimension so that we don't go OOB
            mapper = {}
            for j, d in zip(idx, self.grid.dimensions):
                p = points[j]
                lb = sympy.And(p >= d.symbolic_min - self._radius, evaluate=False)
                ub = sympy.And(p <= d.symbolic_max + self._radius, evaluate=False)
                condition = sympy.And(lb, ub, evaluate=False)
                mapper[d] = ConditionalDimension(p.name, self._sparse_dim,
                                                 condition=condition, indirect=True)

            # Track Indexed substitutions
            idx_subs.append(OrderedDict([(v, v.subs(mapper)) for v in variables
                                         if v.function is not self]))

        # Equations for the indirection dimensions
        eqns = [Eq(v, k) for k, v in points.items()]
        # Equations (temporaries) for the coefficients
        eqns.extend([Eq(p, c) for p, c in
                     zip(self._point_symbols, self._coordinate_bases)])

        return idx_subs, eqns
Exemplo n.º 6
0
def KB(observations,possible_states):
    # kb : list of strings defining states in observations
    kb = []
    kb_not = []
    # undefined : list of unknown states defined by strings of row_col_obsNum
    undefined = []
    # U : list of tuples (row,col) where there is U, at any observation
    U = []
    for item in enumerate(observations):
        obsNum = item[0]
        obs = item[1]
        for i in range(len(obs)):
            for j in range(len(obs[0])):
                state = obs[i][j]
                if state == '?':
                    undefined.append('{}_{}_{}'.format(i, j, obsNum))
                else:
                    kb.append('{}_{}_{}_{}'.format(i, j, obsNum, state))
                    for s in possible_states:
                        if s != state:
                            kb_not.append('~{}_{}_{}_{}'.format(i, j, obsNum, s))
                    if state == 'U':
                        U.append((i, j))
    kb_symbols = 1
    # transform strings to symbols
    # kb_symbols : expression of all strings in KB with & operator between them
    for symbol in kb:
        symbol = sympy.symbols(symbol)
        kb_symbols = sympy.And(kb_symbols, symbol)
    for symbol_n in kb_not:
        symbol_n = symbol_n[1:]
        symbol_n = sympy.symbols(symbol_n)
        kb_symbols = sympy.And(kb_symbols, ~symbol_n)
    return kb_symbols, undefined, U, kb, kb_not
Exemplo n.º 7
0
def pde_model_disc(N, dx):
    if dx < 0:
        raise ValueError("dx must be non-negative")

    if N < 1:
        raise ValueError("N must be positive")

    x = sympy.Symbol('x')
    r = sympy.Symbol('r')
    cl = sympy.Symbol('cl')
    L = sympy.Symbol('L')

    i = sympy.Idx('i')
    c = sympy.IndexedBase('c')
    m = model.Model()
    m.name = 'laplace discretised'
    m.parameters = {cl, L}
    m.solution_variables = {c[i]}
    m.bounds = sympy.And(i >= 0, i <= N)
    m.eqs = {
        (sympy.And(i > 0, i < N), sympy.Eq((c[i+1] - 2*c[i] - c[i-1])/(dx**2), 0)),
        (sympy.Eq(i, 0), sympy.Eq(c[i], cl)),
        (sympy.Eq(i, N), sympy.Eq((c[i] - c[i-1])/dx, 0))
    }

    return m
Exemplo n.º 8
0
def trig_substitution_rule(integral):
    integrand, symbol = integral
    A = sympy.Wild('a', exclude=[0, symbol])
    B = sympy.Wild('b', exclude=[0, symbol])
    theta = sympy.Dummy("theta")
    target_pattern = A + B*symbol**2

    matches = integrand.find(target_pattern)
    for expr in matches:
        match = expr.match(target_pattern)
        a = match.get(A, ZERO)
        b = match.get(B, ZERO)

        a_positive = ((a.is_number and a > 0) or a.is_positive)
        b_positive = ((b.is_number and b > 0) or b.is_positive)
        a_negative = ((a.is_number and a < 0) or a.is_negative)
        b_negative = ((b.is_number and b < 0) or b.is_negative)
        x_func = None
        if a_positive and b_positive:
            # a**2 + b*x**2. Assume sec(theta) > 0, -pi/2 < theta < pi/2
            x_func = (sympy.sqrt(a)/sympy.sqrt(b)) * sympy.tan(theta)
            # Do not restrict the domain: tan(theta) takes on any real
            # value on the interval -pi/2 < theta < pi/2 so x takes on
            # any value
            restriction = True
        elif a_positive and b_negative:
            # a**2 - b*x**2. Assume cos(theta) > 0, -pi/2 < theta < pi/2
            constant = sympy.sqrt(a)/sympy.sqrt(-b)
            x_func = constant * sympy.sin(theta)
            restriction = sympy.And(symbol > -constant, symbol < constant)
        elif a_negative and b_positive:
            # b*x**2 - a**2. Assume sin(theta) > 0, 0 < theta < pi
            constant = sympy.sqrt(-a)/sympy.sqrt(b)
            x_func = constant * sympy.sec(theta)
            restriction = sympy.And(symbol > -constant, symbol < constant)
        if x_func:
            # Manually simplify sqrt(trig(theta)**2) to trig(theta)
            # Valid due to assumed domain restriction
            substitutions = {}
            for f in [sympy.sin, sympy.cos, sympy.tan,
                      sympy.sec, sympy.csc, sympy.cot]:
                substitutions[sympy.sqrt(f(theta)**2)] = f(theta)
                substitutions[sympy.sqrt(f(theta)**(-2))] = 1/f(theta)

            replaced = integrand.subs(symbol, x_func).trigsimp()
            replaced = replaced.subs(substitutions)
            if not replaced.has(symbol):
                replaced *= manual_diff(x_func, theta)
                replaced = replaced.trigsimp()
                secants = replaced.find(1/sympy.cos(theta))
                if secants:
                    replaced = replaced.xreplace({
                        1/sympy.cos(theta): sympy.sec(theta)
                    })

                substep = integral_steps(replaced, theta)
                if not contains_dont_know(substep):
                    return TrigSubstitutionRule(
                        theta, x_func, replaced, substep, restriction,
                        integrand, symbol)
Exemplo n.º 9
0
def to_automaton(f) -> SymbolicDFA:  # noqa: C901
    """Translate to automaton."""
    f = f.to_nnf()
    initial_state = frozenset({frozenset({PLAtomic(f)})})
    states = {initial_state}
    final_states = set()
    transition_function = {}  # type: Dict

    all_labels = f.find_labels()
    alphabet = powerset(all_labels)

    if f.delta({}, epsilon=True) == PLTrue():
        final_states.add(initial_state)

    visited = set()  # type: Set
    to_be_visited = {initial_state}

    while len(to_be_visited) != 0:

        for q in list(to_be_visited):
            to_be_visited.remove(q)
            for actions_set in alphabet:
                new_state = _make_transition(
                    q, {label: True
                        for label in actions_set})
                if new_state not in states:
                    states.add(new_state)
                    to_be_visited.add(new_state)

                transition_function.setdefault(q, {})[actions_set] = new_state

                if new_state not in visited:
                    visited.add(new_state)
                    if _is_true(new_state):
                        final_states.add(new_state)

    automaton = SymbolicAutomaton()
    state2idx = {}
    for state in states:
        state_idx = automaton.create_state()
        state2idx[state] = state_idx
        if state == initial_state:
            automaton.set_initial_state(state_idx)
        if state in final_states:
            automaton.set_accepting_state(state_idx, True)

    for source in transition_function:
        for symbol, destination in transition_function[source].items():
            source_idx = state2idx[source]
            dest_idx = state2idx[destination]
            pos_expr = sympy.And(*map(sympy.Symbol, symbol))
            neg_expr = sympy.And(*map(lambda x: sympy.Not(sympy.Symbol(x)),
                                      all_labels.difference(symbol)))
            automaton.add_transition(
                (source_idx, sympy.And(pos_expr, neg_expr), dest_idx))

    determinized = automaton.determinize()
    minimized = determinized.minimize()
    return minimized
Exemplo n.º 10
0
 def check(cond__):
     false_cond = simplify_and(sympy.And(sympy.Not(cond__),
                                         extra_condition))
     if false_cond == sympy.sympify(False):
         return True
     true_cond = simplify_and(sympy.And(cond__, extra_condition))
     if true_cond == sympy.sympify(False):
         return False
     return None
Exemplo n.º 11
0
 def _parse_expression_list(self, is_conjunction: bool) -> sympy.Basic:
     """<expression_list> ::= <expression> <expression_list> | empty_string"""
     exp = sympy.And() if is_conjunction else sympy.Or()
     self._source_code.consume_leading_spaces()
     while self._source_code.current_char != (self.CONJUNCTION_END if is_conjunction else self.DISJUNCTION_END):
         exp = (sympy.And(exp, self._parse_expression()) if is_conjunction
                else sympy.Or(exp, self._parse_expression()))
         self._source_code.consume_leading_spaces()
     return exp
    def _execute_controller(self):

        rate = rospy.Rate(10)

        P, I = sp.var('p i')
        min_linear_vel = sp.var("minLinearVel")
        min_angular_vel = sp.var("minAngularVel")

        distErr, distVerticalErr, vertDiff, lastLinearOut = sp.var(
            'distErr distVerticalErr vertDiff lastLinearOut')
        anglErr, lastAngularOut, anglDiff = sp.var(
            'anglErr lastAngularOut anglDiff')

        self.linear_eq = sp.Piecewise(
            (sp.Max(P * distErr + I * lastLinearOut, min_linear_vel),
             sp.And(sp.Abs(anglErr) < anglDiff, distErr >= 0)),
            (sp.Min(P * distErr + I * lastLinearOut, -min_linear_vel),
             sp.And(sp.Abs(anglErr) < anglDiff, distErr < 0)),
            (0, sp.Abs(anglErr) >= anglDiff))

        self.linear_vertical_eq = sp.Piecewise(
            (sp.Max(P * distVerticalErr + I * lastLinearOut,
                    min_linear_vel), distVerticalErr > vertDiff), (0, True))

        angular_eq_temp = P * anglErr + I * lastAngularOut

        self.angular_eq = sp.Piecewise(
            (sp.Min(angular_eq_temp, -min_angular_vel), angular_eq_temp < 0),
            (sp.Max(angular_eq_temp, min_angular_vel), angular_eq_temp >= 0))

        constansts = {
            P: self.current_config["p"],
            I: self.current_config["i"],
            min_linear_vel: self.current_config["min_linear_vel"],
            min_angular_vel: self.current_config["min_angular_vel"],
            anglDiff: self.current_config["angular_diff"],
            vertDiff: self.current_config["vertical_diff"]
        }

        variables = [
            distErr, distVerticalErr, lastLinearOut, anglErr, lastAngularOut
        ]

        self.linear_eq = self.linear_eq.subs(constansts)
        self.linear_vertical_eq = self.linear_vertical_eq.subs(constansts)
        self.angular_eq = self.angular_eq.subs(constansts)

        while not rospy.is_shutdown():

            if self._goal != None and self._enabled:
                self._command_to(self._goal, variables)

            self._reach_publisher.publish(Bool(self._reach))

            rate.sleep()
Exemplo n.º 13
0
    def guard(self, expr=None, offset=0):
        """
        Generate guarded expressions, that is expressions that are evaluated
        by an Operator only if certain conditions are met.  The introduced
        condition, here, is that all grid points in the support of a sparse
        value must fall within the grid domain (i.e., *not* on the halo).

        Parameters
        ----------
        expr : expr-like, optional
            Input expression, from which the guarded expression is derived.
            If not specified, defaults to ``self``.
        offset : int, optional
            Relax the guard condition by introducing a tolerance offset.
        """
        _, points = self._index_matrix(offset)

        # Guard through ConditionalDimension
        conditions = {}
        for d, idx in zip(self.grid.dimensions, self._coordinate_indices):
            p = points[idx]
            lb = sympy.And(p >= d.symbolic_min - offset, evaluate=False)
            ub = sympy.And(p <= d.symbolic_max + offset, evaluate=False)
            conditions[p] = sympy.And(lb, ub, evaluate=False)
        condition = sympy.And(*conditions.values(), evaluate=False)
        cd = ConditionalDimension("%s_g" % self._sparse_dim,
                                  self._sparse_dim,
                                  condition=condition)

        if expr is None:
            out = self.indexify().xreplace({self._sparse_dim: cd})
        else:
            functions = {
                f
                for f in retrieve_function_carriers(expr)
                if f.is_SparseFunction
            }
            out = indexify(expr).xreplace(
                {f._sparse_dim: cd
                 for f in functions})

        # Temporaries for the position
        temps = [
            Eq(v, k, implicit_dims=self.dimensions)
            for k, v in self._position_map.items()
        ]
        # Temporaries for the indirection dimensions
        temps.extend([
            Eq(v, k.subs(self._position_map), implicit_dims=self.dimensions)
            for k, v in points.items() if v in conditions
        ])

        return out, temps
Exemplo n.º 14
0
def vaccine(kb, kb_symbols, data_q, undefined, medic_num, num_of_observations, possible_states):
    I_changes = [0] * num_of_observations # for each obs count the number on new I
    H_to_undefined = {k: [] for k in range(num_of_observations)} # for each obs count the number of h to undrfinrd
    H_count = [0] * num_of_observations
    undefined_count = [0] * num_of_observations
    undefined_current = {k: [] for k in range(num_of_observations)}
    for item in kb:
        row, col, obsNum, state = item.split(sep='_')
        obsNum = int(obsNum)
        if state == 'I' and '{}_{}_{}_H'.format(row, col, obsNum - 1) in kb:
            I_changes[obsNum] += 1
        if state == 'H':
            H_count[obsNum] += 1
            if '{}_{}_{}'.format(row, col, obsNum + 1) in undefined:
                H_to_undefined[obsNum + 1].append((row, col))
    for item1 in undefined:
        row, col, obsNum = item1.split(sep='_')
        obsNum = int(obsNum)
        undefined_current[obsNum].append((row,col))
        if '{}_{}_{}'.format(row, col, obsNum + 1) in undefined:
            undefined_count[obsNum + 1] += 1

    for i in range(1,num_of_observations):
        if len(H_to_undefined[i]) + undefined_count[i] <= (medic_num - I_changes[i]):
            for row, col in H_to_undefined[i]:
                symbol = '{}_{}_{}_I'.format(row, col, i)
                data_q.append(symbol)
                kb.append(symbol)
                undefined.remove('{}_{}_{}'.format(row, col, i))
                symbol = sympy.symbols(symbol)
                kb_symbols = sympy.And(kb_symbols, symbol)
                for p in possible_states:
                    if p != 'I':
                        not_symbol = '{}_{}_{}_{}'.format(row, col, i, p)
                        data_q.append('~' + not_symbol)
                        not_symbol = sympy.symbols(not_symbol)
                        kb_symbols = sympy.And(kb_symbols,~not_symbol)
    for i in range(num_of_observations):
        if H_count[i] + len((undefined_current[i])) <= medic_num:
            if i < num_of_observations - 1:
                for row, col in undefined_current[i+1]:
                    new_H = '{}_{}_{}_H'.format(row, col, i+1)
                    data_q.append('~' + new_H)
                    new_H = sympy.symbols(new_H)
                    kb_symbols = sympy.And(kb_symbols, ~new_H)
        if I_changes[i] == medic_num:
            for row, col in undefined_current[i]:
                new_I = '{}_{}_{}_I'.format(row, col, i)
                data_q.append('~' + new_I)
                new_I = sympy.symbols(new_I)
                kb_symbols = sympy.And(kb_symbols, ~new_I)

    return kb_symbols
Exemplo n.º 15
0
    def set_valve_resistances(self, p_v_l_, p_v_l_d_, p_v_r_, p_v_r_d_,
                              p_at_l_d_, p_at_r_d_, p_ar_sys_, p_ar_pul_):

        if self.valvelaw == 'pwlin_pres':
            R_vin_l_ = sp.Piecewise((self.R_vin_l_min, p_v_l_ < p_at_l_d_),
                                    (self.R_vin_l_max, p_v_l_ >= p_at_l_d_))
            R_vin_r_ = sp.Piecewise((self.R_vin_r_min, p_v_r_ < p_at_r_d_),
                                    (self.R_vin_r_max, p_v_r_ >= p_at_r_d_))
            R_vout_l_ = sp.Piecewise(
                (self.R_vout_l_max, p_v_l_d_ < p_ar_sys_),
                (self.R_vout_l_min, p_v_l_d_ >= p_ar_sys_))
            R_vout_r_ = sp.Piecewise(
                (self.R_vout_r_max, p_v_r_d_ < p_ar_pul_),
                (self.R_vout_r_min, p_v_r_d_ >= p_ar_pul_))
        elif self.valvelaw == 'pwlin_time':
            R_vin_l_ = sp.Piecewise(
                (self.R_vin_l_min,
                 sp.Or(self.t_ < self.t_ed, self.t_ >= self.t_es)),
                (self.R_vin_l_max,
                 sp.And(self.t_ >= self.t_ed, self.t_ < self.t_es)))
            R_vin_r_ = sp.Piecewise(
                (self.R_vin_r_min,
                 sp.Or(self.t_ < self.t_ed, self.t_ >= self.t_es)),
                (self.R_vin_r_max,
                 sp.And(self.t_ >= self.t_ed, self.t_ < self.t_es)))
            R_vout_l_ = sp.Piecewise(
                (self.R_vout_l_max,
                 sp.Or(self.t_ < self.t_ed, self.t_ >= self.t_es)),
                (self.R_vout_l_min,
                 sp.And(self.t_ >= self.t_ed, self.t_ < self.t_es)))
            R_vout_r_ = sp.Piecewise(
                (self.R_vout_r_max,
                 sp.Or(self.t_ < self.t_ed, self.t_ >= self.t_es)),
                (self.R_vout_r_min,
                 sp.And(self.t_ >= self.t_ed, self.t_ < self.t_es)))
        elif self.valvelaw == 'smooth_pres':
            R_vin_l_ = 0.5 * (self.R_vin_l_max - self.R_vin_l_min) * (sp.tanh(
                (p_v_l_ - p_at_l_d_) / self.epsvalve) + 1.) + self.R_vin_l_min
            R_vin_r_ = 0.5 * (self.R_vin_r_max - self.R_vin_r_min) * (sp.tanh(
                (p_v_r_ - p_at_r_d_) / self.epsvalve) + 1.) + self.R_vin_r_min
            R_vout_l_ = 0.5 * (self.R_vout_l_max -
                               self.R_vout_l_min) * (sp.tanh(
                                   (p_ar_sys_ - p_v_l_d_) / self.epsvalve) +
                                                     1.) + self.R_vout_l_min
            R_vout_r_ = 0.5 * (self.R_vout_r_max -
                               self.R_vout_r_min) * (sp.tanh(
                                   (p_ar_pul_ - p_v_r_d_) / self.epsvalve) +
                                                     1.) + self.R_vout_r_min
        else:
            raise NameError("Unknown valve law!")

        return R_vin_l_, R_vin_r_, R_vout_l_, R_vout_r_
Exemplo n.º 16
0
def test_PiecewiseTPolyMassAction__sympy():
    import sympy as sp
    tp1 = TPoly([0, 10, 0.1])
    tp2 = TPoly([273.15, 37.315, -0.1])
    pwp = PiecewiseTPolyMassAction.from_polynomials([(0, 273.15),
                                                     (273.15, 373.15)],
                                                    [tp1, tp2])
    T = sp.Symbol('T')
    Reaction({'A': 2, 'B': 1}, {'C': 1}, pwp, {'B': 1})
    res1 = pwp({'A': 11, 'B': 13, 'temperature': T}, backend=sp)
    ref1 = 11**2 * 13 * sp.Piecewise(
        (10 + 0.1 * T, sp.And(0 <= T, T <= 273.15)),
        (37.315 - 0.1 * (T - 273.15), sp.And(273.15 <= T, T <= 373.15)))
    assert res1 == ref1
Exemplo n.º 17
0
def VOF(j: ps.field.Field, v: ps.field.Field, ρ: ps.field.Field):
    """Volume-of-fluid discretization of advection

    Args:
        j: the staggered field to write the fluxes to. Should have a D2Q9/D3Q27 stencil. Other stencils work too, but
           incur a small error (D2Q5/D3Q7: v^2, D3Q19: v^3).
        v: the flow velocity field
        ρ: the quantity to advect
    """
    assert ps.FieldType.is_staggered(j)

    fluxes = [[] for i in range(j.index_shape[0])]

    v0 = v.center_vector
    for d, neighbor in enumerate(j.staggered_stencil):
        c = ps.stencil.direction_string_to_offset(neighbor)
        v1 = v.neighbor_vector(c)

        # going out
        cond = sp.And(
            *[sp.Or(c[i] * v0[i] > 0, c[i] == 0) for i in range(len(v0))])
        overlap1 = [1 - sp.Abs(v0[i]) for i in range(len(v0))]
        overlap2 = [c[i] * v0[i] for i in range(len(v0))]
        overlap = sp.Mul(*[(overlap1[i] if c[i] == 0 else overlap2[i])
                           for i in range(len(v0))])
        fluxes[d].append(ρ.center_vector * overlap * sp.Piecewise((1, cond),
                                                                  (0, True)))

        # coming in
        cond = sp.And(
            *[sp.Or(c[i] * v1[i] < 0, c[i] == 0) for i in range(len(v1))])
        overlap1 = [1 - sp.Abs(v1[i]) for i in range(len(v1))]
        overlap2 = [v1[i] for i in range(len(v1))]
        overlap = sp.Mul(*[(overlap1[i] if c[i] == 0 else overlap2[i])
                           for i in range(len(v1))])
        sign = (c == 1).sum() % 2 * 2 - 1
        fluxes[d].append(sign * ρ.neighbor_vector(c) * overlap * sp.Piecewise(
            (1, cond), (0, True)))

    for i, ff in enumerate(fluxes):
        fluxes[i] = ff[0]
        for f in ff[1:]:
            fluxes[i] += f

    assignments = []
    for i, d in enumerate(j.staggered_stencil):
        for lhs, rhs in zip(
                j.staggered_vector_access(d).values(), fluxes[i].values()):
            assignments.append(ps.Assignment(lhs, rhs))
    return assignments
Exemplo n.º 18
0
def test_PiecewiseTPolyMassAction__sympy():
    import sympy as sp
    tp1 = TPoly([10, 0.1])
    tp2 = ShiftedTPoly([273.15, 37.315, -0.1])
    pwp = MassAction(TPiecewise([0, tp1, 273.15, tp2, 373.15]))
    T = sp.Symbol('T')
    r = Reaction({'A': 2, 'B': 1}, {'C': 1}, inact_reac={'B': 1})
    res1 = pwp({'A': 11, 'B': 13, 'temperature': T}, backend=sp, reaction=r)
    ref1 = 11**2 * 13 * sp.Piecewise(
        (10+0.1*T, sp.And(0 <= T, T <= 273.15)),
        (37.315 - 0.1*(T-273.15), sp.And(273.15 <= T, T <= 373.15)),
        (sp.Symbol('NAN'), True)
    )
    assert res1 == ref1
Exemplo n.º 19
0
def expr_defined_by_limit(func, row_num, col_num, state, obsNum_finite, expr, row, col, NOT, SECOND=False, state2='A', NOT2=False, obsNum_finite2 = 0):
    if row > 0:
        c = '{}_{}_{}_{}'.format(row - 1, col, obsNum_finite, state)
        c = sympy.symbols(c)
        if NOT:
            c = ~c
        if SECOND:
            c2 = '{}_{}_{}_{}'.format(row - 1, col, obsNum_finite2, state2)
            c2 = sympy.symbols(c2)
            if NOT2:
                c2 = ~c2
            c = sympy.And(c,c2)
        expr = func(expr, c)
    if row < row_num - 1:
        c = '{}_{}_{}_{}'.format(row + 1, col, obsNum_finite, state)
        c = sympy.symbols(c)
        if NOT:
            c = ~c
        if SECOND:
            c2 = '{}_{}_{}_{}'.format(row + 1, col, obsNum_finite2, state2)
            c2 = sympy.symbols(c2)
            if NOT2:
                c2 = ~c2
            c = sympy.And(c,c2)
        expr = func(expr, c)
    if col > 0:
        c = '{}_{}_{}_{}'.format(row, col - 1, obsNum_finite, state)
        c = sympy.symbols(c)
        if NOT:
            c = ~c
        if SECOND:
            c2 = '{}_{}_{}_{}'.format(row, col - 1, obsNum_finite2, state2)
            c2 = sympy.symbols(c2)
            if NOT2:
                c2 = ~c2
            c = sympy.And(c,c2)
        expr = func(expr, c)
    if col < col_num - 1:
        c = '{}_{}_{}_{}'.format(row, col + 1, obsNum_finite, state)
        c = sympy.symbols(c)
        if NOT:
            c = ~c
        if SECOND:
            c2 = '{}_{}_{}_{}'.format(row, col + 1, obsNum_finite2, state2)
            c2 = sympy.symbols(c2)
            if NOT2:
                c2 = ~c2
            c = sympy.And(c, c2)
        expr = func(expr, c)
    return expr
Exemplo n.º 20
0
    def valvelaw(self, p, popen, Rmin, Rmax, vparams, topen, tclose):

        if vparams[
                0] == 'pwlin_pres':  # piecewise linear with resistance depending on pressure difference
            R = sp.Piecewise((Rmax, p < popen), (Rmin, p >= popen))
            vl = (popen - p) / R
        elif vparams[
                0] == 'pwlin_time':  # piecewise linear with resistance depending on timing
            if topen > tclose:
                R = sp.Piecewise(
                    (Rmax, sp.And(self.t_ < topen, self.t_ >= tclose)),
                    (Rmin, sp.Or(self.t_ >= topen, self.t_ < tclose)))
            else:
                R = sp.Piecewise(
                    (Rmax, sp.Or(self.t_ < topen, self.t_ >= tclose)),
                    (Rmin, sp.And(self.t_ >= topen, self.t_ < tclose)))
            vl = (popen - p) / R
        elif vparams[0] == 'smooth_pres_resistance':  # smooth resistance value
            R = 0.5 * (Rmax - Rmin) * (sp.tanh(
                (popen - p) / vparams[-1]) + 1.) + Rmin
            vl = (popen - p) / R
        elif vparams[0] == 'smooth_pres_momentum':  # smooth q(p) relationship
            # interpolation by cubic spline in epsilon interval
            p0 = (popen - vparams[-1] / 2. - popen) / Rmax
            p1 = (popen + vparams[-1] / 2. - popen) / Rmin
            m0 = 1. / Rmax
            m1 = 1. / Rmin
            s = (p - (popen - vparams[-1] / 2.)) / vparams[-1]
            # spline ansatz functions
            h00 = 2. * s**3. - 3 * s**2. + 1.
            h01 = -2. * s**3. + 3 * s**2.
            h10 = s**3. - 2. * s**2. + s
            h11 = s**3. - s**2.
            # spline
            c = h00 * p0 + h10 * m0 * vparams[
                -1] + h01 * p1 + h11 * m1 * vparams[-1]
            vl = sp.Piecewise(
                ((popen - p) / Rmax, p < popen - vparams[-1] / 2),
                (-c,
                 sp.And(p >= popen - vparams[-1] / 2.,
                        p < popen + vparams[-1] / 2.)),
                ((popen - p) / Rmin, p >= popen + vparams[-1] / 2.))
        elif vparams[0] == 'pw_pres_regurg':
            vl = sp.Piecewise(
                (vparams[1] * vparams[2] * sp.sqrt(popen - p), p < popen),
                ((popen - p) / Rmin, p >= popen))
        else:
            raise NameError("Unknown valve law %s!" % (vparams[0]))

        return vl, 1. / sp.diff(vl, popen)
Exemplo n.º 21
0
def test_create_Piecewise__nan_fallback__sympy():
    import sympy as sp

    TPw = create_Piecewise("Tmpr", nan_fallback=True)
    pw = TPw([0, 42, 10, 43, 20])
    x = sp.Symbol("x")
    res = pw({"Tmpr": x}, backend=sp)
    assert isinstance(res, sp.Piecewise)
    assert res.args[0][0] == 42
    assert res.args[0][1] == sp.And(0 <= x, x <= 10)
    assert res.args[1][0] == 43
    assert res.args[1][1] == sp.And(10 <= x, x <= 20)
    assert res.args[2][0].name.lower() == "nan"
    assert res.args[2][1] == True  # noqa
Exemplo n.º 22
0
    def _encode_leaf_to_z(self, leaves, inputs, attributions):
        """Each leaf entails one and only one feature usage mask."""
        n_inputs = inputs.shape[0]

        formulas = []
        for leaf in leaves:
            relevant = {i for i, _ in leaf.conds}
            cond = sympy.And(*[inputs[i, value] for i, value in leaf.conds])
            mask = sympy.And(*[
                attributions[i, 1 if i in relevant else 0]
                for i in range(n_inputs)
            ])
            formulas.append(cond & mask)
        return to_cnf(sympy.Or(*formulas))
Exemplo n.º 23
0
def quadratic_denom_rule(integral):
    integrand, symbol = integral
    a = sympy.Wild('a', exclude=[symbol])
    b = sympy.Wild('b', exclude=[symbol])
    c = sympy.Wild('c', exclude=[symbol])
    match = integrand.match(a / (b * symbol ** 2 + c))

    if not match:
        return

    a, b, c = match[a], match[b], match[c]
    return PiecewiseRule([(ArctanRule(a, b, c, integrand, symbol), sympy.Gt(c / b, 0)),
                          (ArccothRule(a, b, c, integrand, symbol), sympy.And(sympy.Gt(symbol ** 2, -c / b), sympy.Lt(c / b, 0))),
                          (ArctanhRule(a, b, c, integrand, symbol), sympy.And(sympy.Lt(symbol ** 2, -c / b), sympy.Lt(c / b, 0))),
    ], integrand, symbol)
Exemplo n.º 24
0
def test_create_Piecewise_Poly__sympy():
    import sympy as sp
    Poly = create_Poly('Tmpr')
    p1 = Poly([1, 0.1])
    p2 = Poly([3, -.1])

    TPw = create_Piecewise('Tmpr')
    pw = TPw([0, p1, 10, p2, 20])
    x = sp.Symbol('x')
    res = pw({'Tmpr': x}, backend=sp)
    assert isinstance(res, sp.Piecewise)
    assert res.args[0][0] == 1 + 0.1 * x
    assert res.args[0][1] == sp.And(0 <= x, x <= 10)
    assert res.args[1][0] == 3 - 0.1 * x
    assert res.args[1][1] == sp.And(10 <= x, x <= 20)
Exemplo n.º 25
0
def test_PiecewiseTPolyMassAction__sympy():
    import sympy as sp

    tp1 = TPoly([10, 0.1])
    tp2 = ShiftedTPoly([273.15, 37.315, -0.1])
    pwp = MassAction(TPiecewise([0, tp1, 273.15, tp2, 373.15]))
    T = sp.Symbol("T")
    r = Reaction({"A": 2, "B": 1}, {"C": 1}, inact_reac={"B": 1})
    res1 = pwp({"A": 11, "B": 13, "temperature": T}, backend=sp, reaction=r)
    ref1 = (11**2 * 13 * sp.Piecewise(
        (10 + 0.1 * T, sp.And(0 <= T, T <= 273.15)),
        (37.315 - 0.1 * (T - 273.15), sp.And(273.15 <= T, T <= 373.15)),
        (sp.Symbol("NAN"), True),
    ))
    assert res1 == ref1
Exemplo n.º 26
0
def is_H(undefined_state, row_num, col_num, police_num, medic_num, num_of_observations):
    row, col, obsNum = undefined_state.split(sep='_')
    row, col, obsNum = int(row), int(col), int(obsNum)
    if obsNum == 0:
        expr = '{}_{}_{}_H'.format(row, col, obsNum + 1)
        expr = sympy.symbols(expr)
        if medic_num > 0:
            temp = '{}_{}_{}_I'.format(row, col, obsNum + 1)
            temp = sympy.symbols(temp)
            expr = sympy.Or(expr, temp)
        return expr
    else:
        expr1, expr2, expr3, expr4, expr5 = 0, 0, 0, 0, 0
        if obsNum >= 3:
            expr1 = '{}_{}_{}_S'.format(row, col, obsNum - 3)
            expr1 = sympy.symbols(expr1)
            temp = '{}_{}_{}_S'.format(row, col, obsNum - 2)
            temp = sympy.symbols(temp)
            expr1 = sympy.And(expr1, temp)
            temp1 = '{}_{}_{}_S'.format(row, col, obsNum - 1)
            temp1 = sympy.symbols(temp1)
            expr1 = sympy.And(expr1, temp1)
        if medic_num > 0 and obsNum + 1 < num_of_observations:
            expr2 = '{}_{}_{}_I'.format(row, col, obsNum + 1)
            expr2 = sympy.symbols(expr2)
            temp = '{}_{}_{}_S'.format(row, col, obsNum - 1)
            temp = sympy.symbols(temp)
            if police_num > 0:
                temp1 = '{}_{}_{}_Q'.format(row, col, obsNum - 1)
                temp1 = sympy.symbols(temp1)
                temp = sympy.Or(temp, temp1)
            expr2 = sympy.And(expr2, temp)
        if medic_num == 0:
            expr3 = '{}_{}_{}_H'.format(row, col, obsNum - 1)
            expr3 = sympy.symbols(expr3)
            expr3 = expr_defined_by_limit(sympy.And, row_num, col_num, 'S', obsNum - 1, expr3, row, col, True)
        if police_num > 0:
            if obsNum > 2:
                expr4 = '{}_{}_{}_Q'.format(row, col, obsNum - 1)
                expr4 = sympy.symbols(expr4)
                temp = '{}_{}_{}_Q'.format(row, col, obsNum - 2)
                temp = sympy.symbols(temp)
                expr4 = sympy.And(expr4, temp)
                expr5 = '{}_{}_{}_Q'.format(row, col, obsNum - 3)
                expr5 = sympy.symbols(expr5)
                expr5 = sympy.And(~expr5, temp)
        expr = sympy.Or(expr5, expr4, expr3, expr2, expr1)
        return expr
Exemplo n.º 27
0
def guard(clusters):
    """
    Split Clusters containing conditional expressions into separate Clusters.
    """
    processed = []
    for c in clusters:
        # Group together consecutive expressions with same ConditionalDimensions
        for cds, g in groupby(c.exprs, key=lambda e: e.conditionals):
            if not cds:
                processed.append(c.rebuild(exprs=list(g)))
                continue

            # Create a guarded Cluster
            guards = {}
            for cd in cds:
                condition = guards.setdefault(cd.parent, [])
                if cd.condition is None:
                    condition.append(CondEq(cd.parent % cd.factor, 0))
                else:
                    condition.append(cd.condition)
            guards = {
                k: sympy.And(*v, evaluate=False)
                for k, v in guards.items()
            }
            processed.append(c.rebuild(exprs=list(g), guards=guards))

    return processed
Exemplo n.º 28
0
def guard(clusters):
    """
    Split Clusters containing conditional expressions into separate Clusters.
    """
    processed = []
    for c in clusters:
        # Group together consecutive expressions with same ConditionalDimensions
        for cds, g in groupby(c.exprs, key=lambda e: tuple(e.conditionals)):
            exprs = list(g)

            if not cds:
                processed.append(c.rebuild(exprs=exprs))
                continue

            # Chain together all conditions from all expressions in `c`
            guards = {}
            for cd in cds:
                condition = guards.setdefault(cd.parent, [])
                for e in exprs:
                    try:
                        condition.append(e.conditionals[cd])
                        break
                    except KeyError:
                        pass
            guards = {
                d: sympy.And(*v, evaluate=False)
                for d, v in guards.items()
            }

            # Construct a guarded Cluster
            processed.append(c.rebuild(exprs=exprs, guards=guards))

    return ClusterGroup(processed)
Exemplo n.º 29
0
def border_conditions(direction, field, ghost_layers=1):
    abs_direction = tuple(-e if e < 0 else e for e in direction)
    assert sum(abs_direction) == 1
    idx = abs_direction.index(1)
    val = direction[idx]

    loop_ctrs = [
        LoopOverCoordinate.get_loop_counter_symbol(i)
        for i in range(len(direction))
    ]
    loop_ctr = loop_ctrs[idx]

    gl = ghost_layers
    border_condition = sp.Eq(loop_ctr,
                             gl if val < 0 else field.shape[idx] - gl - 1)

    if ghost_layers == 0:
        return type_all_numbers(border_condition, loop_ctr.dtype)
    else:
        other_min = [sp.Ge(c, gl) for c in loop_ctrs if c != loop_ctr]
        other_max = [
            sp.Lt(c, field.shape[i] - gl) for i, c in enumerate(loop_ctrs)
            if c != loop_ctr
        ]
        result = sp.And(border_condition, *other_min, *other_max)
        return type_all_numbers(result, loop_ctr.dtype)
Exemplo n.º 30
0
 def test_nested_relational(self):
     expr = Expression(
         sympy.And(
             sympy.Or(sympy.Eq(self.a, self.b), sympy.Eq(self.c, self.d)),
             sympy.Or(sympy.Eq(self.e, self.f), sympy.Lt(self.g, self.f))))
     self.assertEqual(expr.rhs_cstr,
                      '(a == b || c == d) && (e == f || g < f)')