def setUp(self):
     node_label_def = [{
         'name': 'ap',
         'values': PowerSet({'p', 'q', 'r', 'x', 'a', 'b'})}]
     G = labeled_graphs.LabeledDiGraph(node_label_def)
     self.S_ap = labeled_graphs.States(G)
     G.states = self.S_ap
    def setUp(self):
        p = PowerSet({1, 2})
        node_labeling = [
            {
                'name': 'month',
                'values': ['Jan', 'Feb']
            },
            {
                'name': 'day',
                'values': ['Mon', 'Tue']
            },
            {
                'name': 'comb',
                'values': p,
                'setter': p.math_set
            }
        ]
        edge_labeling = node_labeling
        G = labeled_graphs.LabeledDiGraph(node_labeling, edge_labeling)

        G.states.add_from({1, 2})
        G.transitions.add(1, 2, month='Jan', day='Mon')

        assert_raises(Exception, G.transitions.add,
                      1, 2, {'month': 'Jan', 'day': 'abc'})

        # note how untyped keys can be set directly via assignment,
        # whereas check=False is needed for G.add_node
        G.node[1]['mont'] = 'Feb'
        assert(G.node[1] == {'mont':'Feb'})

        G[1][2][0]['day'] = 'Tue'
        assert(G[1][2][0] == {'month':'Jan', 'day':'Tue'})

        self.G = G
Пример #3
0
 def __init__(self):
     ap_labels = PowerSet()
     node_label_types = [{
         'name': 'ap',
         'values': ap_labels,
         'setter': ap_labels.math_set,
         'default': set()
     }]
     super(KripkeStructure, self).__init__(node_label_types)
     self.atomic_propositions = self.ap
     # dot formatting
     self._state_dot_label_format = {
         'ap': '',
         'type?label': '',
         'separator': r'\\n'
     }
     self.dot_node_shape = {'normal': 'rectangle'}
     self._state_dot_label_format = {
         'ap': '',
         'type?label': '',
         'separator': r'\\n'
     }
     self._transition_dot_label_format = {
         'type?label': ':',
         'separator': r'\\n'
     }
     self._transition_dot_mask = dict()
Пример #4
0
def ba_test():
    ba = trs.BA()

    aps = ['p']
    ba.atomic_propositions |= {'p'}
    assert ('p' in ba.atomic_propositions)
    assert (ba.atomic_propositions == MathSet(aps))
    assert (ba.alphabet == PowerSet(aps))

    ba.states.add_from({'q0', 'q1'})
    assert (set(ba.states) == {'q0', 'q1'})

    ba.states.initial.add('q0')
    assert (set(ba.states.initial) == {'q0'})

    ba.states.accepting.add('q1')
    assert (set(ba.states.accepting) == {'q1'})

    ba.transitions.add('q0', 'q1', letter={'p'})
    ba.transitions.add('q1', 'q1', letter={'p'})
    ba.transitions.add('q1', 'q0', letter=set())
    ba.transitions.add('q0', 'q0', letter=set())

    logger.debug(ba)
    ba.save('ba.pdf')
    return ba
Пример #5
0
    def __init__(
        self,
        deterministic=False,
        accepting_states_type=None,
        atomic_proposition_based=True,
        symbolic=False,
    ):
        """Initialize FiniteStateAutomaton.

        Additional keyword arguments are passed to L{LabeledDiGraph.__init__}.

        @param atomic_proposition_based: If False, then the alphabet
            is represented by a set.  If True, then the alphabet is
            represented by a powerset 2^AP.
        """
        self.atomic_proposition_based = atomic_proposition_based
        self.symbolic = symbolic

        # edge labeling
        if symbolic:
            alphabet = None  # no checks
        else:
            if atomic_proposition_based:
                alphabet = PowerSet([])
                self.atomic_propositions = alphabet.math_set
            else:
                alphabet = set()
        self.alphabet = alphabet

        edge_label_types = [{
            'name': 'letter',
            'values': alphabet,
            'setter': True
        }]
        super(FiniteStateAutomaton,
              self).__init__(edge_label_types=edge_label_types)
        # accepting states
        if accepting_states_type is None:
            self._accepting = SubSet(self.states)
            self._accepting_type = SubSet
        else:
            self._accepting = accepting_states_type(self)
            self._accepting_type = accepting_states_type
        self.states.accepting = self._accepting
        # used before label value
        self._transition_dot_label_format = {
            'letter': '',
            'type?label': '',
            'separator': '\n'
        }
        self._transition_dot_mask = dict()

        self.dot_node_shape = {'normal': 'circle', 'accepting': 'doublecircle'}
        self.default_export_fname = 'fsa'
        self.automaton_type = 'Finite State Automaton'
