
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()