Exemplo n.º 1
0
 def handle_constraint(self, ctx: c.Context) -> bool:
     """Evaluate the constraint expression based on the current context."""
     return {
         "<": lambda lhs, rhs: lhs < rhs,
         "<=": lambda lhs, rhs: lhs <= rhs,
         "==": lambda lhs, rhs: lhs == rhs,
         ">=": lambda lhs, rhs: lhs >= rhs,
         ">": lambda lhs, rhs: lhs > rhs,
     }[self.op](ctx.get_val(self.lhs), ctx.get_val(self.rhs))
Exemplo n.º 2
0
    def test_context_init():
        """Test Context initializer."""
        c = Context(set(), {}, {})
        assert c.clocks == set()
        assert c.constants == {}
        assert c.initial_state == {}

        c = Context(set(["foo", "bar"]), {"x": 13, "y": -1}, {"z": 11})

        assert "foo" in c.clocks and "bar" in c.clocks
        assert c.constants["x"] == 13 and c.constants["y"] == -1
        assert c.initial_state["z"] == 11
Exemplo n.º 3
0
def compute_constraint(
    clock_to_delay: Dict[str, List[int]],
    exp: ClockConstraintExpression,
    variable_count: int,
    ctx: Context,
    add_epsilon: bool = False,
    skip_var_threshold: bool = False,
) -> Tuple[List[List[int]], List[int]]:
    """Construct a row of the Linear Program.

    The satisfiability of the constraints with variable thresholds depends on
    the current state. For this reason they should be omitted in
    semi-realizability checking for path segments considered while populating
    the DP table.

    Args:
        clock_to_delay: Dictionary of list of ints. clock_to_delay['x'] gives
            a list of delay variables for the locations visited since the last
            reset of clock 'x'.
        exp: ClockConstraintExpression
        variable_count: Int for determining the row size.
        ctx: Context used to determine the valuations of variables.
        add_epsilon: Whether to treat '<=' as '<' by adding an epsilon value to
            the threshold.
        skip_var_threshold: Whether to skip constraints of form clock < variable
    """

    if ctx.is_variable(exp.threshold) and skip_var_threshold:
        return [], []

    A_row = [[0 for _ in range(variable_count)]]
    for delay_var in clock_to_delay[exp.clocks[0]]:
        A_row[0][delay_var] = 1

    if len(exp.clocks) == 2:  # clock difference
        for delay_var in clock_to_delay[exp.clocks[1]]:
            A_row[0][delay_var] -= 1

    # TODO: get value from context
    B_row = [ctx.get_val(exp.threshold)]
    if exp.operator == ">":
        A_row[0] = [x * -1 for x in A_row[0]]
        B_row[0] = -1 * B_row[0]

    if add_epsilon and exp.equality == False:  # Inequality: Add epsilon.
        B_row[0] -= EPS

    if exp.operator == "=":
        A_row.append([x * -1 for x in A_row[0]])
        B_row.append(-B_row[0])

    return A_row, B_row
Exemplo n.º 4
0
    def test_mcontext_to_mutable():
        """Test to_MutableContext method of Context."""
        c = Context(set(), {"foo": 3}, {
            "bar": 4,
        })
        mc = c.to_MutableContext()

        assert mc.clocks == set()
        assert mc.get_val("foo") == 3
        assert mc.get_val("bar") == 4

        mc.set_val("bar", 1)

        assert mc.get_val("bar") == 1
        assert c.get_val("foo") == 3
        assert c.get_val("bar") == 4
Exemplo n.º 5
0
 def parse_expr(cls, string: str, ctx: c.Context) -> "ConstraintExpression":
     """Parse an expression string and generate an Expression."""
     lhs, _, rhs = cls.tokenize(string, "<>=")
     for x in lhs.split("-") + rhs.split("-"):
         if ctx.is_clock(x.strip()):
             return ClockConstraintExpression(string, ctx)
     return cls(string, ctx)
Exemplo n.º 6
0
    def __init__(self, string: str, ctx: c.Context) -> None:
        """Construct a clock constraint."""
        super().__init__(string, ctx, "<>=")
        self._threshold_side: Union[Literal["left"], Literal["right"]]
        self.clocks: List[str]

        # Determine which side the threshold is.
        if (ctx.is_constant(self.lhs) or ctx.is_literal(self.lhs)
                or ctx.is_variable(self.lhs)):
            self._threshold_side = "left"
            self.clocks = [c.strip() for c in self.rhs.split("-")]
        else:
            self._threshold_side = "right"
            self.clocks = [c.strip() for c in self.lhs.split("-")]

        self.operator = self.op[0]
        self.equality = len(self.op) == 2