Пример #6
0
def powerset_test():
    s = [[1, 2], '3', {'a': 1}, 1]

    p = PowerSet(s)

    s2 = ['3', {'a': 1}, [1, 2], 1]
    q = PowerSet()
    q.math_set = MathSet(s2)

    assert (p.math_set == MathSet(s))
    assert (q.math_set == MathSet(s))
    assert (isinstance(q.math_set, MathSet))
    assert (p == q)

    q.math_set.add(6)

    # CAUTION: comparing p() and q() might yield False, due to ordering
    f = p + q
    assert (isinstance(f, PowerSet))
    assert (f.math_set._set == {1, '3', 6})
    assert (compare_lists(f.math_set._list, [[1, 2], {'a': 1}]))

    return s
def powerset_test():
    s = [[1, 2], "3", {"a": 1}, 1]

    p = PowerSet(s)

    s2 = ["3", {"a": 1}, [1, 2], 1]
    q = PowerSet()
    q.math_set = MathSet(s2)

    assert p.math_set == MathSet(s)
    assert q.math_set == MathSet(s)
    assert isinstance(q.math_set, MathSet)
    assert p == q

    q.math_set.add(6)

    # CAUTION: comparing p() and q() might yield False, due to ordering
    f = p + q
    assert isinstance(f, PowerSet)
    assert f.math_set._set == {1, "3", 6}
    assert compare_lists(f.math_set._list, [[1, 2], {"a": 1}])

    return s
Пример #8
0
 def __init__(self):
     ap_labels = PowerSet()
     node_label_types = [
         {'name': 'ap',
          'values': ap_labels,
          'setter': ap_labels.math_set,
          'default': set()}]
     super(LabeledGameGraph, self).__init__(node_label_types)
     self.atomic_propositions = self.ap
     # dot formatting
     self._state_dot_label_format = {
         'ap': '',
         'type?label': '',
         'separator': '\n'}
     self.dot_node_shape = {'normal': 'rectangle'}
Пример #9
0
def _construct_wfa(all_propositions, false_propositions):
    # Construct WFA for invariant spec
    # ! \wedge_{props \in false_propositions} \vee_{prop \in props} prop
    fa = WFA()
    fa.atomic_propositions.add_from(all_propositions)
    fa.states.add_from({"q0"})
    fa.states.initial.add("q0")
    fa.states.accepting.add("q0")

    transition_letters = set()
    for propositions in false_propositions:
        props_without_false = copy.deepcopy(fa.atomic_propositions)
        for prop in propositions:
            props_without_false.remove(prop)
        transition_letters |= set(PowerSet(props_without_false))

    for letter in transition_letters:
        fa.transitions.add("q0", "q0", letter=letter)
    return fa
Пример #10
0
ts.states.initial.add(baseState)

for transition in setOfTransitions:
    ts.transitions.add(transition.prevState, transition.nextState, 1)
ts.atomic_propositions.add("VALID")
ts.atomic_propositions.add("SAT")

for s in setOfStates:
    ts.states[s]["ap"] = set(s.labels)

# ts = synchronous_parallel([ts])

fa1 = WFA()
fa1.atomic_propositions.add_from(ts.atomic_propositions)
fa1.states.add_from({"q0"})
fa1.states.initial.add("q0")
fa1.states.accepting.add("q0")

ap_with_both = copy.deepcopy(fa1.atomic_propositions)
transition_letters = set(PowerSet(ap_with_both))
for letter in transition_letters:
    fa1.transitions.add("q0", "q0", letter=letter)

spec = PrioritizedSpecification()
spec.add_rule(fa1, priority=1, level=0)

