建立專用的 Python 連接器 Bonsai


  • 完成的總時間:40分鐘
  • 有效時間:40分鐘
  • 使用中時間:0分鐘

連線在您的本機環境中執行的模擬器,以 Bonsai 進行模擬器測試和大腦定型。

在您開始使用 Intune 之前

  • 您必須熟悉 Python 程式碼撰寫。 下列指示假設您已瞭解 Python 程式碼撰寫的基本概念。 如果您之前從未在 Python 中撰寫程式碼,我們建議您在繼續進行之前,先 閱讀 MS 學習: Python 課程簡介
  • 您必須安裝 Python。 所有範例程式碼都是以 Python 3.7撰寫。 如果您已經安裝 Python,而且想要避免與現有的安裝發生衝突,請使用 python 環境 (pyenv) 或 虛擬環境 (virtualenv) 。
  • 您必須已 安裝

提示

如果您在隔離 Python 相依性不符或一般環境衝突時遇到問題,請考慮設定 Miniconda 虛擬環境以進行程式碼撰寫工作。

步驟1:使用新的類別包裝現有的模擬器

機器教學模擬器必須能夠:

  • 將任意設定設定為每個集的初始狀態。
  • 只要預期來自 AI 的輸入,就會暫停。
  • 對 AI 的輸入採取行動。
  • 傳回因 AI 指令採取行動而產生的新狀態。

符合這些需求最簡單的方式,就是將現有的程式碼包裝成包含明確和函式的模擬器模型類別 resetstep

  • reset:用來在每個定型集開始時,將您的模擬器重設為所需的設定。
  • step:藉由制定所定型的大腦所提供的指示,在每次反復時用來逐步執行您的模擬器 Bonsai 。

例如:

from typing import NamedTuple, Dict, Any

class SimulatorModel:
    def __init__(self):
        # TODO: Perform any global runtime simulator initialization that is needed here.
        pass

    def reset(self, config) -> Dict[str, Any]:
        # TODO: Reset state from the previous episode that needs to be cleared.
        # TODO: Perform initialization in preparation for running an episode using the values in the config dictionary.
        return { 
            'sim_halted': False,
            # TODO: Add simulator state as dictionary with key as the state and value as the state's value.
            'key': value,
        }

    def step(self, action) -> Dict[str, Any]:
        # TODO: Perform a simulation step using the values in the action dictionary.
        return {
            # TODO: If 'sim_halted' is set to True, that indicates that the simulator is unable to continue and the
            # episode will be discarded. If your simulator cannot reach an unrecoverable state, always set 'sim_halted'
            # to False.
            'sim_halted': False,
            # TODO: Add simulator state as dictionary with key as the state and value as the state's value.
            'key': value,
        }

步驟2:新增程式碼以將您現有的模擬器連線到 Bonsai

下一步是更新您的 main.py 檔案,以註冊您的模擬器,並將其連線至

提示

您可以在 GitHub 存放庫中看到功能完整的main.py 檔案範例。 此範例會在本機執行,以註冊並連接新增數位的內含模擬器。

使用下列程式碼,向註冊模擬器會話 Bonsai :

import os
import time
from microsoft_bonsai_api.simulator.client import BonsaiClient, BonsaiClientConfig
from microsoft_bonsai_api.simulator.generated.models import SimulatorInterface, SimulatorState, SimulatorSessionResponse

workspace = os.getenv("SIM_WORKSPACE")
accesskey = os.getenv("SIM_ACCESS_KEY")

config_client = BonsaiClientConfig()
client = BonsaiClient(config_client)

registration_info = SimulatorInterface(
    name="MY_SIMULATOR_NAME",
    timeout=60,
    simulator_context=config_client.simulator_context,
    description=None,
)

registered_session: SimulatorSessionResponse = client.session.create(workspace_name=config_client.workspace, body=registration_info)
print(f"Registered simulator. {registered_session.session_id}")

注意

此範例假設您已設定 SIM_WORKSPACE 和的環境變數, SIM_ACCESS_KEY 以方便使用。 如果您想要的話,也可以使用替代方法來傳遞該資訊,例如加密的設定檔案或資料庫連接。

然後使用下列迴圈來接收和處理 Bonsai 事件:

import os
import time
from microsoft_bonsai_api.simulator.client import BonsaiClient, BonsaiClientConfig
from microsoft_bonsai_api.simulator.generated.models import SimulatorInterface, SimulatorState, SimulatorSessionResponse

workspace = os.getenv("SIM_WORKSPACE")
accesskey = os.getenv("SIM_ACCESS_KEY")

config_client = BonsaiClientConfig()
client = BonsaiClient(config_client)

registration_info = SimulatorInterface(
    name="MY_SIMULATOR_NAME",
    timeout=60,
    simulator_context=config_client.simulator_context,
    description=None,
)

registered_session: SimulatorSessionResponse = client.session.create(workspace_name=config_client.workspace, body=registration_info)
print(f"Registered simulator. {registered_session.session_id}")

sequence_id = 1
sim_model = SimulatorModel()
sim_model_state = { 'sim_halted': False }

try:
    while True:
        sim_state = SimulatorState(sequence_id=sequence_id, state=sim_model_state, halted=sim_model_state.get('sim_halted', False))
        event = client.session.advance(
            workspace_name=config_client.workspace,
            session_id=registered_session.session_id,
            body=sim_state,
        )
        sequence_id = event.sequence_id

        if event.type == "Idle":
            time.sleep(event.idle.callback_time)
        elif event.type == "EpisodeStart":
            sim_model_state = sim_model.reset(event.episode_start.config)
        elif event.type == "EpisodeStep":
            sim_model_state = sim_model.step(event.episode_step.action)
        elif event.type == "EpisodeFinish":
            sim_model_state = { 'sim_halted': False }
        elif event.type == "Unregister":
            print(f"Simulator Session unregistered by platform because '{event.unregister.details}'")
            return
except BaseException as err:
    client.session.delete(workspace_name=config_client.workspace, session_id=registered_session.session_id)
    print(f"Unregistered simulator because {type(err).__name__}: {err}")

您現在有一個可運作的模擬器 Bonsai ,可接收來自服務的事件, Bonsai 並使用您的 SimulatorModel 類別來啟動、逐步執行和完成模擬集。

下一步

執行您的模擬器,並確認其名稱列于工作區的 [模擬器] 窗格中 Bonsai 。 嘗試建立並定型使用您模擬器的大腦。