Пример #1
0
    def test_on_cfp(self, local):
        """
        Test that an agent can send a CFP to another agent, with different types of queries.
        """

        with setup_test_agents(2, local, prefix="on_cfp") as agents:

            for a in agents:
                a.connect()

            agent_0, agent_1 = agents  # type: AgentTest, AgentTest

            agent_0.send_cfp(0, 0, agent_1.public_key, 0, None)
            agent_0.send_cfp(0, 1, agent_1.public_key, 0, b"hello")
            agent_0.send_cfp(0, 2, agent_1.public_key, 0,
                             Query([Constraint("foo", Eq(0))]))

            asyncio.ensure_future(agent_1.async_run())
            asyncio.get_event_loop().run_until_complete(
                asyncio.sleep(_ASYNCIO_DELAY))

        expected_message_01 = (0, 0, agent_0.public_key, 0, None)
        expected_message_02 = (0, 1, agent_0.public_key, 0, b"hello")
        expected_message_03 = (0, 2, agent_0.public_key, 0,
                               Query([Constraint("foo", Eq(0))]))

        assert 3 == len(agent_1.received_msg)
        assert expected_message_01 == agent_1.received_msg[0]
        assert expected_message_02 == agent_1.received_msg[1]
        assert expected_message_03 == agent_1.received_msg[2]
Пример #2
0
    def test_not_equal_when_compared_with_different_type(self):
        an_and = And(
            [Constraint("foo", Eq(True)),
             Constraint("bar", Eq(False))])
        not_an_and = tuple()

        assert an_and != not_an_and
Пример #3
0
def makeClient(number: int):

    #check if entity has already been created
    if (os.path.exists('./workdir/Agent_Auction/client/client' + str(number) +
                       '_private.key')):

        #locate the agent account entity for interacting with the ledger.
        with open(
                './workdir/Agent_Auction/client/client' + str(number) +
                '_private.key', 'r') as private_key_file:
            client_agentID = Entity.load(private_key_file)

    else:
        #create new entity for the agent
        client_agentID = Entity()
        #store private key of newly formed entity
        with open(
                './workdir/Agent_Auction/client/client' + str(number) +
                '_private.key', 'w') as private_key_file:
            client_agentID.dump(private_key_file)
        #give the account starting tokens
        api.sync(api.tokens.wealth(client_agentID, 1000))

    startBalance = api.tokens.balance(client_agentID)

    price = random.randint(25, 100)
    interval = random.randint(5, 20)

    # define an OEF Agent
    client = client_agent.ClientAgent(str(Address(client_agentID)),
                                      price,
                                      interval,
                                      client_agentID,
                                      oef_addr="127.0.0.1",
                                      oef_port=10000)

    print('Balance Before:', startBalance)

    # connect it to the OEF Node
    client.connect()

    # query OEF for DataService providers
    echo_query1 = Query(
        [Constraint("timezone", Eq(3)),
         Constraint("twentyfour", Eq(False))], TIME_AGENT())

    client.search_services(0, echo_query1)
    client.run()
Пример #4
0
def search_parking():
    #if request.method != 'POST':
    #    return json.dumps({"status":"only POST requests are accepted"})
    agent = DriverAgent("DriverAgent", oef_addr="127.0.0.1", oef_port=10000)
    agent.connect()
    time.sleep(2)
    query = Query([Constraint(PARKING_PRICE_PER_1HOUR.name, Eq(True))],
                  PARKING_JOURNEY_MODEL)

    agent.search_services(0, query)

    time.sleep(1)
    try:
        agent.run()
        time.sleep(3)
    except Exception as ex:
        print("EXCEPTION:", ex)
    finally:
        try:
            agent.stop()
            agent.disconnect()
        except:
            pass

    return json.dumps({"status": "done"})