(cost, state_path, product_path, wpa) = solve_mvp(ts, "SAT", spec)
print("Optimal cost: {}".format(cost))
print("State path: {}".format(state_path))
print("Product path: {}".format(product_path))
#wpa.plot()
Пример #11
0
    def __init__(self, env_actions=None, sys_actions=None):
        """Instantiate finite transition system.

        @param env_actions: environment (uncontrolled) actions,
            defined as C{edge_label_types} in L{LabeledDiGraph.__init__}

        @param sys_actions: system (controlled) actions, defined as
            C{edge_label_types} in L{LabeledDiGraph.__init__}
        """
        self._owner = 'sys'

        if env_actions is None:
            env_actions = [
                {'name': 'env_actions',
                 'values': MathSet(),
                 'setter': True}]
        if sys_actions is None:
            sys_actions = [
                {'name': 'sys_actions',
                 'values': MathSet(),
                 'setter': True}]
        # note: "sys_actions" used to be "actions"
        # in closed systems (old FTS)
        action_types = env_actions + sys_actions
        edge_label_types = action_types
        ap_labels = PowerSet()
        node_label_types = [
            {'name': 'ap',
             'values': ap_labels,
             'setter': ap_labels.math_set,
             'default': set()}]
        super(FiniteTransitionSystem, self).__init__(
            node_label_types, edge_label_types)
        # make them available also via an "actions" dicts
        # name, codomain, *rest = x
        actions = {x['name']: x['values'] for x in edge_label_types}
        if 'actions' in actions:
            msg = '"actions" cannot be used as an action type name,\n'
            msg += 'because if an attribute for this action type'
            msg += 'is requested,\n then it will conflict with '
            msg += 'the dict storing all action types.'
            raise ValueError(msg)
        self.actions = actions
        self.atomic_propositions = self.ap
        self.aps = self.atomic_propositions  # shortcut
        # action constraint used in synth.synthesize
        self.env_actions_must = 'xor'
        self.sys_actions_must = 'xor'
        # dot formatting
        self._state_dot_label_format = {
            'ap': '',
            'type?label': '',
            'separator': r'\\n'}
        self._transition_dot_label_format = {
            'sys_actions': 'sys',  # todo: '' if no env
            'env_actions': 'env',
            'type?label': ':',  # todo: '' if no env
            'separator': r'\\n'}
        self._transition_dot_mask = dict()
        self.dot_node_shape = {'normal': 'box'}  # todo: rectangle if no env
        self.default_export_fname = 'fts'
Пример #12
0
 def setUp(self):
     self.p = PowerSet({1, 2, 3})
     self.q_unhashable = PowerSet(MathSet([[1, 2], ["a", "b"]]))
     self.singleton = PowerSet(set([1]))
     self.empty = PowerSet()
