Exemplo n.º 1
0
 def from_oef_constraint_expr(
     cls, oef_constraint_expr: OEFConstraintExpr
 ) -> ConstraintExpr:
     """From our query to OEF query."""
     if isinstance(oef_constraint_expr, OEFAnd):
         return And(
             [
                 cls.from_oef_constraint_expr(c)
                 for c in oef_constraint_expr.constraints
             ]
         )
     elif isinstance(oef_constraint_expr, OEFOr):
         return Or(
             [
                 cls.from_oef_constraint_expr(c)
                 for c in oef_constraint_expr.constraints
             ]
         )
     elif isinstance(oef_constraint_expr, OEFNot):
         return Not(cls.from_oef_constraint_expr(oef_constraint_expr.constraint))
     elif isinstance(oef_constraint_expr, OEFConstraint):
         constraint_type = cls.from_oef_constraint_type(
             oef_constraint_expr.constraint
         )
         return Constraint(oef_constraint_expr.attribute_name, constraint_type)
     else:
         raise ValueError("OEF Constraint not supported.")
Exemplo n.º 2
0
def test_constraints_expressions():
    """Test constraint expressions: And, Or, Not."""
    expression = And([
        ConstraintType(ConstraintTypes.EQUAL, 12),
        ConstraintType(ConstraintTypes.EQUAL, 12),
    ])
    expression.check_validity()
    assert expression.check(12)
    expression.is_valid(Attribute("test", int, True))

    expression = Or([
        ConstraintType(ConstraintTypes.EQUAL, 12),
        ConstraintType(ConstraintTypes.EQUAL, 13),
    ])
    expression.check_validity()
    assert expression.check(12)

    expression.is_valid(Attribute("test", int, True))

    expression = Not(
        And([
            ConstraintType(ConstraintTypes.EQUAL, 12),
            ConstraintType(ConstraintTypes.EQUAL, 12),
        ]))
    expression.check_validity()
    assert expression.check(13)
    expression.is_valid(Attribute("test", int, True))
Exemplo n.º 3
0
 def test_or_check(self):
     """Test the or().check function."""
     attribute_foo = Attribute("foo", int, True, "a foo attribute.")
     attribute_bar = Attribute("bar", str, True, "a bar attribute.")
     data_model_foobar = DataModel("foobar", [attribute_foo, attribute_bar],
                                   "A foobar data model.")
     description_foobar = Description({
         "foo": 1,
         "bar": "baz"
     },
                                      data_model=data_model_foobar)
     constraint = Or([
         (Constraint("foo", ConstraintType("==", 1))),
         (Constraint("bar", ConstraintType("==", "baz"))),
     ])
     assert constraint.check(description_foobar)
Exemplo n.º 4
0
    def test_query(self):
        """Test that the translation for the Query class works."""
        attribute_foo = Attribute("foo", int, True, "a foo attribute.")
        attribute_bar = Attribute("bar", str, True, "a bar attribute.")
        data_model_foobar = DataModel(
            "foobar", [attribute_foo, attribute_bar], "A foobar data model."
        )

        query = Query(
            [
                And(
                    [
                        Or(
                            [
                                Not(Constraint("foo", ConstraintType("==", 1))),
                                Not(Constraint("bar", ConstraintType("==", "baz"))),
                            ]
                        ),
                        Constraint("foo", ConstraintType("<", 2)),
                    ]
                )
            ],
            data_model_foobar,
        )

        oef_query = OEFObjectTranslator.to_oef_query(query)
        expected_query = OEFObjectTranslator.from_oef_query(oef_query)
        actual_query = query
        assert expected_query == actual_query
Exemplo n.º 5
0
 def test_query_check(self):
     """Test that the query.check() method works."""
     attribute_foo = Attribute("foo", int, True, "a foo attribute.")
     attribute_bar = Attribute("bar", str, True, "a bar attribute.")
     data_model_foobar = DataModel(
         "foobar", [attribute_foo, attribute_bar], "A foobar data model."
     )
     description_foobar = Description(
         {"foo": 1, "bar": "baz"}, data_model=data_model_foobar
     )
     query = Query(
         [
             And(
                 [
                     Or(
                         [
                             Not(Constraint("foo", ConstraintType("==", 1))),
                             Not(Constraint("bar", ConstraintType("==", "baz"))),
                         ]
                     ),
                     Constraint("foo", ConstraintType("<", 2)),
                 ]
             )
         ],
         data_model_foobar,
     )
     assert not query.check(description=description_foobar)
Exemplo n.º 6
0
    def test_pickable_query(self):
        """Test that an istance of the Query class is pickable."""
        attribute_foo = Attribute("foo", int, True, "a foo attribute.")
        attribute_bar = Attribute("bar", str, True, "a bar attribute.")
        data_model_foobar = DataModel(
            "foobar", [attribute_foo, attribute_bar], "A foobar data model."
        )

        query = Query(
            [
                And(
                    [
                        Or(
                            [
                                Not(Constraint("foo", ConstraintType("==", 1))),
                                Not(Constraint("bar", ConstraintType("==", "baz"))),
                            ]
                        ),
                        Constraint("foo", ConstraintType("<", 2)),
                    ]
                )
            ],
            data_model_foobar,
        )
        try:
            pickle.dumps(query)
        except Exception:
            pytest.fail("Error during pickling.")
