AI 寻优代码示例(2024-2026 实战)

2026-07 校准:3 个实战代码示例 — Python RL 冷机寻优 / Node-RED 群控 / MindSphere 集成。给研发岗直接复制

1. Python RL 冷机寻优(2024-2026 主流)

# chiller_optimization_rl.py
# 2024-2026 主流:RL 冷机群控 + 故障预测
# 依赖: pip install stable-baselines3 gym numpy pandas
 
import gym
import numpy as np
import pandas as pd
from stable_baselines3 import PPO
 
class ChillerEnv(gym.Env):
    """冷机优化环境:动作=冷机组合 + 启停,观察=负荷 + 室外温度"""
    def __init__(self, num_chillers=3):
        super().__init__()
        self.num = num_chillers
        # 动作:每个冷机 0=关, 1=低负荷, 2=中负荷, 3=高负荷
        self.action_space = gym.spaces.MultiDiscrete([4] * num_chillers)
        # 观察:室外温度 + 负荷 + 当前每台负荷
        self.observation_space = gym.spaces.Box(
            low=0, high=100, shape=(3 + num_chillers,), dtype=np.float32
        )
        self.reset()
 
    def reset(self):
        self.t = 0
        self.outdoor = 25
        self.load = 0.5
        self.ch_state = [0] * self.num
        return np.array([self.outdoor, self.load] + self.ch_state, dtype=np.float32)
 
    def step(self, action):
        # 简化模型:每台冷机 COP 随负荷率变化
        cop_per_ch = []
        for i, a in enumerate(action):
            if a == 0:  # 关
                cop_per_ch.append(0)
            else:
                load_rate = 0.33 * a
                cop = 4.5 + 1.0 * load_rate - 0.5 * load_rate ** 2
                cop_per_ch.append(cop)
        # 总 COP
        total_cop = np.mean(cop_per_ch) if cop_per_ch else 0
 
        # 故障预测(简化)
        fault_risk = max(action) * 0.01  # 高负荷 → 高故障
 
        # 奖励 = COP - 故障风险 - 能耗
        reward = total_cop * 10 - fault_risk * 100 - 1
 
        # 时序更新
        self.t += 1
        self.outdoor = 25 + 10 * np.sin(self.t / 10)
        self.load = 0.5 + 0.2 * np.cos(self.t / 8)
        return (
            np.array([self.outdoor, self.load] + list(action), dtype=np.float32),
            reward,
            self.t > 100,
            {"cop": total_cop, "fault": fault_risk}
        )
 
env = ChillerEnv(num_chillers=3)
model = PPO("MlpPolicy", env, verbose=1)
model.learn(total_timesteps=10000)
model.save("chiller_rl_v1_2026.model")

2. Node-RED 群控(2024-2026 主流)

// flows_2026.json - 冷站群控流程
{
  "id": "chiller_plant_control_2026",
  "type": "tab",
  "label": "冷站群控 2026",
  "disabled": false,
  "info": "AI 寻优 + 故障预测"
}
// 冷机选择器
[
  {
    "id": "load_predictor",
    "type": "function",
    "name": "负荷预测(AI)",
    "func": "// 简化:用历史平均 + 实时调整\nconst currentLoad = msg.payload.load || 0;\nconst outdoorT = msg.payload.outdoor || 25;\nconst predicted = currentLoad * 1.15; // 简化预测\nreturn { payload: { load: predicted, outdoor: outdoorT, ts: Date.now() } };",
    "outputs": 1
  },
  {
    "id": "ai_optimizer",
    "type": "function",
    "name": "AI 群控寻优(2026)",
    "func": "// 简化的 RL 群控:根据负荷分配冷机\nconst load = msg.payload.load || 0;\nconst numChillers = 3;\nlet actions = [0, 0, 0];\n\nif (load < 0.4) {\n  actions = [1, 0, 0];  // 单台低负荷\n} else if (load < 0.7) {\n  actions = [2, 1, 0];  // 一主一备\n} else if (load < 0.95) {\n  actions = [3, 2, 0];  // 一主一中\n} else {\n  actions = [3, 2, 1];  // 全开\n}\nreturn { payload: { actions, load, ts: Date.now() } };",
    "outputs": 1
  },
  {
    "id": "chiller_action",
    "type": "mqtt out",
    "topic": "hvac/chillers/control",
    "name": "下发冷机指令",
    "qos": "2"
  }
]