Пример #5
0
def add_agent(data):
    # create and connect the agent
    print('Add agent: ' + data['name'])
    agent = TripAgent(data,
                      str(randint(1, 1e9)).replace('0', 'A').replace('1', 'B'),
                      oef_addr="185.91.52.11",
                      oef_port=10000)
    agent.connect()

    time.sleep(2)

    query = Query([Constraint(PRICE_PER_KM.name, Eq(True))], JOURNEY_MODEL)

    agent.search_services(0, query)

    time.sleep(1)
    try:
        agent.run()
        time.sleep(3)
    except Exception as ex:
        print("EXCEPTION:", ex)
    finally:
        try:
            agent.stop()
            agent.disconnect()
        except:
            pass
Пример #6
0
 def to_oef_constraint_type(
     cls, constraint_type: ConstraintType
 ) -> OEFConstraintType:
     """From our constraint type to OEF constraint type."""
     value = constraint_type.value
     if constraint_type.type == ConstraintTypes.EQUAL:
         return Eq(value)
     elif constraint_type.type == ConstraintTypes.NOT_EQUAL:
         return NotEq(value)
     elif constraint_type.type == ConstraintTypes.LESS_THAN:
         return Lt(value)
     elif constraint_type.type == ConstraintTypes.LESS_THAN_EQ:
         return LtEq(value)
     elif constraint_type.type == ConstraintTypes.GREATER_THAN:
         return Gt(value)
     elif constraint_type.type == ConstraintTypes.GREATER_THAN_EQ:
         return GtEq(value)
     elif constraint_type.type == ConstraintTypes.WITHIN:
         return Range(value)
     elif constraint_type.type == ConstraintTypes.IN:
         return In(value)
     elif constraint_type.type == ConstraintTypes.NOT_IN:
         return NotIn(value)
     else:
         raise ValueError("Constraint type not recognized.")
Пример #7
0
    def test_unregister_service(self, local):
        """
        Test that the unregistration of services works correctly.
        """

        with setup_test_agents(2, local,
                               prefix="unregister_service") as agents:

            for a in agents:
                a.connect()

            agent_0, agent_1 = agents

            dummy_datamodel = DataModel("dummy_datamodel",
                                        [AttributeSchema("foo", int, False)])
            dummy_service_description = Description({}, dummy_datamodel)
            agent_1.register_service(0, dummy_service_description)
            agent_1.unregister_service(0, dummy_service_description)

            agent_0.search_services(
                0, Query([Constraint("foo", Eq(0))], dummy_datamodel))
            asyncio.ensure_future(agent_0.async_run())
            asyncio.get_event_loop().run_until_complete(
                asyncio.sleep(_ASYNCIO_DELAY))

        assert 1 == len(agent_0.received_msg)
        assert (0, []) == agent_0.received_msg[0]
Пример #8
0
    def test_query_invalid_when_constraint_attribute_name_not_in_data_model(
            self):
        """Test that we raise an exception when at least one constraint attribute name
        is not present in the data model."""

        with pytest.raises(ValueError, match=""):
            a_query = Query([Constraint("an_attribute_name", Eq(0))],
                            DataModel("a_data_model", []))
Пример #9
0
    def test_query_invalid_when_constraint_attribute_name_different_type(self):
        """Test that we raise an exception when at least one constraint attribute name
        has a different type wrt the data model."""

        with pytest.raises(ValueError, match=""):
            a_query = Query(
                [Constraint("an_attribute_name", Eq(0))],
                DataModel("a_data_model",
                          [AttributeSchema("an_attribute_name", str, True)]))
