
1. 文件頭與庫導入
# -*- coding: utf-8 -*-
import streamlit as st
import pandas as pd
import numpy as np
import plotly.graph_objects as go
from datetime import datetime
from sklearn.ensemble import RandomForestRegressor
- ??作用??:設置文件編碼為UTF-8,導入依賴庫:
streamlit
:構建Web應用界面pandas/numpy
:數據處理plotly
:3D可視化RandomForestRegressor
:機器學習模型用于進化預測
2. NineScreenCell類
class NineScreenCell:def __init__(self, time_dimension: str, system_level: str):# 驗證時空維度(符合GB/T 31769-2015)self.time = time_dimension # 時間維度:過去/現在/未來self.level = system_level # 系統層級:子系統/系統/超系統# TRIZ要素定義self.technical_elements = [] # 技術要素集合self.resources = {"物質": [], "能量": [], ...} # 五類資源分類# 進化參數self._tech_maturity = 0.5 # 技術成熟度 [0,1]self.evolution_stages = [] # 進化階段記錄self.contradictions = [] # 工程矛盾ID列表# 動態更新風險指標self.update_risk_score()
- ??核心功能??:
- 表示九屏法中單個單元格的完整狀態
- 通過
update_risk_score()
計算風險指數(技術成熟度、矛盾數量、資源完備性加權) - 使用屬性裝飾器確保技術成熟度在[0,1]范圍內
3. TRIZNineScreenMatrix類
class TRIZNineScreenMatrix:def __init__(self, system_name: str):# 構建3x3矩陣(時間維度 x 系統層級)self.matrix = [[NineScreenCell(t, l) for l in levels] for t in times]def _load_standard_conflict_matrix(self):# 加載簡化的TRIZ矛盾矩陣(39x39標準)return pd.DataFrame(...)def predict_evolution(self):# 使用隨機森林預測未來進化階段model = RandomForestRegressor()model.fit(X, y) # 基于歷史數據訓練# 預測未來階段的演進路徑
- ??關鍵點??:
- 構建完整的3x3九屏矩陣
- 內置TRIZ標準矛盾矩陣(簡化版)
- 機器學習預測未來技術演進階段
4. 三維可視化引擎
def plot_nine_screen_3d(matrix):fig = go.Figure(data=go.Surface(...))# 添加風險曲面和進化階段標注annotations = [...] # 顯示每個單元格的進化階段fig.update_layout(...)
- ??可視化邏輯??:
- X軸:時間維度(過去/現在/未來)
- Y軸:系統層級(子系統/系統/超系統)
- Z軸:風險指數(顏色映射表示高低風險)
- 標注顯示技術演進的關鍵階段
5. Streamlit主界面
def main():st.set_page_config(...) # 初始化頁面配置# 狀態管理:保持系統實例if "triz_system" not in st.session_state:st.session_state.triz_system = TRIZNineScreenMatrix(...)# 側邊欄控制面板with st.sidebar:# 系統參數配置tech_maturity = st.slider(...) # 技術成熟度調節resource_management = st.multiselect(...) # 資源管理st.button("更新模型") # 觸發重新預測# 主顯示區域with tab1: # 3D可視化st.plotly_chart(fig)with tab2: # 矛盾矩陣分析st.dataframe(...) # 顯示標準矛盾矩陣# 動態推薦創新原理
- ??交互設計??:
- 側邊欄控制當前選中單元格的參數
- 雙標簽頁分別展示空間分析和矛盾解決工具
- 實時反饋參數變化對風險模型的影響
6. 運行入口
if __name__ == "__main__":main()
7. 完整代碼
# -*- coding: utf-8 -*-
import streamlit as st
import pandas as pd
import numpy as np
import plotly.graph_objects as go
from datetime import datetime
from sklearn.ensemble import RandomForestRegressor# --------------------------
# TRIZ九屏核心模型(符合GB/T 31769-2015)
# --------------------------
class NineScreenCell:"""嚴格符合九屏法理論的標準單元格"""def __init__(self, time_dimension: str, system_level: str):# 時空維度驗證valid_time = ["過去", "現在", "未來"]valid_level = ["子系統", "系統", "超系統"]if time_dimension not in valid_time or system_level not in valid_level:raise ValueError("時空維度定義不符合九屏法標準")self.time = time_dimension # 時間維度self.level = system_level # 系統層級# 核心要素(符合TRIZ標準)self.technical_elements = [] # 技術要素集合self.resources = {"物質": [],"能量": [],"信息": [],"時空": [],"功能": []} # 五類資源分類# 進化參數self._tech_maturity = 0.5 # 技術成熟度 [0,1]self.evolution_stages = [] # 進化階段記錄self.contradictions = [] # 工程矛盾ID列表# 動態指標self.update_risk_score()def update_risk_score(self):"""基于TRIZ的風險評估模型"""resource_score = sum(len(v) for v in self.resources.values()) / 15contradiction_score = len(self.contradictions) * 0.1self.risk = np.clip((1 - self._tech_maturity) * 0.6 +contradiction_score * 0.3 +(1 - resource_score) * 0.1,0, 1)@propertydef tech_maturity(self):return self._tech_maturity@tech_maturity.setterdef tech_maturity(self, value):self._tech_maturity = np.clip(value, 0, 1)self.update_risk_score()class TRIZNineScreenMatrix:"""標準九屏矩陣引擎"""def __init__(self, system_name: str):self.system_name = system_nameself.time_dimensions = ["過去", "現在", "未來"]self.system_levels = ["子系統", "系統", "超系統"]# 構建3x3矩陣self.matrix = [[NineScreenCell(t, l) for l in self.system_levels]for t in self.time_dimensions]# 加載標準矛盾矩陣self.conflict_matrix = self._load_standard_conflict_matrix()def _load_standard_conflict_matrix(self):"""加載TRIZ標準39x39矛盾矩陣"""# 簡化的矛盾矩陣示例(實際需加載完整數據)return pd.DataFrame(np.array([[15, 10, 29, 35, 2],[1, 40, 35, 28, 14],[35, 34, 28, 10, 29],[29, 28, 10, 34, 15],[34, 15, 40, 18, 37]]), # 示例數據index=[1, 5, 13, 24, 33], # 改善參數columns=[1, 5, 13, 24, 33] # 惡化參數)def predict_evolution(self):"""基于時間序列的進化路徑預測"""# 準備訓練數據X, y = [], []for t_idx in range(len(self.time_dimensions) - 1):for l_idx in range(len(self.system_levels)):cell = self.matrix[t_idx][l_idx]X.append([t_idx,l_idx,cell.tech_maturity,len(cell.contradictions)])y.append(len(cell.evolution_stages))# 使用隨機森林進行預測model = RandomForestRegressor(n_estimators=100)model.fit(X, y)# 預測未來進化階段future_idx = self.time_dimensions.index("未來")for l_idx in range(len(self.system_levels)):current_cell = self.matrix[1][l_idx] # 現在時態prediction = model.predict([[future_idx,l_idx,current_cell.tech_maturity,len(current_cell.contradictions)]])stages = [f"階段{int(i + 1)}" for i in range(int(prediction[0]))]self.matrix[future_idx][l_idx].evolution_stages = stages# --------------------------
# 三維可視化引擎
# --------------------------
def plot_nine_screen_3d(matrix):"""標準九屏三維可視化"""time_labels = matrix.time_dimensionslevel_labels = matrix.system_levels# 構建風險曲面數據risk_data = [[cell.risk for cell in row]for row in matrix.matrix]fig = go.Figure(data=go.Surface(z=risk_data,x=time_labels,y=level_labels,colorscale='RdBu_r',opacity=0.9,contours={"z": {"show": True, "usecolormap": True}}))# 添加進化標注annotations = []for t_idx, time in enumerate(time_labels):for l_idx, level in enumerate(level_labels):cell = matrix.matrix[t_idx][l_idx]if cell.evolution_stages:text = f"<b>{cell.system_name}</b><br>" + "<br>".join(cell.evolution_stages[:3])annotations.append({"x": time,"y": level,"z": cell.risk + 0.1,"text": text,"showarrow": False,"font": {"size": 10}})fig.update_layout(scene=dict(xaxis_title='時間維度',yaxis_title='系統層級',zaxis_title='風險指數',camera={"eye": {"x": 1.8, "y": -1.5, "z": 0.8}},annotations=annotations),margin={"l": 0, "r": 0, "b": 0, "t": 30},height=700)return fig# --------------------------
# 主應用界面
# --------------------------
def main():st.set_page_config(page_title="TRIZ九屏分析系統",layout="wide",page_icon="🌐")# 初始化系統if "triz_system" not in st.session_state:st.session_state.triz_system = TRIZNineScreenMatrix("智能電控系統")st.session_state.triz_system.predict_evolution()# 側邊欄控制面板with st.sidebar:st.header("?? 控制中心")system_name = st.text_input("系統名稱", value=st.session_state.triz_system.system_name)# 時空維度選擇col1, col2 = st.columns(2)with col1:selected_time = st.selectbox("時間維度",st.session_state.triz_system.time_dimensions,index=1)with col2:selected_level = st.selectbox("系統層級",st.session_state.triz_system.system_levels,index=1)# 獲取當前單元格t_idx = st.session_state.triz_system.time_dimensions.index(selected_time)l_idx = st.session_state.triz_system.system_levels.index(selected_level)current_cell = st.session_state.triz_system.matrix[t_idx][l_idx]# 技術參數控制with st.expander("🔧 技術參數", expanded=True):current_cell.tech_maturity = st.slider("技術成熟度", 0.0, 1.0,value=current_cell.tech_maturity,key=f"maturity_{t_idx}_{l_idx}")# 資源管理with st.expander("📦 資源分析"):for res_type in current_cell.resources:current_cell.resources[res_type] = st.multiselect(f"{res_type}資源",options=["R1", "R2", "R3", "R4"],default=current_cell.resources[res_type],key=f"res_{res_type}_{t_idx}_{l_idx}")# 模型控制if st.button("🔄 更新預測模型"):st.session_state.triz_system.predict_evolution()st.rerun()# 主顯示區域tab1, tab2 = st.tabs(["三維九屏分析", "矛盾矩陣"])with tab1:st.header(f"{system_name}九屏分析視圖")fig = plot_nine_screen_3d(st.session_state.triz_system)st.plotly_chart(fig, use_container_width=True)with tab2:st.header("標準TRIZ矛盾矩陣")st.dataframe(st.session_state.triz_system.conflict_matrix.style.background_gradient(cmap='Blues').format(precision=0),height=600)# 矛盾分析工具with st.expander("矛盾解析工具"):col1, col2 = st.columns(2)with col1:improve_param = st.selectbox("改善參數",st.session_state.triz_system.conflict_matrix.index)with col2:worsen_param = st.selectbox("惡化參數",st.session_state.triz_system.conflict_matrix.columns)principle = st.session_state.triz_system.conflict_matrix.loc[improve_param, worsen_param]st.success(f"推薦創新原理: 原理{principle}")if __name__ == "__main__":main()