Exemplo n.º 7
0
    def test_context_is_literal():
        """Test is_literal method."""
        c = Context(set(), {}, {})
        assert c.is_literal("9")

        c = Context(set([]), {}, {"foo": 4})
        assert c.is_literal("hello") == False
Exemplo n.º 8
0
    def test_context_is_variable():
        """Test is_variable method."""
        c = Context(set(), {}, {})
        assert c.is_variable("notvar") == False

        c = Context(set([]), {}, {"foo": 4})
        assert c.is_variable("foo")
Exemplo n.º 9
0
    def test_context_is_constant():
        """Test is_constant method."""
        c = Context(set(), {}, {})
        assert c.is_constant("notconstant") == False

        c = Context(set([]), {"foo": 4}, {})
        assert c.is_constant("foo")
Exemplo n.º 10
0
    def from_element(cls: Type["NTA"], et) -> "NTA":
        """Construct NTA from Element, and return it."""
        kw = {}
        kw["declaration"] = Declaration.from_element(et.find("declaration"))

        if kw["declaration"] is None or kw["declaration"].text is None:
            kw["context"] = Context.parse_context(None)
        else:
            kw["context"] = Context.parse_context(kw["declaration"].text)
        kw["templates"] = [
            te.Template.from_element(template, kw["context"])
            for template in et.iterchildren("template")
        ]
        kw["system"] = SystemDeclaration.from_element(et.find("system"))
        if et.find("queries") is None:
            kw["queries"] = []
        else:
            kw["queries"] = [
                Query.from_element(query)
                for query in et.find("queries").iter("query")
            ]
        return cls(**kw)
Exemplo n.º 11
0
 def ctx(cls):
     return Context(
         {"c1", "c2", "c"},
         {
             "x": -10,
             "y": 0,
             "constant3": 3
         },
         {
             "i": -1,
             "j": 4,
             "k": 10
         },
     )
Exemplo n.º 12
0
 def test_nta_init():
     """Test NTA()."""
     nta = NTA(
         declaration=Declaration("foo"),
         templates=[],
         system=SystemDeclaration("bar"),
         queries=[],
         context=Context.empty()
     )
     assert nta.declaration.text == "foo"
     assert nta.system.text == "bar"
     assert nta.templates == []
     assert nta.queries == []
     assert nta._associated_file == ""
     assert nta._doctype == ""
Exemplo n.º 13
0
    def test_context_parse_context():
        """Test parse_context method."""
        c = Context.parse_context("""
const int x, y = 10; // comment here.
int a = 11, b;
clock c1, c2,c3;
            """)
        print(c.clocks, c.constants, c.initial_state, sep="\n")
        assert c.is_constant("x") and c.get_val("x") == 0
        assert c.is_constant("y") and c.get_val("y") == 10

        assert c.is_variable("a") and c.get_val("a") == 11
        assert c.is_variable("b") and c.get_val("b") == 0

        assert c.is_clock("c1") and c.is_clock("c2") and c.is_clock("c3")
        assert not c.is_clock("c4") and not c.is_clock("x") and not c.is_clock(
            "a")
Exemplo n.º 14
0
 def test_context_get_val():
     """Test get_val method."""
     c = Context(set(), {"foo": 3}, {"bar": 4})
     c.get_val("foo") == 3
     c.get_val("bar") == 4
     c.get_val("15") == 15
Exemplo n.º 15
0
    def test_context_is_clock():
        """Test is_clock method."""
        c = Context(set(), {}, {})
        assert c.is_clock("notclock") == False

        c = Context(set(["foo"]), {}, {})
        assert c.is_clock("foo")

        c = Context(set(["foo", "bar"]), {}, {})
        assert c.is_clock("foo")
        assert c.is_clock("bar")

        c = Context(set(), {"foo": 3}, {"bar": 4})
        assert c.is_clock("foo") == False
        assert c.is_clock("bar") == False
Exemplo n.º 16
0
 def parse_expr(cls, string: str, ctx: c.Context) -> "UpdateExpression":
     """Construct UpdateExpression with some polymorphism."""
     lhs, _, _ = cls.tokenize(string)
     if ctx.is_clock(lhs):
         return ClockResetExpression(string, ctx)
     return cls(string, ctx)