Пример #10
0
    def test_on_search_result_agents(self, local):
        """
        Test that an agent can do a search for agents.
        """

        with setup_test_agents(3, local, prefix="search_agents") as agents:

            for a in agents:
                a.connect()

            agent_0, agent_1, agent_2 = agents

            foo_attr = AttributeSchema("foo", int, False, "A foo attribute.")
            bar_attr = AttributeSchema("bar", str, False, "A bar attribute.")

            dummy_datamodel = DataModel("dummy_datamodel",
                                        [foo_attr, bar_attr])
            agent_1.register_agent(
                0, Description({
                    "foo": 15,
                    "bar": "BAR"
                }, dummy_datamodel))
            agent_2.register_agent(
                0, Description({
                    "foo": 5,
                    "bar": "ABC"
                }, dummy_datamodel))

            agent_0.search_agents(
                0, Query([Constraint("foo", Eq(0))], dummy_datamodel))
            agent_0.search_agents(
                0,
                Query([
                    Constraint("foo", Gt(10)),
                    Constraint("bar", Gt("B")),
                ], dummy_datamodel))
            agent_0.search_agents(
                0, Query([
                    Constraint("bar", Gt("A")),
                ], dummy_datamodel))

            asyncio.ensure_future(agent_0.async_run())
            asyncio.get_event_loop().run_until_complete(
                asyncio.sleep(_ASYNCIO_DELAY))
            agent_1.unregister_agent(0)
            agent_2.unregister_agent(0)

        expected_message_01 = (0, [])
        expected_message_02 = (0, [agent_1.public_key])
        expected_message_03 = (0, [agent_1.public_key, agent_2.public_key])

        assert 3 == len(agent_0.received_msg)
        assert expected_message_01 == agent_0.received_msg[0]
        assert expected_message_02 == agent_0.received_msg[1]
        assert expected_message_03 == agent_0.received_msg[2]
    def test_group_dialogue_one_client_n_servers(self):
        with NetworkOEFNode():
            client_proxy = OEFNetworkProxy("client",
                                           oef_addr="127.0.0.1",
                                           port=3333)
            client = ClientAgentGroupDialogueTest(client_proxy)
            client.connect()

            N = 10
            server_proxies = [
                OEFNetworkProxy("server_{:02d}".format(i),
                                oef_addr="127.0.0.1",
                                port=3333) for i in range(N)
            ]
            server_data_model = DataModel("server",
                                          [AttributeSchema("foo", bool, True)])

            servers = [
                ServerAgentTest(server_proxy, price=random.randint(10, 100))
                for server_proxy in server_proxies
            ]
            for server in servers:
                server.connect()
                server.register_service(
                    0, Description({"foo": True}, server_data_model))

            best_server = ServerAgentTest(OEFNetworkProxy("best_server",
                                                          oef_addr="127.0.0.1",
                                                          port=3333),
                                          price=5)
            best_server.connect()
            best_server.register_service(
                0, Description({"foo": True}, server_data_model))
            servers.append(best_server)

            asyncio.get_event_loop().run_until_complete(
                asyncio.sleep(_ASYNCIO_DELAY))

            query = Query([Constraint("foo", Eq(True))], server_data_model)

            client.search_services(0, query)

            asyncio.get_event_loop().run_until_complete(
                asyncio.gather(client.async_run(),
                               *[server.async_run() for server in servers]))

            assert "best_server" == client.group.best_agent
            assert 5 == client.group.best_price
def makeAgent(preferences):
    OEF_Address = os.environ.get('OEF_ADDRESS')
    OEF_Port = os.environ.get('OEF_PORT')
    Agent_id = "Passenger{}".format(str(random.randint(
        0, 9999999999999))).replace("0", "")
    print(Agent_id, OEF_Address, OEF_Port)
    client_agent = ClientAgent(str(Agent_id),
                               oef_addr=OEF_Address,
                               oef_port=OEF_Port,
                               preferences=preferences)

    # connect it to the OEF Node
    client_agent.connect()

    # query OEF for DataService providers
    echo_query = Query([Constraint("timezone", Eq(2))], TIME_AGENT())
    client_agent.QUERY = echo_query
    client_agent.search_services(0, echo_query)
    return client_agent, Agent_id