3. MindSphere 数据接入(2024-2026 主流)

# mindsphere_hvac_2026.py
# MindSphere 数字孪生 + AI 寻优集成
import mindsphere.client as ms
import json
 
client = ms.MindSphereAPIClient(
    tenant="your_tenant",
    auth=ms.Credentials("user", "password")
)
 
# 1. 设备孪生查询
asset_id = "chiller_unit_001_2026"
asset = client.assets.retrieve(asset_id)
print(f"Asset: {asset.name}, type: {asset.typeId}")
 
# 2. 实时数据读取
timeseries = client.timeseries.read(
    entity_id=asset_id,
    properties=["temperature_in", "temperature_out", "pressure_high", "power"],
    limit=100,
    sort="desc",
    select="timestamp,value"
)
 
# 3. AI 寻优预测(2024-2026 主流)
def predict_optimization(asset_data):
    """基于历史数据 + 实时数据 + AI 寻优 → 调速 / 启停建议"""
    avg_power = sum(d['value'] for d in asset_data if d['property'] == 'power') / len(asset_data)
    avg_temp_out = sum(d['value'] for d in asset_data if d['property'] == 'temperature_out') / len(asset_data)
    
    # 简化 AI 寻优
    if avg_power > 1000 and avg_temp_out > 30:
        return {"action": "reduce_load", "target_temp": 7, "expected_saving": "8%"}
    elif avg_temp_out < 18:
        return {"action": "free_cooling", "expected_saving": "15%"}
    return {"action": "maintain", "expected_saving": "0%"}
 
optimization = predict_optimization(timeseries)
 
# 4. 推送到 MindSphere 事件流
event = client.events.create(
    entity_id=asset_id,
    body={
        "timestamp": "2026-07-01T00:00:00Z",
        "properties": {
            "ai_optimization": optimization,
            "source": "AI 寻优(2024-2026)"
        }
    }
)
print(f"Optimization event created: {event.id}")

4. 故障预测示例(2024-2026 主流)

# fault_predict_2026.py
# 故障预测 + 健康管理
import pandas as pd
from sklearn.ensemble import IsolationForest
 
# 1. 加载历史数据(从 InfluxDB)
df = pd.read_csv("chiller_history.csv", parse_dates=["timestamp"])
# 字段: timestamp, current_A, voltage_V, temp_oil, vibration, power_kW
 
# 2. 训练异常检测模型
features = ["current_A", "voltage_V", "temp_oil", "vibration", "power_kW"]
model = IsolationForest(contamination=0.01, random_state=42)
model.fit(df[features])
 
# 3. 实时检测
new_data = df[features].tail(10)
predictions = model.predict(new_data)
anomalies = new_data[predictions == -1]
print(f"检测到 {len(anomalies)} 个异常点")
 
# 4. 推送到 MindSphere 事件
for idx, row in anomalies.iterrows():
    event = client.events.create(
        entity_id="chiller_001_2026",
        body={
            "timestamp": row["timestamp"].isoformat(),
            "properties": {
                "fault": "compressor_anomaly",
                "severity": "high" if row["vibration"] > 5 else "medium",
                "ai_source": "IsolationForest 2024-2026"
            }
        }
    )
    print(f"已推送事件: {event.id}")

5. 写代码 / 部署必查清单(2024-2026 校准)

  • Python 3.10+ / Node.js 18+
  • stable-baselines3 / InfluxDB client / MindSphere SDK
  • 数据 ≥ 6 月(故障预测 ≥ 1 年)
  • 模型版本管理(MLflow / DVC)
  • 实时流处理(Kafka / Flink)
  • 模型监控 / 漂移告警
  • 5 年 TCO 含运维

引用