diff src/MY_sequential_example.py @ 0:f895e266b37a draft

planemo upload for repository https://forgemia.inra.fr/nathalie.rousse/use/-/tree/gama/GAMA/galaxy-tools commit 67d85c013c62c16392b4796af86836b1334f2eef
author siwaa
date Tue, 04 Jun 2024 15:18:01 +0000
parents
children 168edc2db729
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/MY_sequential_example.py	Tue Jun 04 15:18:01 2024 +0000
@@ -0,0 +1,213 @@
+import asyncio
+from asyncio import Future
+from typing import Dict
+
+from gama_client.base_client import GamaBaseClient
+from gama_client.command_types import CommandTypes
+from gama_client.message_types import MessageTypes
+
+import pprint # _PRINT_
+import argparse
+
+nb_preys_init = 100     # default
+nb_predators_init = 10  # default
+nb_more_steps = 5       # default
+
+experiment_future: Future
+play_future: Future
+pause_future: Future
+expression_future: Future
+step_future: Future
+stop_future: Future
+
+
+async def message_handler(message: Dict):
+    print("received", message)
+    if "command" in message:
+        if message["command"]["type"] == CommandTypes.Load.value:
+            experiment_future.set_result(message)
+        elif message["command"]["type"] == CommandTypes.Play.value:
+            play_future.set_result(message)
+        elif message["command"]["type"] == CommandTypes.Pause.value:
+            pause_future.set_result(message)
+        elif message["command"]["type"] == CommandTypes.Expression.value:
+            expression_future.set_result(message)
+        elif message["command"]["type"] == CommandTypes.Step.value:
+            step_future.set_result(message)
+        elif message["command"]["type"] == CommandTypes.Stop.value:
+            stop_future.set_result(message)
+
+
+async def main():
+
+    global experiment_future
+    global play_future
+    global pause_future
+    global expression_future
+    global step_future
+    global stop_future
+
+    # Experiment and Gama-server constants
+
+    MY_SERVER_URL = "localhost"
+
+    MY_SERVER_PORT = 8000
+
+    GAML_FILE_PATH_ON_SERVER = "gama-platform/headless/samples/predatorPrey/MY_predatorPrey.gaml"
+
+    EXPERIMENT_NAME = "prey_predator"
+
+    MY_EXP_INIT_PARAMETERS = [{"type": "int", "name": "nb_preys_init",
+                               "value": nb_preys_init},
+                              {"type": "int", "name": "nb_predators_init",
+                               "value": nb_predators_init}]
+
+    print("[MY_sequential_example.py Setting]",
+          " MY_SERVER_URL:", MY_SERVER_URL,
+         ", MY_SERVER_PORT:", MY_SERVER_PORT,
+         ", GAML_FILE_PATH_ON_SERVER: ", GAML_FILE_PATH_ON_SERVER,
+         ", EXPERIMENT_NAME: ", EXPERIMENT_NAME,
+         ", MY_EXP_INIT_PARAMETERS: ", MY_EXP_INIT_PARAMETERS)
+
+    client = GamaBaseClient(MY_SERVER_URL, MY_SERVER_PORT, message_handler)
+
+    print("connecting to Gama server")
+    await client.connect()
+
+    print("initialize a gaml model")
+    experiment_future = asyncio.get_running_loop().create_future()
+    #await client.load(GAML_FILE_PATH_ON_SERVER, EXPERIMENT_NAME, True, True, True, MY_EXP_INIT_PARAMETERS) # error
+    await client.load(file_path=GAML_FILE_PATH_ON_SERVER,
+                      experiment_name=EXPERIMENT_NAME,
+                      console=True, status=True, dialog=True, runtime=True,
+                      parameters=MY_EXP_INIT_PARAMETERS)
+
+    gama_response = await experiment_future
+    print("*********************") # _PRINT_
+    print("gama_response.keys():", gama_response.keys())
+    print("gama_response:")
+    pprint.pprint(gama_response)
+    print("*********************")
+
+    try:
+        experiment_id = gama_response["content"]
+    except Exception as e:
+        print("error while initializing", gama_response, e)
+        return
+
+    print("initialization successful, running the model")
+    play_future = asyncio.get_running_loop().create_future()
+    await client.play(experiment_id)
+    gama_response = await play_future
+    if gama_response["type"] != MessageTypes.CommandExecutedSuccessfully.value:
+        print("error while trying to run the experiment", gama_response)
+        return
+    print("*********************") # _PRINT_
+    print("gama_response.keys():", gama_response.keys())
+    print("gama_response:")
+    pprint.pprint(gama_response)
+    print("*********************")
+
+    print("model running, waiting a bit")
+    await asyncio.sleep(2)
+
+    print("pausing the model")
+    pause_future = asyncio.get_running_loop().create_future()
+    await client.pause(experiment_id)
+    gama_response = await pause_future
+    if gama_response["type"] != MessageTypes.CommandExecutedSuccessfully.value:
+        print("Unable to pause the experiment", gama_response)
+        return
+    print("*********************") # _PRINT_
+    print("gama_response.keys():", gama_response.keys())
+    print("gama_response:")
+    pprint.pprint(gama_response)
+    print("*********************")
+
+    expression_future = asyncio.get_running_loop().create_future()
+    await client.expression(experiment_id, r"cycle")
+    gama_response = await expression_future
+    print("asking simulation the value of: cycle=", gama_response["content"])
+    print("*********************") # _PRINT_
+    print("gama_response.keys():", gama_response.keys())
+    print("gama_response:")
+    pprint.pprint(gama_response)
+    print("*********************")
+
+    expression_future = asyncio.get_running_loop().create_future()
+    await client.expression(experiment_id, r"nb_preys/nb_preys_init")
+    gama_response = await expression_future
+    print("asking simulation the value of: nb_preys/nb_preys_init=",  gama_response["content"])
+    print("*********************") # _PRINT_
+    print("gama_response.keys():", gama_response.keys())
+    print("gama_response:")
+    pprint.pprint(gama_response)
+    print("*********************")
+
+    print("asking gama to run ",nb_more_steps," more steps of the experiment")
+    step_future = asyncio.get_running_loop().create_future()
+    await client.step(experiment_id, nb_more_steps, True)
+    #await client.step(experiment_id, 10, True)
+    gama_response = await step_future
+    if gama_response["type"] != MessageTypes.CommandExecutedSuccessfully.value:
+        print("Unable to execute 10 new steps in the experiment", gama_response)
+        return
+    print("*********************") # _PRINT_
+    print("gama_response.keys():", gama_response.keys())
+    print("gama_response:")
+    pprint.pprint(gama_response)
+    print("*********************")
+
+    expression_future = asyncio.get_running_loop().create_future()
+    await client.expression(experiment_id, r"cycle")
+    gama_response = await expression_future
+    print("asking simulation the value of: cycle=", gama_response["content"])
+    print("*********************") # _PRINT_
+    print("gama_response.keys():", gama_response.keys())
+    print("gama_response:")
+    pprint.pprint(gama_response)
+    print("*********************")
+
+    print("killing the simulation")
+    stop_future = asyncio.get_running_loop().create_future()
+    await client.stop(experiment_id)
+    gama_response = await stop_future
+    if gama_response["type"] != MessageTypes.CommandExecutedSuccessfully.value:
+        print("Unable to stop the experiment", gama_response)
+        return
+    print("*********************") # _PRINT_
+    print("gama_response.keys():", gama_response.keys())
+    print("gama_response:")
+    pprint.pprint(gama_response)
+    print("*********************")
+
+    # Added
+    print("killing gama-server")
+    exit_future = asyncio.get_running_loop().create_future()
+    await client.exit()
+    # no response
+    print("*********************") # _PRINT_
+    print("Command exit() done")
+    print("*********************")
+
+
+if __name__ == "__main__":
+
+    parser = argparse.ArgumentParser()
+    parser.add_argument("-nb_preys_init", type=int, help="nb_preys_init")
+    parser.add_argument("-nb_predators_init", type=int, help="nb_predators_init")
+    parser.add_argument("-nb_more_steps", type=int, help="nb_more_steps")
+    args = parser.parse_args()
+    if (args.nb_preys_init is not None) and (args.nb_preys_init != 'None') :
+        nb_preys_init = args.nb_preys_init
+    if (args.nb_predators_init is not None) and (args.nb_predators_init != 'None') :
+        nb_predators_init = args.nb_predators_init
+    if (args.nb_more_steps is not None) and (args.nb_more_steps != 'None') :
+        nb_more_steps = args.nb_more_steps
+
+    print("[MY_sequential_example.py Parameters]",
+          " nb_preys_init (for MY_predatorPrey.gaml) :", nb_preys_init,
+          " nb_predators_init (for MY_predatorPrey.gaml) :", nb_predators_init,
+         ", nb_more_steps (for MY_sequential_example.py) :", nb_more_steps)
+
+    asyncio.run(main())