Пример #13
0
    def test_not_equal_when_compared_with_different_type(self):
        a_query = Query([Constraint("foo", Eq(0))],
                        DataModel("bar", [AttributeSchema("foo", int, True)]))
        not_a_query = tuple()

        assert a_query != not_a_query
    server_agent = GreetingsAgent(server_proxy)

    # connect the agents to the OEF
    client_agent.connect()
    server_agent.connect()

    # register the greetings service agent on the OEF
    say_hello = AttributeSchema("say_hello", bool, True,
                                "The agent answers to 'hello' messages.")
    greetings_model = DataModel("greetings", [say_hello], "Greetings service.")
    greetings_description = Description({"say_hello": True}, greetings_model)
    server_agent.register_service(0, greetings_description)

    # the client executes the search for greetings services
    # we are looking for services that answers to "hello" messages
    query = Query([Constraint("say_hello", Eq(True))], greetings_model)

    print("[{}]: Search for 'greetings' services. search_id={}".format(
        client_agent.public_key, 0))
    client_agent.search_services(0, query)

    # run the agents
    try:
        loop = asyncio.get_event_loop()
        asyncio.ensure_future(local_node.run())
        loop.run_until_complete(
            asyncio.gather(client_agent.async_run(), server_agent.async_run()))
    finally:
        client_agent.stop()
        server_agent.stop()
Пример #15
0
        #store private key of newly formed entity
        with open('./workdir/Agent3/client/client_private.key',
                  'w') as private_key_file:
            client_agentID.dump(private_key_file)
        #give the account starting tokens
        api.sync(api.tokens.wealth(client_agentID, 1000))

    startBalance = api.tokens.balance(client_agentID)

    highest_price = 999

    # define an OEF Agent
    client_agent = ClientAgent(str(Address(client_agentID)),
                               highest_price,
                               client_agentID,
                               oef_addr="127.0.0.1",
                               oef_port=10000)

    print('Balance Before:', startBalance)

    # connect it to the OEF Node
    client_agent.connect()

    # query OEF for DataService providers
    echo_query1 = Query(
        [Constraint("timezone", Eq(3)),
         Constraint("twentyfour", Eq(False))], TIME_AGENT())

    client_agent.search_services(0, echo_query1)
    client_agent.run()
Пример #16
0
            self.stop()


if __name__ == '__main__':

    # define an OEF Agent
    client_agent = EchoClientAgent("echo_client",
                                   oef_addr="oef-node",
                                   oef_port=10000,
                                   loop=asyncio.get_event_loop())

    # connect it to the OEF Node
    client_agent.connect()

    # create a query for the echo data model
    echo_feature = AttributeSchema("does_echo", bool, True,
                                   "Whether the service agent can do echo.")
    echo_model = DataModel("echo", [echo_feature], "echo service.")
    echo_query = Query([Constraint("does_echo", Eq(True))], echo_model)

    print("[{}]: Make search to the OEF".format(client_agent.public_key))
    client_agent.search_services(0, echo_query)

    # wait for events
    try:
        client_agent.run()
    finally:
        print("[{}]: Disconnecting...".format(client_agent.public_key))
        client_agent.stop()
        client_agent.disconnect()
Пример #17
0
        self.stop()


if __name__ == '__main__':

    #define the ledger parameters
    api = LedgerApi('127.0.0.1', 8100)

    #locate the client account entity for interacting with the ledger.
    with open('./workdir/UberX/client_private.key', 'r') as private_key_file:
        client_agentID = Entity.load(private_key_file)

    # define an OEF Agent
    client_agent = ClientAgent(str(Address(client_agentID)),
                               oef_addr="127.0.0.1",
                               oef_port=10000)

    print('Balance Before:', api.tokens.balance(client_agentID))

    # connect it to the OEF Node
    client_agent.connect()

    # query OEF for DataService providers (i.e. available drivers in the area)
    my_current_area = 3  # Ideally we would keep track of this and update accordingly
    echo_query1 = Query([
        Constraint("area", Eq(my_current_area)),
        Constraint("available", Eq(True))
    ], DRIVER_AGENT())
    client_agent.search_services(0, echo_query1)
    client_agent.run()
        #    print("[{0}]: Sending contract to {1}".format(self.public_key, origin))
        #    self.send_message(0, dialogue_id, origin, encoded_data)