Пример #13
0
def generate_trace(graph, override=False):
    # check if synthesis results already exist for the input graph. if so, return stored value
    if not override:
        if graph.base_state in synthesis_dictionary.keys():
            return synthesis_dictionary[graph.base_state]

    ts = WKS()
    ts.states.add_from(graph.states)
    ts.states.initial.add(graph.base_state)

    for transition in graph.transitions:
        ts.transitions.add(transition[0], transition[2], {"cost": 1})

    ts.atomic_propositions.add("VALID")
    ts.atomic_propositions.add("WRONG_PORT")
    ts.atomic_propositions.add("OVERFLOWED_PORT")
    ts.atomic_propositions.add("FINISH")

    for s in graph.states:
        ts.states[s]["ap"] = set(s.labels)

    fa0 = WFA()
    fa0.atomic_propositions.add_from(ts.atomic_propositions)
    fa0.states.add_from({"q0"})
    fa0.states.initial.add("q0")
    fa0.states.accepting.add("q0")

    ap_without_valid = copy.deepcopy(fa0.atomic_propositions)
    ap_without_valid.remove("VALID")
    valid = {"VALID"}

    for letter in PowerSet(ap_without_valid):  # union of everything with valid
        fa0.transitions.add("q0", "q0", letter=set(letter) | valid)

    fa1 = WFA()
    fa1.atomic_propositions.add_from(ts.atomic_propositions)
    fa1.states.add_from({"q0"})
    fa1.states.initial.add("q0")
    fa1.states.accepting.add("q0")

    ap_without_wrong_port = copy.deepcopy(fa1.atomic_propositions)
    ap_without_wrong_port.remove("WRONG_PORT")
    wrong_port = {"WRONG_PORT"}

    for letter in PowerSet(ap_without_wrong_port):
        fa1.transitions.add("q0", "q0", letter=letter)

    fa2 = WFA()
    fa2.atomic_propositions.add_from(ts.atomic_propositions)
    fa2.states.add_from({"q0"})
    fa2.states.initial.add("q0")
    fa2.states.accepting.add("q0")

    ap_without_port_overflow = copy.deepcopy(fa2.atomic_propositions)
    ap_without_port_overflow.remove("OVERFLOWED_PORT")

    for letter in PowerSet(ap_without_port_overflow):
        fa2.transitions.add("q0", "q0", letter=letter)

    spec = PrioritizedSpecification()
    spec.add_rule(fa0, priority=1, level=0)
    spec.add_rule(fa1, priority=1, level=1)
    spec.add_rule(fa2, priority=2, level=1)

    (cost, state_path, product_path, wpa) = solve_mvp(ts, "FINISH", spec)
    synthesis_dictionary[graph.base_state] = (cost, state_path, product_path, wpa)
    # print("Optimal cost: {}".format(cost))
    # print("State path: {}".format(state_path))
    # print("Product path: {}".format(product_path))
    return (cost, state_path, product_path, wpa)
def tulip_tests(graph):
    ts = WKS()
    ts.states.add_from(graph.states)
    ts.states.initial.add(graph.base_state)

    for transition in graph.transitions:
        ts.transitions.add(transition[0], transition[2], {"cost": 1})

    ts.atomic_propositions.add("VALID")
    ts.atomic_propositions.add("WRONG_PORT")
    ts.atomic_propositions.add("OVERFLOWED_PORT")
    ts.atomic_propositions.add("FINISH")

    for s in graph.states:
        ts.states[s]["ap"] = set(s.labels)

    fa0 = WFA()
    fa0.atomic_propositions.add_from(ts.atomic_propositions)
    fa0.states.add_from({"q0"})
    fa0.states.initial.add("q0")
    fa0.states.accepting.add("q0")

    ap_without_valid = copy.deepcopy(fa0.atomic_propositions)
    ap_without_valid.remove("VALID")
    valid = {"VALID"}

    for letter in PowerSet(ap_without_valid):  # union of everything with valid
        fa0.transitions.add("q0", "q0", letter=set(letter) | valid)

    fa1 = WFA()
    fa1.atomic_propositions.add_from(ts.atomic_propositions)
    fa1.states.add_from({"q0"})
    fa1.states.initial.add("q0")
    fa1.states.accepting.add("q0")

    ap_without_wrong_port = copy.deepcopy(fa1.atomic_propositions)
    ap_without_wrong_port.remove("WRONG_PORT")
    wrong_port = {"WRONG_PORT"}

    for letter in PowerSet(ap_without_wrong_port):
        fa1.transitions.add("q0", "q0", letter=letter)

    fa2 = WFA()
    fa2.atomic_propositions.add_from(ts.atomic_propositions)
    fa2.states.add_from({"q0"})
    fa2.states.initial.add("q0")
    fa2.states.accepting.add("q0")

    ap_without_port_overflow = copy.deepcopy(fa2.atomic_propositions)
    ap_without_port_overflow.remove("OVERFLOWED_PORT")

    for letter in PowerSet(ap_without_port_overflow):
        fa2.transitions.add("q0", "q0", letter=letter)

    spec = PrioritizedSpecification()
    spec.add_rule(fa0, priority=1, level=0)
    spec.add_rule(fa1, priority=1, level=1)
    spec.add_rule(fa2, priority=2, level=1)

    (cost, state_path, product_path, wpa) = solve_mvp(ts, "FINISH", spec)

    print("Optimal cost: {}".format(cost))
    print("State path: {}".format(state_path))
    print("Product path: {}".format(product_path))