ノードとプラグインを書く
ノードは普通のPythonクラスで、プラグインはノードをまとめた普通のPythonパッケージです。テンプレートのプラグインにノードを2つ追加し、計算グラフにつないで実行します。
プラグインの構成
テンプレートのプラグインuser-nodesの構成は、次のとおりです。
templates/default/plugins/
├── manifest.json 有効にするプラグインの一覧
└── user-nodes/
├── pyproject.toml パッケージ名と依存パッケージ
└── user_nodes/
├── __init__.py register_nodes(registry)でノードを登録する
└── nodes.py SynthesizerとSpectrumAnalyzerフォルダ名はハイフン(user-nodes)、Pythonパッケージ名はアンダースコア(user_nodes)です。エンジンは起動時に、manifest.jsonで有効なプラグインを読み込み、そのregister_nodesを呼びます。
プラグインはソースのまま読み込まれ、pyproject.tomlの依存パッケージは自動ではインストールされません。プラグインが使うライブラリは、エンジンの環境に入っている必要があります。この環境にはNumPyとSciPyが入っています。ほかのライブラリを使うときは、エンジンのフォルダでuv add <パッケージ名>を実行します。
値を受け取って送るノード
信号に係数を掛けるノードを、templates/default/plugins/user-nodes/user_nodes/gain.pyに書きます。
import numpy as np
from nonoha_core.data_type import DataType, PortValueType, PropertyDataType
from nonoha_core.node import BaseNode, NodeDoc
from nonoha_core.port import StaticTypeInputPort, StaticTypeOutputPort
class GainNode(BaseNode):
@classmethod
def describe(cls, properties=None):
return NodeDoc(
description="Multiplies a signal by a gain",
category="Custom",
inputs={"in": "Samples"},
outputs={"out": "The samples times the gain"},
)
PROPERTIES = {
"gain": {"description": "The factor to multiply by", "default_value": 0.5, "data_type": "f64"},
}
def __init__(self, name: str):
super().__init__(name, "Gain")
samples = PortValueType(DataType.Float32)
self._input = StaticTypeInputPort("in", [samples])
self._input.subscribe(id(self), self._on_input)
self.inputs[self._input.name] = self._input
self._output = StaticTypeOutputPort("out", [samples])
self.outputs[self._output.name] = self._output
def _on_input(self, values: list[np.ndarray]):
# values[0]: a batch of samples, shape (batch,)
self._output.dispatch([values[0] * np.float32(self.properties["gain"])])
def set_properties(self, properties: dict[str, PropertyDataType]):
if "gain" in properties:
self.properties["gain"] = float(properties["gain"])
if self.parent_graph is not None:
self.parent_graph.notify_node_updated(self)describe()は、ノードの一覧(カタログ)に表示する説明を返します。PROPERTIESは、プロパティとその既定値です。data_typeを書いたプロパティは、プロパティポート(@gain)にもなります。__init__()でポートを作成します。副作用を持たせず、時間のかかる処理や通信はactivate()で始めます(後述)。- 入力ポートに値が届くと、
_on_inputが呼ばれます。values[0]はバッチ次元を持つNumPy配列で、このポートの型(f32)では形状が(バッチ,)です。 dispatch()で出力ポートに送ります。送る配列も、バッチ次元を持ちます。set_properties()は、計算グラフの読み込み時と、エディタ、API、プロパティポートからプロパティが変わったときに呼ばれます。最後にnotify_node_updated()を呼ぶと、エンジンが変更をgraph.jsonに保存します。
登録する
user_nodes/__init__.pyのregister_nodesに、ノードを追加します(抜粋)。register_nodeに渡す名前は、super().__init__(name, "Gain")の名前と一致させます。
from .gain import GainNode
def register_nodes(registry: NodeRegistry):
registry.register_node("Synthesizer", SynthesizerNode)
registry.register_node("SpectrumAnalyzer", SpectrumAnalyzerNode)
registry.register_node("Gain", GainNode)計算グラフにつなぐ
エンジンを止めてから、templates/default/flows/default.vnf/graphs/app.vng/graph.jsonを編集します。nodesにGainを追加します。
"Gain_1": { "type": "Gain", "properties": { "gain": 0.5 } }edgesでは、Synthesizerの波形をそのまま出力するエッジ{ "source": "Synthesizer_1.waveform", "target": ".waveform" }を削除し、Gainを通す2本を追加します。
{ "source": "Synthesizer_1.waveform", "target": "Gain_1.in" },
{ "source": "Gain_1.out", "target": ".waveform" }エンジンを起動し直すと、アプリの「WAVEFORM」の振幅が半分になります。ノードの一覧(catalogコマンド、または/node-flow/catalog/nodes)にもGainが表示され、入力ポートinとプロパティポート@gainがあります。
自分で値を送り出すノード
入力を待たず、一定の間隔で値を送り出すノードです。user_nodes/counter.pyに書き、Gainと同じようにregister_nodesに追加します。
import asyncio
import numpy as np
from nonoha_core.data_type import DataType, PortValueType, PropertyDataType
from nonoha_core.node import BaseNode, NodeDoc
from nonoha_core.port import StaticTypeOutputPort
class CounterNode(BaseNode):
@classmethod
def describe(cls, properties=None):
return NodeDoc(
description="Counts up at a regular interval",
category="Custom",
outputs={"count": "The current count"},
)
PROPERTIES = {
"interval": {"description": "Seconds between counts", "default_value": 1.0, "data_type": "f64"},
}
def __init__(self, name: str):
super().__init__(name, "Counter")
self._output = StaticTypeOutputPort("count", [PortValueType(DataType.Float32)])
self.outputs[self._output.name] = self._output
self._count = 0
self._task: asyncio.Task | None = None
def activate(self):
# The graph is running: start counting on its event loop
self._task = asyncio.get_running_loop().create_task(self._count_up())
async def _count_up(self):
while True:
await asyncio.sleep(self.properties["interval"])
self._count += 1
self._output.dispatch([np.array([self._count], dtype=np.float32)])
# Nothing else sends what a timer dispatches: send it on now
if self.parent_graph is not None:
self.parent_graph.flush_outputs()
def finalize(self):
# The node is removed or the engine stops
if self._task is not None:
self._task.cancel()
self._task = None
def set_properties(self, properties: dict[str, PropertyDataType]):
if "interval" in properties:
self.properties["interval"] = float(properties["interval"])
if self.parent_graph is not None:
self.parent_graph.notify_node_updated(self)activate()は、実行中の計算グラフにノードが追加されたときに呼ばれます。ここでエンジンのイベントループにタスクを作成します。finalize()は、ノードを削除したときや、エンジンが止まるときに呼ばれます。開始したタスクを止めます。- 入力に応じて送った値は、その入力を送った側がまとめて送り出します。タイマーのように自分のタイミングで送る値は、
dispatch()のあとにflush_outputs()を呼んで、すぐに送り出します。
エンジンを止めてから、計算グラフにノード、グラフの出力ポートcount、それをつなぐエッジを追加します。
"nodes": { "Counter_1": { "type": "Counter", "properties": { "interval": 0.5 } } },
"outputs": { "count": { "types": ["f32"] } },
"edges": [{ "source": "Counter_1.count", "target": ".count" }]ここに書いたのは追加する部分だけで、既存のnodes、outputs、edgesはそのまま残します。この出力は、カスタムのWeb UIで画面に表示します。
配列の形状に気をつける
送る配列の形状は、出力ポートの型の前にバッチ次元を付けたものです。f32の出力ポートなら(バッチ,)、f32[N]の出力ポートなら(バッチ, N)です。f32[N]の出力ポートで、1回の計算で長さNの結果が1つできるときは、result[np.newaxis]で先頭にバッチ次元を付けてから送ります。ポートの型は、しくみにまとめています。
次に読む
- カスタムのWeb UI:GainとCounterを画面から操作します。
- ノードの書き方の決まりは、nonoha-engineのAGENTS.mdにまとまっています。