if __name__ == "__main__":

    name = sys.argv[1]

    print('Name:', name)

    agent = ScooterAgent(name, oef_addr="127.0.0.1", oef_port=10000)
    agent.connect()

    time.sleep(2)

    query = Query([Constraint(PRICE_PER_ENERGY_PERCENT.name, Eq(True))],
                  JOURNEY_MODEL)

    agent.search_services(0, query)

    time.sleep(1)

    print("[{}]: Waiting for clients...".format(agent.public_key))
    try:
        agent.run()
    finally:
        try:
            agent.stop()
            agent.disconnect()
        except:
            pass
                    print("Sending decline !")
                    self.send_decline(msg_id,dialogue_id, self.received_proposals[i]['agent'],msg_id + 1)
               
                self.cost = int(self.received_proposals[0]['proposal']['Price'])    
                self.send_accept(msg_id,dialogue_id,self.received_proposals[0]['agent'],msg_id + 1)
            else : 
                print("They don't have data")
                self.stop()

    def on_decline(self, msg_id: int, dialogue_id: int, origin: str, target: int) :
        print("Received a decline!")
        self.received_declines += 1

if __name__ == '__main__':

    # define an OEF Agent
    client_agent = ClientAgent("agent_client", oef_addr="oef.economicagents.com", oef_port=3333)

    # connect it to the OEF Node
    client_agent.connect()

    # query OEF for DataService providers
    echo_query = Query([Constraint("country", Eq("UK"))],
                        weather_station_dataModel.WEATHER_STATION_DATAMODEL())

    print("Make search to the OEF")
    client_agent.search_services(0, echo_query)

    # wait for events
    client_agent.run()
Пример #20
0
    def test_not_equal_when_compared_with_different_type(self):
        a_relation = Eq("foo")
        not_a_relation = tuple()

        assert a_relation != not_a_relation
    # query OEF for DataService providers
    echo_query = Query([Constraint("timezone", Eq(2))], TIME_AGENT())
    client_agent.QUERY = echo_query
    client_agent.search_services(0, echo_query)
    return client_agent, Agent_id
    # client_agent.run()


if __name__ == '__main__':

    OEF_Address = os.environ.get('OEF_ADDRESS')
    OEF_Port = os.environ.get('OEF_PORT')
    # oef.economicagents.com, 3333

    # define an OEF Agent
    Agent_id = base58.b58encode("Passenger{}".format(
        str(random.randint(0, 9999999999999))).replace("0", ""))
    print(Agent_id)
    client_agent = ClientAgent(Agent_id,
                               oef_addr=OEF_Address,
                               oef_port=OEF_Port)

    # connect it to the OEF Node
    client_agent.connect()

    # query OEF for DataService providers
    echo_query = Query([Constraint("timezone", Eq(2))], TIME_AGENT())

    client_agent.search_services(0, echo_query)
    client_agent.run()
Пример #22
0
        transaction = json.loads(content.decode("utf-8"))
        print("[{0}]: Received contract from {1}".format(
            self.public_key, origin))
        print("READY TO SUBMIT: ", transaction)

        self.stop()


if __name__ == "__main__":
    # create and connect the agent
    agent = RiderAgent("RiderAgent", oef_addr="127.0.0.1", oef_port=10000)
    agent.connect()

    time.sleep(2)

    query = Query([Constraint(PRICE_PER_KM.name, Eq(True))], JOURNEY_MODEL)

    agent.search_services(0, query)

    time.sleep(1)
    try:
        agent.run()
        time.sleep(3)
    except Exception as ex:
        print("EXCEPTION:", ex)
    finally:
        try:
            agent.stop()
            agent.disconnect()
        except:
            pass
Пример #23
0
results = False


class Searcher(OEFAgent):

    def on_search_result(self, search_id: int, agents: List[str]):
        with open('search_results.json', 'w') as outfile:
            json.dump(str(agents), outfile)
        self.stop()
        return


if __name__ == '__main__':
    search_terms = sys.argv[1].split('_')
    net = sys.argv[2]
    oef = 'oef.economicagents.com' if net == 'test' else '127.0.0.1'
    query_array = []
    for term in search_terms:
        query_array.append(Constraint(term, Eq(True)))
    query = Query(query_array)
    agent = Searcher('Searcher', oef_addr = oef, oef_port = 10000)
    agent.connect()
    agent.search_services(0, query)
    try:
        agent.run()
    finally:
        agent.stop()
        agent.disconnect()