Exemplo n.º 7
0
def test_constraints_or():
    """Test Or."""
    or_expression = Or([
        Constraint("number", ConstraintType(ConstraintTypes.EQUAL, 12)),
        Constraint("number", ConstraintType(ConstraintTypes.EQUAL, 13)),
    ])
    or_expression.check_validity()
    assert or_expression.check(Description({"number": 12}))
    assert or_expression.is_valid(
        DataModel("some_name", [Attribute("number", int, True)]))
    or_expression_pb = or_expression.encode()
    actual_or_expression = Or.decode(or_expression_pb)
    assert actual_or_expression == or_expression
Exemplo n.º 8
0
def test_constraints_expression():
    """Test constraint expressions: And, Or, Not, Constraint."""
    and_expression = And([
        Constraint("number", ConstraintType(ConstraintTypes.LESS_THAN, 15)),
        Constraint("number", ConstraintType(ConstraintTypes.GREATER_THAN, 10)),
    ])
    and_expression.check_validity()
    assert and_expression.check(Description({"number": 12}))
    assert and_expression.is_valid(
        DataModel("some_name", [Attribute("number", int, True)]))
    and_expression_pb = ConstraintExpr._encode(and_expression)
    actual_and_expression = ConstraintExpr._decode(and_expression_pb)
    assert actual_and_expression == and_expression

    or_expression = Or([
        Constraint("number", ConstraintType(ConstraintTypes.EQUAL, 12)),
        Constraint("number", ConstraintType(ConstraintTypes.EQUAL, 13)),
    ])
    or_expression.check_validity()
    assert or_expression.check(Description({"number": 12}))
    assert or_expression.is_valid(
        DataModel("some_name", [Attribute("number", int, True)]))
    or_expression_pb = ConstraintExpr._encode(or_expression)
    actual_or_expression = ConstraintExpr._decode(or_expression_pb)
    assert actual_or_expression == or_expression

    not_expression = Not(
        And([
            Constraint("number", ConstraintType(ConstraintTypes.EQUAL, 12)),
            Constraint("number", ConstraintType(ConstraintTypes.EQUAL, 12)),
        ]))
    not_expression.check_validity()
    assert not_expression.check(Description({"number": 13}))
    assert not_expression.is_valid(
        DataModel("some_name", [Attribute("number", int, True)]))
    not_expression_pb = ConstraintExpr._encode(not_expression)
    actual_not_expression = ConstraintExpr._decode(not_expression_pb)
    assert actual_not_expression == not_expression

    # constraint
    constraint_expression = Constraint("author",
                                       ConstraintType("==", "Stephen King"))
    constraint_expression.check_validity()
    assert constraint_expression.check(Description({"author": "Stephen King"}))
    assert constraint_expression.is_valid(
        DataModel("some_name", [Attribute("author", str, True)]))
    constraint_expression_pb = ConstraintExpr._encode(constraint_expression)
    actual_constraint_expression = ConstraintExpr._decode(
        constraint_expression_pb)
    assert actual_constraint_expression == constraint_expression

    incorrect_expression = Location(1.1, 2.2)
    with pytest.raises(
            ValueError,
            match=
            f"Invalid expression type. Expected either of 'And', 'Or', 'Not', 'Constraint'. Found {type(incorrect_expression)}.",
    ):
        ConstraintExpr._encode(incorrect_expression)
Exemplo n.º 9
0
def build_goods_query(
    good_ids: List[str],
    currency_id: str,
    is_searching_for_sellers: bool,
    is_search_query: bool,
) -> Query:
    """
    Build buyer or seller search query.

    Specifically, build the search query
        - to look for sellers if the agent is a buyer, or
        - to look for buyers if the agent is a seller.

    In particular, if the agent is a buyer and the demanded good ids are {'tac_good_0', 'tac_good_2', 'tac_good_3'}, the resulting constraint expression is:

        tac_good_0 >= 1 OR tac_good_2 >= 1 OR tac_good_3 >= 1

    That is, the OEF will return all the sellers that have at least one of the good in the query
    (assuming that the sellers are registered with the data model specified).

    :param good_ids: the list of good ids to put in the query
    :param currency_id: the currency used for pricing and transacting.
    :param is_searching_for_sellers: Boolean indicating whether the query is for sellers (supply) or buyers (demand).
    :param is_search_query: whether or not the query is used for search on OEF

    :return: the query
    """
    if is_search_query:
        # the OEF does not accept attribute names consisting of integers only
        good_ids = [PREFIX + good_id for good_id in good_ids]

    data_model = _build_goods_datamodel(good_ids=good_ids,
                                        is_supply=is_searching_for_sellers)
    constraints = [
        Constraint(good_id, ConstraintType(">=", 1)) for good_id in good_ids
    ]
    constraints.append(
        Constraint("currency_id", ConstraintType("==", currency_id)))
    constraint_expr = cast(List[ConstraintExpr], constraints)

    if len(good_ids) > 1:
        constraint_expr = [Or(constraint_expr)]

    query = Query(constraint_expr, model=data_model)
    return query