Пример #24
0
    # create and connect the agent
    client_proxy = OEFNetworkProxy("weather_client", oef_addr="127.0.0.1", port=3333)
    client = WeatherClient(client_proxy)
    client.connect()

    N = 10
    station_proxies = [OEFNetworkProxy("weather_station_{:02d}".format(i),
                                       oef_addr="127.0.0.1", port=3333) for i in range(N)]

    stations = [WeatherStation(station_proxy, random.randint(10, 50)) for station_proxy in station_proxies]
    for station in stations:
        station.connect()
        station.register_service(0, station.weather_service_description)

    query = Query([
        Constraint("temperature", Eq(True)),
        Constraint("air_pressure", Eq(True)),
        Constraint("humidity", Eq(True))],
        WEATHER_DATA_MODEL)

    client.search_services(0, query)

    asyncio.get_event_loop().run_until_complete(
        asyncio.gather(
            client.async_run(),
            *[station.async_run() for station in stations]
        )
    )


Пример #25
0
    else:
        #create new entity for the agent
        client_agentID = Entity()
        #store private key of newly formed entity
        with open('./workdir/Agent4/client/client_private.key', 'w') as private_key_file:
            client_agentID.dump(private_key_file)
        #give the account starting tokens
        api.sync(api.tokens.wealth(client_agentID, 2000))

    startBalance = api.tokens.balance(client_agentID)

    # define an OEF Agent
    client_agent = ClientAgent(str(Address(client_agentID)), oef_addr="127.0.0.1", oef_port=10000)

    print('Balance Before:', startBalance)

    highest_price = 1700
    if highest_price > api.tokens.balance(client_agentID):
        highest_price = api.tokens.balance(client_agentID)
    currentPrice = 0

    # connect it to the OEF Node
    client_agent.connect()

    # query OEF for DataService providers
    echo_query1 = Query([Constraint("timezone", Eq(3)), Constraint("twentyfour", Eq(False))],TIME_AGENT())


    client_agent.search_services(0, echo_query1)
    client_agent.run()
Пример #26
0
    def test_not_equal_when_compared_with_different_type(self):
        a_not = Not(Constraint("foo", Eq(True)))
        not_a_not = tuple()

        assert a_not != not_a_not
Пример #27
0
    core = AsyncioCore(logger=logger)
    core.run_threaded()

    # create and connect the agent
    agent = WeatherClient("weatherCLient",
                          oef_addr="127.0.0.1",
                          oef_port=10000,
                          core=core)
    agent.connect()

    # look for service agents registered as 'weather_station' that:
    # - provide measurements for temperature
    # - provide measurements for air pressure
    # - provide measurements for humidity
    query = Query([
        Constraint(TEMPERATURE_ATTR.name, Eq(True)),
        Constraint(AIR_PRESSURE_ATTR.name, Eq(True)),
        Constraint(HUMIDITY_ATTR.name, Eq(True))
    ], WEATHER_DATA_MODEL)

    agent.search_services(0, query)

    try:
        agent.run()
        time.sleep(3)
    except Exception as ex:
        print("EXCEPTION:", ex)
    finally:
        agent.stop()
        agent.disconnect()
        core.stop()
Пример #28
0
    def on_message(self, msg_id: int, dialogue_id: int, origin: str,
                   content: bytes):
        """Extract and print data from incoming (simple) messages."""

        self.stop()


if __name__ == "__main__":
    # create and connect the agent
    agent = DriverAgent("DriverAgent", oef_addr="127.0.0.1", oef_port=10000)
    agent.connect()

    time.sleep(2)

    query = Query([Constraint(CHARGE_PRICE_PER_20MIN.name, Eq(True))],
                  CHARGE_JOURNEY_MODEL)

    agent.search_services(0, query)

    time.sleep(1)

    query = Query([Constraint(PARKING_PRICE_PER_1HOUR.name, Eq(True))],
                  PARKING_JOURNEY_MODEL)

    agent.search_services(0, query)

    time.sleep(1)
    try:
        agent.run()
        time.sleep(3)