app.py 108 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403
  1. """
  2. 缺陷集中性分析 - Streamlit 交互式可视化页面
  3. """
  4. import pandas as pd
  5. import numpy as np
  6. import matplotlib
  7. matplotlib.use("Agg")
  8. import matplotlib.pyplot as plt
  9. import matplotlib.font_manager as fm
  10. import seaborn as sns
  11. import streamlit as st
  12. import plotly.express as px
  13. import plotly.graph_objects as go
  14. import os
  15. from datetime import datetime
  16. from sklearn.cluster import DBSCAN
  17. from sklearn.decomposition import PCA
  18. from sklearn.preprocessing import StandardScaler
  19. from defect_analysis.data_quality import build_data_quality_report
  20. from defect_analysis.ml.key_factors import find_key_factors
  21. from app_utils import (
  22. apply_defect_filters,
  23. build_diagnostic_dashboard,
  24. calculate_kpis,
  25. calculate_spc_metrics,
  26. generate_industry_diagnosis,
  27. get_missing_required_columns,
  28. normalize_defect_schema,
  29. TEMPLATE_COLUMNS,
  30. )
  31. # --- 中文字体设置 ---
  32. def setup_chinese_font():
  33. """设置中文字体"""
  34. font_paths = [
  35. r"C:\Windows\Fonts\msyh.ttc", # 微软雅黑
  36. r"C:\Windows\Fonts\simhei.ttf", # 黑体
  37. r"C:\Windows\Fonts\simsun.ttc", # 宋体
  38. r"C:\Windows\Fonts\malgun.ttf", # Malgun Gothic
  39. ]
  40. for fp in font_paths:
  41. if os.path.exists(fp):
  42. font_prop = fm.FontProperties(fname=fp)
  43. plt.rcParams["font.family"] = font_prop.get_name()
  44. plt.rcParams["axes.unicode_minus"] = False
  45. return font_prop
  46. # fallback
  47. plt.rcParams["font.sans-serif"] = ["SimHei", "Microsoft YaHei", "Arial Unicode MS"]
  48. plt.rcParams["axes.unicode_minus"] = False
  49. return None
  50. setup_chinese_font()
  51. # --- 页面配置 ---
  52. st.set_page_config(
  53. page_title="屏幕缺陷集中性分析",
  54. page_icon="🔍",
  55. layout="wide",
  56. initial_sidebar_state="expanded"
  57. )
  58. # --- 侧边栏 ---
  59. st.sidebar.title("🔍 筛选条件")
  60. # --- 数据源切换 ---
  61. st.sidebar.divider()
  62. st.sidebar.subheader("📂 数据源")
  63. data_source = st.sidebar.radio("选择数据源", ["内置模拟数据", "上传CSV文件"], label_visibility="collapsed")
  64. uploaded_df = None
  65. if data_source == "上传CSV文件":
  66. uploaded_file = st.sidebar.file_uploader("上传CSV文件", type=["csv"], accept_multiple_files=False)
  67. if uploaded_file is not None:
  68. try:
  69. uploaded_df = pd.read_csv(uploaded_file, parse_dates=["timestamp"])
  70. uploaded_df["timestamp"] = pd.to_datetime(uploaded_df["timestamp"])
  71. missing = get_missing_required_columns(uploaded_df)
  72. if missing:
  73. st.sidebar.error(f"缺少字段: {', '.join(missing)}")
  74. uploaded_df = None
  75. else:
  76. uploaded_df = normalize_defect_schema(uploaded_df)
  77. st.sidebar.success(f"已加载 {len(uploaded_df)} 条记录")
  78. st.sidebar.caption("已自动补齐缺陷几何、多工序机台、治具和材料批次等可选行业字段")
  79. # 下载模板
  80. template_df = pd.DataFrame(columns=TEMPLATE_COLUMNS)
  81. csv_template = template_df.to_csv(index=False, encoding="utf-8-sig")
  82. st.sidebar.download_button(
  83. label="📋 下载数据格式模板",
  84. data=csv_template,
  85. file_name="defect_data_template.csv",
  86. mime="text/csv"
  87. )
  88. except Exception as e:
  89. st.sidebar.error(f"CSV解析失败: {e}")
  90. uploaded_df = None
  91. else:
  92. st.sidebar.info("请选择一个CSV文件上传")
  93. # --- 加载数据 ---
  94. @st.cache_data(ttl=300)
  95. def load_data_from_csv():
  96. """加载内置模拟数据"""
  97. if not os.path.exists("defect_data.csv"):
  98. st.error("未找到 defect_data.csv,请先运行 generate_data.py 生成数据")
  99. return None
  100. df = pd.read_csv("defect_data.csv", parse_dates=["timestamp"])
  101. return normalize_defect_schema(df)
  102. if data_source == "上传CSV文件" and uploaded_df is not None:
  103. df = uploaded_df
  104. else:
  105. df = load_data_from_csv()
  106. if df is None:
  107. st.stop()
  108. # --- 角色视图 ---
  109. st.sidebar.divider()
  110. st.sidebar.subheader("👤 视图模式")
  111. view_mode = st.sidebar.selectbox(
  112. "选择视图模式",
  113. options=["操作员", "工程师", "管理者"],
  114. index=1,
  115. help="操作员: 基础分析 | 工程师: 全部功能 | 管理者: KPI+SPC+健康评分"
  116. )
  117. # 各角色可见的 Tab
  118. tab_visibility = {
  119. "操作员": {
  120. "tabs": ["🗺️ 空间集中性", "📊 类型集中性 (帕累托)", "📈 时间集中性",
  121. "🏗️ 设备座号集中性", "🔬 缺陷模式识别", "🧭 诊断驾驶舱"],
  122. "show_kpi": True,
  123. "show_export": True,
  124. },
  125. "工程师": {
  126. "tabs": "all",
  127. "show_kpi": True,
  128. "show_export": True,
  129. },
  130. "管理者": {
  131. "tabs": ["🚨 SPC 控制图与预警", "🔬 缺陷模式识别", "💚 设备健康与共性分析",
  132. "📊 类型集中性 (帕累托)", "📈 时间集中性", "🧭 诊断驾驶舱"],
  133. "show_kpi": True,
  134. "show_export": True,
  135. },
  136. }
  137. # 应用 Tab 可见性
  138. current_config = tab_visibility[view_mode]
  139. # --- 筛选条件 ---
  140. # 日期范围
  141. min_date = df["timestamp"].min().date()
  142. max_date = df["timestamp"].max().date()
  143. date_range = st.sidebar.date_input(
  144. "日期范围",
  145. value=[min_date, max_date],
  146. min_value=min_date,
  147. max_value=max_date
  148. )
  149. if len(date_range) == 2:
  150. start_date, end_date = pd.Timestamp(date_range[0]), pd.Timestamp(date_range[1])
  151. else:
  152. start_date, end_date = pd.Timestamp(min_date), pd.Timestamp(max_date)
  153. # 缺陷类型
  154. all_types = sorted(df["defect_type"].unique())
  155. selected_types = st.sidebar.multiselect("缺陷类型", options=all_types, default=all_types)
  156. # 班次
  157. shift_options = ["全部", "白班", "夜班"]
  158. selected_shift = st.sidebar.radio("班次", options=shift_options)
  159. # 批次
  160. all_batches = sorted(df["batch_id"].unique())
  161. selected_batches = st.sidebar.multiselect("批次", options=all_batches, default=all_batches)
  162. # 严重程度
  163. all_severities = ["全部", "轻微", "中等", "严重"]
  164. selected_severity = st.sidebar.selectbox("严重程度", options=all_severities)
  165. # 设备
  166. all_equipment = sorted(df["equipment_id"].unique())
  167. selected_equipment = st.sidebar.multiselect("前贴附设备", options=all_equipment, default=all_equipment)
  168. # 座号(随设备联动)
  169. if selected_equipment:
  170. eq_seats = sorted(df[df["equipment_id"].isin(selected_equipment)]["seat_id"].unique())
  171. selected_seats = st.sidebar.multiselect("座号", options=eq_seats, default=eq_seats)
  172. else:
  173. selected_seats = []
  174. filtered_df = apply_defect_filters(
  175. df,
  176. start_date=start_date,
  177. end_date=end_date,
  178. selected_types=selected_types,
  179. selected_batches=selected_batches,
  180. selected_equipment=selected_equipment,
  181. selected_seats=selected_seats,
  182. selected_shift=selected_shift,
  183. selected_severity=selected_severity,
  184. )
  185. # ========== KPI 看板 ==========
  186. kpis = calculate_kpis(df, filtered_df)
  187. total_panels_inspected = kpis["total_panels_inspected"]
  188. defective_panels = kpis["defective_panels"]
  189. yield_rate = kpis["yield_rate"]
  190. total_defects = kpis["total_defects"]
  191. critical_defects = kpis["critical_defects"]
  192. top_defect_type = kpis["top_defect_type"]
  193. kpi1, kpi2, kpi3, kpi4, kpi5, kpi6 = st.columns(6)
  194. kpi1.metric("检测面板数", f"{total_panels_inspected} 块")
  195. kpi2.metric("不良面板数", f"{defective_panels} 块", delta=f"{defective_panels/total_panels_inspected*100:.1f}%" if total_panels_inspected > 0 else "0%")
  196. kpi3.metric("综合良率", f"{yield_rate:.1f}%", delta=f"{yield_rate - 95:.1f}%", delta_color="normal" if yield_rate >= 95 else "inverse")
  197. kpi4.metric("缺陷总数", f"{total_defects} 个")
  198. kpi5.metric("严重缺陷", f"{critical_defects} 个", delta=f"{critical_defects/max(total_defects,1)*100:.1f}%" if total_defects > 0 else "0%")
  199. kpi6.metric("主要缺陷类型", top_defect_type)
  200. # 第二排 KPI
  201. eq_concentrated = False
  202. if "equipment_id" in filtered_df.columns:
  203. eq_stats = filtered_df.groupby("equipment_id").size()
  204. top_eq = eq_stats.idxmax() if len(eq_stats) > 0 else "-"
  205. top_eq_count = eq_stats.max() if len(eq_stats) > 0 else 0
  206. else:
  207. top_eq, top_eq_count = "-", 0
  208. seat_concentrated = False
  209. if "seat_id" in filtered_df.columns and len(filtered_df) > 0:
  210. seat_stats = filtered_df.groupby("seat_id").size()
  211. if len(seat_stats) > 0:
  212. top_seat = seat_stats.idxmax()
  213. top_seat_count = seat_stats.max()
  214. avg_seat_count = seat_stats.mean()
  215. if top_seat_count > avg_seat_count * 2:
  216. seat_concentrated = True
  217. else:
  218. top_seat, top_seat_count = "-", 0
  219. else:
  220. top_seat, top_seat_count = "-", 0
  221. kpi7, kpi8, kpi9 = st.columns(3)
  222. kpi7.metric("最高缺陷设备", str(top_eq), f"{top_eq_count} 个缺陷")
  223. kpi8.metric("最高缺陷座号", str(top_seat), f"{top_seat_count} 个缺陷")
  224. if seat_concentrated:
  225. kpi9.metric("座号集中性", "⚠️ 存在集中", delta="需关注", delta_color="inverse")
  226. else:
  227. kpi9.metric("座号集中性", "✅ 正常分布")
  228. # --- 主标题 ---
  229. st.title("📊 屏幕缺陷集中性分析系统")
  230. st.markdown(f"**数据范围**: {start_date.strftime('%Y-%m-%d')} ~ {end_date.strftime('%Y-%m-%d')} | "
  231. f"**筛选后缺陷数**: {len(filtered_df)} 条 | "
  232. f"**涉及面板**: {filtered_df['panel_id'].nunique()} 块")
  233. st.divider()
  234. if filtered_df.empty:
  235. st.warning("当前筛选条件下没有缺陷记录,请放宽日期、批次、设备或缺陷类型筛选。")
  236. st.stop()
  237. # --- Tab 布局 (按角色动态) ---
  238. ALL_TABS = [
  239. "🧭 诊断驾驶舱",
  240. "🗺️ 空间集中性",
  241. "📊 类型集中性 (帕累托)",
  242. "📈 时间集中性",
  243. "🏭 批次集中性",
  244. "🏗️ 设备座号集中性",
  245. "🔗 关联分析",
  246. "🧠 智能缺陷聚类 (DBSCAN)",
  247. "🚨 SPC 控制图与预警",
  248. "🔬 缺陷模式识别",
  249. "💚 设备健康与共性分析",
  250. "🔲 多层叠加分析"
  251. ]
  252. if current_config["tabs"] == "all":
  253. visible_tabs = ALL_TABS
  254. else:
  255. visible_tabs = [t for t in ALL_TABS if t in current_config["tabs"]]
  256. tab_containers = st.tabs(visible_tabs)
  257. tab_map = {name: container for name, container in zip(visible_tabs, tab_containers)}
  258. def get_tab(name):
  259. """获取指定 Tab 容器,如果不可见则返回 None"""
  260. return tab_map.get(name)
  261. # ========== Tab 0: 诊断驾驶舱 ==========
  262. _t = get_tab("🧭 诊断驾驶舱")
  263. if _t:
  264. with _t:
  265. dashboard = build_diagnostic_dashboard(filtered_df)
  266. industry_diagnosis = generate_industry_diagnosis(filtered_df, dashboard)
  267. quality_report = build_data_quality_report(filtered_df)
  268. key_factors = find_key_factors(filtered_df, target_defect_type=dashboard["top_defect_type"], top_n=10)
  269. level_colors = {
  270. "严重": ("#7f1d1d", "#fee2e2"),
  271. "关注": ("#92400e", "#fef3c7"),
  272. "正常": ("#14532d", "#dcfce7"),
  273. }
  274. level_fg, level_bg = level_colors.get(dashboard["severity_level"], ("#334155", "#e2e8f0"))
  275. st.markdown(
  276. """
  277. <style>
  278. .diag-hero {
  279. padding: 24px 28px;
  280. border-radius: 24px;
  281. background:
  282. radial-gradient(circle at 15% 15%, rgba(20, 184, 166, .18), transparent 28%),
  283. linear-gradient(135deg, #0f172a 0%, #12343b 52%, #294936 100%);
  284. color: #f8fafc;
  285. box-shadow: 0 18px 45px rgba(15, 23, 42, .18);
  286. margin-bottom: 18px;
  287. }
  288. .diag-hero h2 { margin: 0 0 8px 0; font-size: 30px; letter-spacing: .02em; }
  289. .diag-hero p { margin: 0; color: #cbd5e1; font-size: 15px; }
  290. .diag-badge {
  291. display: inline-flex;
  292. align-items: center;
  293. padding: 6px 12px;
  294. border-radius: 999px;
  295. font-weight: 700;
  296. margin-bottom: 12px;
  297. }
  298. .diag-card {
  299. padding: 18px 18px;
  300. border-radius: 18px;
  301. border: 1px solid #dbe4e7;
  302. background: linear-gradient(180deg, #ffffff 0%, #f8fafc 100%);
  303. min-height: 128px;
  304. }
  305. .diag-card .label { color: #64748b; font-size: 13px; margin-bottom: 8px; }
  306. .diag-card .value { color: #0f172a; font-size: 26px; font-weight: 800; line-height: 1.1; }
  307. .diag-card .hint { color: #475569; font-size: 13px; margin-top: 10px; }
  308. </style>
  309. """,
  310. unsafe_allow_html=True,
  311. )
  312. st.markdown(
  313. f"""
  314. <div class="diag-hero">
  315. <div class="diag-badge" style="color:{level_fg}; background:{level_bg};">
  316. 当前诊断等级:{dashboard["severity_level"]}
  317. </div>
  318. <h2>缺陷诊断驾驶舱</h2>
  319. <p>{dashboard["primary_recommendation"]}</p>
  320. </div>
  321. """,
  322. unsafe_allow_html=True,
  323. )
  324. card1, card2, card3, card4 = st.columns(4)
  325. with card1:
  326. st.markdown(
  327. f"""
  328. <div class="diag-card">
  329. <div class="label">筛选后缺陷</div>
  330. <div class="value">{len(filtered_df)}</div>
  331. <div class="hint">涉及 {filtered_df["panel_id"].nunique()} 块面板</div>
  332. </div>
  333. """,
  334. unsafe_allow_html=True,
  335. )
  336. with card2:
  337. st.markdown(
  338. f"""
  339. <div class="diag-card">
  340. <div class="label">主导缺陷类型</div>
  341. <div class="value">{dashboard["top_defect_type"]}</div>
  342. <div class="hint">占全部缺陷 {dashboard["top_defect_share"]:.1%}</div>
  343. </div>
  344. """,
  345. unsafe_allow_html=True,
  346. )
  347. with card3:
  348. st.markdown(
  349. f"""
  350. <div class="diag-card">
  351. <div class="label">严重缺陷占比</div>
  352. <div class="value">{dashboard["serious_share"]:.1%}</div>
  353. <div class="hint">高于 20% 建议立即复盘</div>
  354. </div>
  355. """,
  356. unsafe_allow_html=True,
  357. )
  358. with card4:
  359. top_root = dashboard["root_causes"].iloc[0] if len(dashboard["root_causes"]) else None
  360. root_name = top_root["根因候选"] if top_root is not None else "-"
  361. root_share = top_root["占比"] if top_root is not None else 0
  362. root_lift = top_root["异常倍数"] if top_root is not None else 0
  363. st.markdown(
  364. f"""
  365. <div class="diag-card">
  366. <div class="label">首要根因候选</div>
  367. <div class="value" style="font-size:22px;">{root_name}</div>
  368. <div class="hint">贡献 {root_share:.1%} 缺陷,异常 {root_lift:.2f}x</div>
  369. </div>
  370. """,
  371. unsafe_allow_html=True,
  372. )
  373. st.markdown(
  374. f"""
  375. <div style="
  376. margin-top: 16px;
  377. padding: 18px 20px;
  378. border-radius: 18px;
  379. border: 1px solid #c7d2fe;
  380. background: linear-gradient(135deg, #eef2ff 0%, #f8fafc 55%, #ecfeff 100%);
  381. ">
  382. <div style="font-size: 13px; color: #475569; font-weight: 700; margin-bottom: 6px;">
  383. 3C 面板行业诊断结论
  384. </div>
  385. <div style="font-size: 18px; color: #0f172a; font-weight: 800;">
  386. {industry_diagnosis["headline"]}
  387. </div>
  388. </div>
  389. """,
  390. unsafe_allow_html=True,
  391. )
  392. diag_col1, diag_col2 = st.columns([1, 1])
  393. with diag_col1:
  394. st.subheader("识别到的缺陷模式")
  395. for pattern in industry_diagnosis["patterns"]:
  396. st.markdown(f"- {pattern}")
  397. with diag_col2:
  398. st.subheader("行业化排查建议")
  399. for idx, recommendation in enumerate(industry_diagnosis["recommendations"], 1):
  400. st.markdown(f"{idx}. {recommendation}")
  401. quality_cols = st.columns(5)
  402. quality_cols[0].metric("数据质量分", f"{quality_report['score']:.1f}")
  403. quality_cols[1].metric("必填完整率", f"{quality_report['required_complete_rate']:.1%}")
  404. quality_cols[2].metric("坐标合法率", f"{quality_report['coordinate_valid_rate']:.1%}")
  405. quality_cols[3].metric("枚举合法率", f"{quality_report['enum_valid_rate']:.1%}")
  406. quality_cols[4].metric("追溯覆盖率", f"{quality_report['traceability_rate']:.1%}")
  407. if quality_report["issues"] != ["数据质量良好"]:
  408. st.warning("数据质量提示:" + ";".join(quality_report["issues"]))
  409. st.divider()
  410. left, right = st.columns([1.25, 1])
  411. with left:
  412. st.subheader("交互式面板数字孪生")
  413. panel_w = float(df["panel_width_mm"].iloc[0])
  414. panel_h = float(df["panel_height_mm"].iloc[0])
  415. fig_map = go.Figure()
  416. fig_map.add_shape(
  417. type="rect",
  418. x0=0,
  419. y0=0,
  420. x1=panel_w,
  421. y1=panel_h,
  422. line=dict(color="#0f172a", width=2),
  423. fillcolor="#f8fafc",
  424. layer="below",
  425. )
  426. fig_map.add_trace(
  427. go.Scatter(
  428. x=filtered_df["x_mm"],
  429. y=filtered_df["y_mm"],
  430. mode="markers",
  431. marker=dict(
  432. size=7,
  433. color=filtered_df["severity"].map({"轻微": 1, "中等": 2, "严重": 3}),
  434. colorscale=[[0, "#38bdf8"], [0.5, "#f59e0b"], [1, "#dc2626"]],
  435. showscale=True,
  436. colorbar=dict(title="严重度"),
  437. opacity=0.72,
  438. line=dict(width=0.4, color="#ffffff"),
  439. ),
  440. text=filtered_df["defect_id"],
  441. customdata=filtered_df[["defect_type", "severity", "equipment_id", "seat_id", "batch_id"]],
  442. hovertemplate=(
  443. "缺陷ID: %{text}<br>"
  444. "坐标: (%{x:.1f}, %{y:.1f}) mm<br>"
  445. "类型: %{customdata[0]}<br>"
  446. "严重度: %{customdata[1]}<br>"
  447. "设备/座号: %{customdata[2]} / %{customdata[3]}<br>"
  448. "批次: %{customdata[4]}<extra></extra>"
  449. ),
  450. name="缺陷点",
  451. )
  452. )
  453. fig_map.add_vrect(x0=0, x1=panel_w * 0.1, fillcolor="#f97316", opacity=0.08, line_width=0)
  454. fig_map.add_vrect(x0=panel_w * 0.9, x1=panel_w, fillcolor="#f97316", opacity=0.08, line_width=0)
  455. fig_map.add_hrect(y0=panel_h * 0.72, y1=panel_h * 0.88, fillcolor="#14b8a6", opacity=0.09, line_width=0)
  456. fig_map.update_layout(
  457. height=560,
  458. margin=dict(l=18, r=18, t=30, b=18),
  459. plot_bgcolor="#ffffff",
  460. paper_bgcolor="#ffffff",
  461. xaxis=dict(title="X (mm)", range=[0, panel_w], showgrid=True, gridcolor="#e2e8f0"),
  462. yaxis=dict(title="Y (mm)", range=[0, panel_h], scaleanchor="x", scaleratio=1, showgrid=True, gridcolor="#e2e8f0"),
  463. title="按真实屏幕比例定位缺陷,橙色为边缘敏感区,青色为 FPC 关注区",
  464. )
  465. st.plotly_chart(fig_map, use_container_width=True)
  466. fig_density = px.density_heatmap(
  467. filtered_df,
  468. x="x_mm",
  469. y="y_mm",
  470. nbinsx=28,
  471. nbinsy=42,
  472. color_continuous_scale="YlOrRd",
  473. title="密度热区视图",
  474. labels={"x_mm": "X (mm)", "y_mm": "Y (mm)"},
  475. )
  476. fig_density.update_layout(height=300, margin=dict(l=18, r=18, t=42, b=18))
  477. st.plotly_chart(fig_density, use_container_width=True)
  478. with right:
  479. st.subheader("根因候选榜")
  480. root_causes = dashboard["root_causes"].copy()
  481. fig_root = px.bar(
  482. root_causes.sort_values("风险分", ascending=True),
  483. x="风险分",
  484. y="根因候选",
  485. orientation="h",
  486. color="异常倍数",
  487. color_continuous_scale="Tealrose",
  488. text="风险分",
  489. hover_data={
  490. "缺陷数": True,
  491. "占比": ":.1%",
  492. "异常倍数": ":.2f",
  493. "涉及面板": True,
  494. "主要缺陷": True,
  495. "严重占比": ":.1%",
  496. "风险分": ":.1f",
  497. },
  498. labels={"风险分": "风险分", "根因候选": ""},
  499. )
  500. fig_root.update_traces(texttemplate="%{text:.1f}", textposition="outside")
  501. fig_root.update_layout(height=360, margin=dict(l=8, r=20, t=20, b=20))
  502. st.plotly_chart(fig_root, use_container_width=True)
  503. root_table = root_causes.copy()
  504. root_table["占比"] = root_table["占比"].map(lambda v: f"{v:.1%}")
  505. root_table["异常倍数"] = root_table["异常倍数"].map(lambda v: f"{v:.2f}x")
  506. root_table["严重占比"] = root_table["严重占比"].map(lambda v: f"{v:.1%}")
  507. st.dataframe(root_table, use_container_width=True, hide_index=True)
  508. st.caption("风险分 = 贡献规模 + 异常倍数 + 严重占比 + 涉及面板数。先查高贡献且高偏离的组合。")
  509. extended_root_causes = dashboard.get("extended_root_causes")
  510. if extended_root_causes is not None and not extended_root_causes.empty:
  511. st.subheader("扩展根因候选")
  512. extended_table = extended_root_causes.copy()
  513. extended_table["占比"] = extended_table["占比"].map(lambda v: f"{v:.1%}")
  514. extended_table["异常倍数"] = extended_table["异常倍数"].map(lambda v: f"{v:.2f}x")
  515. extended_table["严重占比"] = extended_table["严重占比"].map(lambda v: f"{v:.1%}")
  516. st.dataframe(extended_table, use_container_width=True, hide_index=True)
  517. st.caption("覆盖治具、吸嘴、材料批次、清洗/绑定等维度,用于多前制程链路追溯。")
  518. if not key_factors.empty:
  519. st.subheader(f"关键因子分析:{dashboard['top_defect_type']}")
  520. key_factor_table = key_factors.copy()
  521. key_factor_table["目标占比"] = key_factor_table["目标占比"].map(lambda v: f"{v:.1%}")
  522. key_factor_table["基线占比"] = key_factor_table["基线占比"].map(lambda v: f"{v:.1%}")
  523. key_factor_table["异常倍数"] = key_factor_table["异常倍数"].map(lambda v: f"{v:.2f}x")
  524. key_factor_table["支持度"] = key_factor_table["支持度"].map(lambda v: f"{v:.1%}")
  525. st.dataframe(key_factor_table, use_container_width=True, hide_index=True)
  526. st.caption("关键因子按目标缺陷占比、异常倍数、样本数和支持度综合排序。")
  527. trend_col, pareto_col = st.columns([1, 1])
  528. with trend_col:
  529. st.subheader("每日缺陷走势")
  530. daily_trend = dashboard["daily_trend"]
  531. fig_trend_dash = px.area(
  532. daily_trend,
  533. x="day",
  534. y="缺陷数",
  535. markers=True,
  536. color_discrete_sequence=["#0f766e"],
  537. labels={"day": "日期", "缺陷数": "缺陷数"},
  538. )
  539. fig_trend_dash.update_traces(line=dict(width=3), fillcolor="rgba(20, 184, 166, .22)")
  540. fig_trend_dash.update_layout(height=350, margin=dict(l=18, r=18, t=20, b=18))
  541. st.plotly_chart(fig_trend_dash, use_container_width=True)
  542. with pareto_col:
  543. st.subheader("缺陷类型 Pareto")
  544. pareto = dashboard["pareto"].head(8)
  545. fig_pareto_dash = go.Figure()
  546. fig_pareto_dash.add_trace(
  547. go.Bar(
  548. x=pareto["缺陷类型"],
  549. y=pareto["缺陷数"],
  550. marker_color="#334155",
  551. name="缺陷数",
  552. hovertemplate="%{x}<br>缺陷数: %{y}<extra></extra>",
  553. )
  554. )
  555. fig_pareto_dash.add_trace(
  556. go.Scatter(
  557. x=pareto["缺陷类型"],
  558. y=pareto["累计占比"],
  559. yaxis="y2",
  560. mode="lines+markers",
  561. line=dict(color="#dc2626", width=3),
  562. name="累计占比",
  563. hovertemplate="%{x}<br>累计占比: %{y:.1%}<extra></extra>",
  564. )
  565. )
  566. fig_pareto_dash.update_layout(
  567. height=350,
  568. margin=dict(l=18, r=18, t=20, b=18),
  569. yaxis=dict(title="缺陷数"),
  570. yaxis2=dict(title="累计占比", overlaying="y", side="right", tickformat=".0%"),
  571. legend=dict(orientation="h", y=1.12),
  572. )
  573. st.plotly_chart(fig_pareto_dash, use_container_width=True)
  574. # ========== Tab 1: 空间集中性 ==========
  575. _t = get_tab("🗺️ 空间集中性")
  576. if _t:
  577. with _t:
  578. st.header("缺陷空间分布热力图")
  579. col1, col2 = st.columns([2, 1])
  580. with col1:
  581. # 热力图分辨率
  582. grid_size = st.slider("热力图网格分辨率", min_value=5, max_value=50, value=20)
  583. fig, axes = plt.subplots(1, 2, figsize=(14, 6))
  584. # 左图:2D 热力图
  585. x_edges = np.linspace(0, df["panel_width_mm"].iloc[0], grid_size + 1)
  586. y_edges = np.linspace(0, df["panel_height_mm"].iloc[0], grid_size + 1)
  587. H, _, _ = np.histogram2d(
  588. filtered_df["x_mm"], filtered_df["y_mm"],
  589. bins=[x_edges, y_edges]
  590. )
  591. im = axes[0].imshow(
  592. H.T, origin="lower", aspect="auto",
  593. extent=[0, df["panel_width_mm"].iloc[0], 0, df["panel_height_mm"].iloc[0]],
  594. cmap="YlOrRd"
  595. )
  596. axes[0].set_title(f"缺陷密度热力图 (总 {len(filtered_df)} 个)")
  597. axes[0].set_xlabel("X (mm)")
  598. axes[0].set_ylabel("Y (mm)")
  599. plt.colorbar(im, ax=axes[0], label="缺陷数量")
  600. # 右图:散点图(叠加)
  601. axes[1].scatter(
  602. filtered_df["x_mm"], filtered_df["y_mm"],
  603. alpha=0.3, s=5, c="red", edgecolors="none"
  604. )
  605. axes[1].set_title("缺陷位置散点图")
  606. axes[1].set_xlabel("X (mm)")
  607. axes[1].set_ylabel("Y (mm)")
  608. axes[1].set_aspect("equal")
  609. st.pyplot(fig)
  610. plt.close()
  611. with col2:
  612. st.subheader("区域统计")
  613. # 将面板分为 9 宫格
  614. x_bins = pd.cut(filtered_df["x_mm"], bins=3, labels=["左", "中", "右"])
  615. y_bins = pd.cut(filtered_df["y_mm"], bins=3, labels=["上", "中", "下"])
  616. region_df = pd.DataFrame({"X区域": x_bins, "Y区域": y_bins})
  617. region_counts = region_df.groupby(["X区域", "Y区域"], observed=False).size().unstack(fill_value=0)
  618. st.dataframe(region_counts, use_container_width=True)
  619. # 高频缺陷区域 TOP5
  620. st.subheader("高频缺陷区域 TOP5")
  621. region_df["区域"] = region_df["X区域"].astype(str) + "-" + region_df["Y区域"].astype(str)
  622. top_regions = region_df["区域"].value_counts().head(5)
  623. for i, (region, count) in enumerate(top_regions.items(), 1):
  624. st.metric(f"#{i} {region}", f"{count} 个缺陷")
  625. # --- 模拟面板缺陷标注图 ---
  626. st.divider()
  627. st.subheader("🖼️ 模拟面板缺陷标注图")
  628. st.markdown("选择批次和面板,查看缺陷在面板上的实际分布标注(按缺陷类型用不同颜色/形状区分)")
  629. ann_col1, ann_col2, ann_col3 = st.columns(3)
  630. with ann_col1:
  631. ann_batch = st.selectbox("选择批次", options=sorted(filtered_df["batch_id"].unique()), key="ann_batch")
  632. with ann_col2:
  633. panels_in_batch = sorted(filtered_df[filtered_df["batch_id"] == ann_batch]["panel_id"].unique())
  634. ann_panel = st.selectbox("选择面板", options=panels_in_batch, key="ann_panel")
  635. with ann_col3:
  636. ann_show_label = st.checkbox("显示缺陷标签", value=True)
  637. panel_defects = filtered_df[(filtered_df["batch_id"] == ann_batch) & (filtered_df["panel_id"] == ann_panel)]
  638. if len(panel_defects) == 0:
  639. st.warning(f"当前面板 **{ann_panel}** (批次 {ann_batch}) 在筛选条件下无缺陷记录,请调整筛选条件或选择其他面板")
  640. else:
  641. pw = df["panel_width_mm"].iloc[0]
  642. ph = df["panel_height_mm"].iloc[0]
  643. # 缺陷类型 → 颜色/形状映射
  644. type_style = {
  645. "划痕": {"color": "red", "marker": "x", "size": 80},
  646. "亮点": {"color": "yellow", "marker": "o", "size": 60},
  647. "暗点": {"color": "black", "marker": "x", "size": 60},
  648. "气泡": {"color": "cyan", "marker": "o", "size": 100},
  649. "色差": {"color": "magenta", "marker": "s", "size": 70},
  650. "漏光": {"color": "orange", "marker": "D", "size": 80},
  651. "裂纹": {"color": "darkred", "marker": "v", "size": 90},
  652. "异物": {"color": "green", "marker": "P", "size": 80},
  653. }
  654. fig_ann, ax_ann = plt.subplots(figsize=(3.5, 5))
  655. # 面板背景(模拟屏幕灰色渐变)
  656. ax_ann.add_patch(plt.Rectangle((0, 0), pw, ph, facecolor="#1a1a2e", edgecolor="#444", linewidth=2))
  657. # 内框(模拟屏幕可视区域)
  658. margin = 8
  659. ax_ann.add_patch(plt.Rectangle((margin, margin), pw - 2*margin, ph - 2*margin,
  660. facecolor="#16213e", edgecolor="#0f3460", linewidth=1.5))
  661. # FPC绑定区域标注
  662. fpc_y = ph * 0.7
  663. ax_ann.axhline(y=fpc_y, color="#555", linestyle="--", alpha=0.4, linewidth=0.5)
  664. ax_ann.text(pw/2, fpc_y + 2, "FPC区", color="#666", fontsize=7, ha="center", alpha=0.5)
  665. # 绘制缺陷标注
  666. for _, row in panel_defects.iterrows():
  667. style = type_style.get(row["defect_type"], {"color": "white", "marker": "o", "size": 50})
  668. severity_size = {"轻微": 0.7, "中等": 1.0, "严重": 1.4}.get(row["severity"], 1.0)
  669. ax_ann.scatter(row["x_mm"], row["y_mm"],
  670. c=style["color"], marker=style["marker"],
  671. s=style["size"] * severity_size,
  672. edgecolors="white", linewidth=0.3, alpha=0.85, zorder=3)
  673. if ann_show_label:
  674. ax_ann.annotate(row["defect_type"][:2],
  675. (row["x_mm"], row["y_mm"]),
  676. fontsize=5, color="white",
  677. ha="center", va="bottom", alpha=0.7, zorder=4)
  678. # 图例
  679. legend_elements = [plt.Line2D([0], [0], marker=type_style[t]["marker"], color="w",
  680. markerfacecolor=type_style[t]["color"], markersize=8,
  681. label=t, markeredgewidth=0.5, markeredgecolor="white")
  682. for t in type_style]
  683. ax_ann.legend(handles=legend_elements, loc="upper right", fontsize=7,
  684. framealpha=0.7, facecolor="#222", edgecolor="#555")
  685. ax_ann.set_xlim(-5, pw + 5)
  686. ax_ann.set_ylim(-5, ph + 5)
  687. ax_ann.set_title(f"面板 {ann_panel} | 批次 {ann_batch} | {len(panel_defects)} 个缺陷",
  688. fontsize=11, pad=10)
  689. ax_ann.set_xlabel("X (mm)")
  690. ax_ann.set_ylabel("Y (mm)")
  691. ax_ann.set_aspect("equal")
  692. ax_ann.grid(True, alpha=0.1, color="gray")
  693. st.pyplot(fig_ann)
  694. plt.close()
  695. # ========== Tab 2: 帕累托分析 ==========
  696. _t = get_tab("📊 类型集中性 (帕累托)")
  697. if _t:
  698. with _t:
  699. st.header("缺陷类型帕累托分析")
  700. type_counts = filtered_df["defect_type"].value_counts().reset_index()
  701. type_counts.columns = ["缺陷类型", "数量"]
  702. type_counts = type_counts.sort_values("数量", ascending=False).reset_index(drop=True)
  703. type_counts["累计占比"] = type_counts["数量"].cumsum() / type_counts["数量"].sum() * 100
  704. type_counts["占比"] = type_counts["数量"] / type_counts["数量"].sum() * 100
  705. fig, ax1 = plt.subplots(figsize=(10, 5))
  706. # 柱状图
  707. bars = ax1.bar(type_counts["缺陷类型"], type_counts["数量"], color="steelblue", alpha=0.8)
  708. ax1.set_xlabel("缺陷类型")
  709. ax1.set_ylabel("数量", color="steelblue")
  710. ax1.set_title("帕累托图 - 缺陷类型分布")
  711. # 累计占比折线
  712. ax2 = ax1.twinx()
  713. ax2.plot(type_counts["缺陷类型"], type_counts["累计占比"], color="red", marker="o", linewidth=2)
  714. ax2.axhline(y=80, color="green", linestyle="--", alpha=0.5, label="80%线")
  715. ax2.set_ylabel("累计占比 (%)", color="red")
  716. ax2.set_ylim(0, 110)
  717. # 标注数值
  718. for bar, count in zip(bars, type_counts["数量"]):
  719. ax1.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 2,
  720. str(count), ha="center", va="bottom", fontsize=9)
  721. st.pyplot(fig)
  722. plt.close()
  723. # 数据表格
  724. st.subheader("详细数据")
  725. st.dataframe(type_counts, use_container_width=True)
  726. # 严重程度分布
  727. st.subheader("按严重程度分布")
  728. sev_counts = filtered_df["severity"].value_counts()
  729. fig2, ax = plt.subplots(figsize=(6, 4))
  730. colors = {"轻微": "#4CAF50", "中等": "#FF9800", "严重": "#F44336"}
  731. sev_counts.plot(kind="bar", ax=ax, color=[colors.get(s, "gray") for s in sev_counts.index])
  732. ax.set_title("缺陷严重程度分布")
  733. ax.set_ylabel("数量")
  734. st.pyplot(fig2)
  735. plt.close()
  736. # ========== Tab 3: 时间集中性 ==========
  737. _t = get_tab("📈 时间集中性")
  738. if _t:
  739. with _t:
  740. st.header("缺陷时间分布趋势")
  741. col1, col2 = st.columns(2)
  742. with col1:
  743. # 按天趋势
  744. daily = filtered_df.groupby("day").size().reset_index(name="缺陷数")
  745. daily["day"] = pd.to_datetime(daily["day"])
  746. fig1, ax1 = plt.subplots(figsize=(10, 4))
  747. ax1.plot(daily["day"], daily["缺陷数"], marker="o", markersize=3, linewidth=1.5, color="steelblue")
  748. ax1.fill_between(daily["day"], daily["缺陷数"], alpha=0.2, color="steelblue")
  749. ax1.set_title("每日缺陷数量趋势")
  750. ax1.set_ylabel("缺陷数量")
  751. ax1.tick_params(axis="x", rotation=45)
  752. # 移动平均
  753. if len(daily) > 3:
  754. daily["移动平均(3天)"] = daily["缺陷数"].rolling(window=3, min_periods=1).mean()
  755. ax1.plot(daily["day"], daily["移动平均(3天)"], color="red", linestyle="--",
  756. linewidth=2, alpha=0.7, label="3日移动平均")
  757. ax1.legend()
  758. st.pyplot(fig1)
  759. plt.close()
  760. with col2:
  761. # 按小时分布
  762. hourly = filtered_df.groupby("hour").size().reindex(range(24), fill_value=0)
  763. fig2, ax2 = plt.subplots(figsize=(10, 4))
  764. colors = ["#FF6B6B" if (h >= 17 or h < 8) else "#4ECDC4" for h in hourly.index]
  765. ax2.bar(hourly.index, hourly.values, color=colors, alpha=0.8)
  766. ax2.set_title("每小时缺陷分布 (红色=夜班)")
  767. ax2.set_xlabel("小时")
  768. ax2.set_ylabel("缺陷数量")
  769. st.pyplot(fig2)
  770. plt.close()
  771. # 班次对比
  772. st.subheader("班次对比")
  773. shift_stats = filtered_df.groupby("shift").agg({
  774. "defect_id": "count",
  775. "panel_id": "nunique"
  776. }).rename(columns={"defect_id": "缺陷数", "panel_id": "涉及面板数"})
  777. st.dataframe(shift_stats, use_container_width=True)
  778. # 每周分布
  779. st.subheader("按星期分布")
  780. filtered_df_copy = filtered_df.copy()
  781. filtered_df_copy["weekday"] = filtered_df_copy["timestamp"].dt.day_name()
  782. weekday_order = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
  783. weekday_cn = {"Monday": "周一", "Tuesday": "周二", "Wednesday": "周三",
  784. "Thursday": "周四", "Friday": "周五", "Saturday": "周六", "Sunday": "周日"}
  785. filtered_df_copy["星期"] = filtered_df_copy["weekday"].map(weekday_cn)
  786. weekday_counts = filtered_df_copy.groupby("星期").size().reindex(
  787. [weekday_cn[d] for d in weekday_order], fill_value=0
  788. )
  789. fig3, ax3 = plt.subplots(figsize=(8, 4))
  790. ax3.bar(range(7), weekday_counts.values, color="steelblue", alpha=0.8)
  791. ax3.set_xticks(range(7))
  792. ax3.set_xticklabels(weekday_counts.index)
  793. ax3.set_title("按星期分布")
  794. ax3.set_ylabel("缺陷数量")
  795. st.pyplot(fig3)
  796. plt.close()
  797. # ========== Tab 4: 批次集中性 ==========
  798. _t = get_tab("🏭 批次集中性")
  799. if _t:
  800. with _t:
  801. st.header("批次缺陷集中性分析")
  802. batch_stats = filtered_df.groupby("batch_id").agg({
  803. "defect_id": "count",
  804. "panel_id": "nunique",
  805. "severity": lambda x: (x == "严重").sum()
  806. }).rename(columns={"defect_id": "缺陷数", "panel_id": "面板数", "severity": "严重缺陷数"})
  807. batch_stats["缺陷率"] = batch_stats["缺陷数"] / batch_stats["面板数"]
  808. batch_stats = batch_stats.sort_index()
  809. col1, col2 = st.columns(2)
  810. with col1:
  811. fig1, ax1 = plt.subplots(figsize=(10, 4))
  812. ax1.bar(range(len(batch_stats)), batch_stats["缺陷数"], color="steelblue", alpha=0.8)
  813. ax1.set_title("各批次缺陷数量")
  814. ax1.set_xlabel("批次")
  815. ax1.set_ylabel("缺陷数")
  816. ax1.set_xticks(range(len(batch_stats)))
  817. ax1.set_xticklabels(batch_stats.index, rotation=90, fontsize=7)
  818. st.pyplot(fig1)
  819. plt.close()
  820. with col2:
  821. fig2, ax2 = plt.subplots(figsize=(10, 4))
  822. ax2.plot(range(len(batch_stats)), batch_stats["缺陷率"], marker="o", markersize=3,
  823. color="red", linewidth=1.5)
  824. ax2.axhline(y=batch_stats["缺陷率"].mean(), color="green", linestyle="--",
  825. label=f"平均缺陷率: {batch_stats['缺陷率'].mean():.2%}")
  826. ax2.set_title("各批次缺陷率趋势")
  827. ax2.set_xlabel("批次")
  828. ax2.set_ylabel("缺陷率")
  829. ax2.set_xticks(range(len(batch_stats)))
  830. ax2.set_xticklabels(batch_stats.index, rotation=90, fontsize=7)
  831. ax2.legend()
  832. st.pyplot(fig2)
  833. plt.close()
  834. # 异常批次
  835. st.subheader("异常批次 (缺陷率 > 平均值 + 1倍标准差)")
  836. threshold = batch_stats["缺陷率"].mean() + batch_stats["缺陷率"].std()
  837. abnormal = batch_stats[batch_stats["缺陷率"] > threshold].sort_values("缺陷率", ascending=False)
  838. if len(abnormal) > 0:
  839. st.dataframe(abnormal, use_container_width=True)
  840. else:
  841. st.success("未发现异常批次")
  842. # ========== Tab 5: 设备座号集中性 ==========
  843. _t = get_tab("🏗️ 设备座号集中性")
  844. if _t:
  845. with _t:
  846. st.header("🏗️ 前贴附制程设备座号集中性分析")
  847. st.markdown(
  848. "分析缺陷是否集中在特定设备的特定座号(工位)。"
  849. "如果某个座号缺陷明显多于其他座号,说明该座号对应的设备局部存在问题(如吸嘴老化、加热不均、压力异常等)。"
  850. )
  851. # --- 设备对比 ---
  852. st.subheader("设备级别对比")
  853. eq_stats = filtered_df.groupby("equipment_id").agg({
  854. "defect_id": "count",
  855. "panel_id": "nunique",
  856. "severity": lambda x: (x == "严重").sum()
  857. }).rename(columns={"defect_id": "缺陷数", "panel_id": "面板数", "severity": "严重缺陷"})
  858. eq_stats["缺陷率"] = eq_stats["缺陷数"] / eq_stats["面板数"]
  859. eq_stats = eq_stats.sort_values("缺陷数", ascending=False)
  860. col_eq1, col_eq2 = st.columns(2)
  861. with col_eq1:
  862. fig_eq1, ax_eq1 = plt.subplots(figsize=(8, 4))
  863. bars1 = ax_eq1.bar(range(len(eq_stats)), eq_stats["缺陷数"], color=["#FF6B6B", "#4ECDC4", "#45B7D1"][:len(eq_stats)], alpha=0.8)
  864. ax_eq1.set_xticks(range(len(eq_stats)))
  865. ax_eq1.set_xticklabels(eq_stats.index, fontsize=10)
  866. ax_eq1.set_ylabel("缺陷数量")
  867. ax_eq1.set_title("各设备缺陷总数")
  868. for bar, count in zip(bars1, eq_stats["缺陷数"]):
  869. ax_eq1.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 3,
  870. str(count), ha="center", va="bottom", fontsize=10, fontweight="bold")
  871. st.pyplot(fig_eq1)
  872. plt.close()
  873. with col_eq2:
  874. fig_eq2, ax_eq2 = plt.subplots(figsize=(8, 4))
  875. bars2 = ax_eq2.bar(range(len(eq_stats)), eq_stats["缺陷率"] * 100,
  876. color=["#FF6B6B", "#4ECDC4", "#45B7D1"][:len(eq_stats)], alpha=0.8)
  877. ax_eq2.set_xticks(range(len(eq_stats)))
  878. ax_eq2.set_xticklabels(eq_stats.index, fontsize=10)
  879. ax_eq2.set_ylabel("缺陷率 (%)")
  880. ax_eq2.set_title("各设备缺陷率")
  881. for bar, rate in zip(bars2, eq_stats["缺陷率"] * 100):
  882. ax_eq2.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.3,
  883. f"{rate:.1f}%", ha="center", va="bottom", fontsize=10, fontweight="bold")
  884. st.pyplot(fig_eq2)
  885. plt.close()
  886. st.dataframe(eq_stats, use_container_width=True)
  887. # --- 座号级别分析 ---
  888. st.divider()
  889. st.subheader("座号级别缺陷分布")
  890. # 选择设备查看座号
  891. eq_for_seat = st.selectbox("选择设备查看座号分布", options=sorted(filtered_df["equipment_id"].unique()), key="eq_seat")
  892. eq_data = filtered_df[filtered_df["equipment_id"] == eq_for_seat]
  893. eq_info = None
  894. for eq_name, info in [("LAM-A01", {"rows": 4, "cols": 5}), ("LAM-A02", {"rows": 4, "cols": 5}), ("LAM-B01", {"rows": 5, "cols": 4})]:
  895. if eq_name == eq_for_seat:
  896. eq_info = info
  897. break
  898. seat_counts = eq_data.groupby("seat_id").size().reset_index(name="缺陷数")
  899. seat_counts = seat_counts.sort_values("缺陷数", ascending=False)
  900. if eq_info:
  901. # 网格热力图
  902. grid = np.zeros((eq_info["rows"], eq_info["cols"]))
  903. seat_to_defects = eq_data.groupby("seat_id").size().to_dict()
  904. for r in range(1, eq_info["rows"] + 1):
  905. for c in range(1, eq_info["cols"] + 1):
  906. seat_name = f"R{r}C{c}"
  907. grid[r - 1, c - 1] = seat_to_defects.get(seat_name, 0)
  908. fig_grid, ax_grid = plt.subplots(figsize=(8, 6))
  909. im = ax_grid.imshow(grid, cmap="YlOrRd", aspect="equal")
  910. ax_grid.set_title(f"{eq_for_seat} 座号缺陷热力图")
  911. ax_grid.set_xlabel("列号")
  912. ax_grid.set_ylabel("行号")
  913. ax_grid.set_xticks(range(eq_info["cols"]))
  914. ax_grid.set_xticklabels([f"C{i+1}" for i in range(eq_info["cols"])])
  915. ax_grid.set_yticks(range(eq_info["rows"]))
  916. ax_grid.set_yticklabels([f"R{i+1}" for i in range(eq_info["rows"])])
  917. # 标注数值
  918. for r in range(eq_info["rows"]):
  919. for c in range(eq_info["cols"]):
  920. val = int(grid[r, c])
  921. color = "white" if val > grid.max() * 0.7 else "black"
  922. ax_grid.text(c, r, str(val), ha="center", va="center", fontsize=10,
  923. color=color, fontweight="bold")
  924. plt.colorbar(im, ax=ax_grid, label="缺陷数量")
  925. st.pyplot(fig_grid)
  926. plt.close()
  927. else:
  928. fig_bar, ax_bar = plt.subplots(figsize=(10, 4))
  929. ax_bar.bar(range(len(seat_counts)), seat_counts["缺陷数"], color="steelblue", alpha=0.8)
  930. ax_bar.set_xticks(range(len(seat_counts)))
  931. ax_bar.set_xticklabels(seat_counts["seat_id"], rotation=45, fontsize=8)
  932. ax_bar.set_ylabel("缺陷数量")
  933. ax_bar.set_title("座号缺陷分布")
  934. st.pyplot(fig_bar)
  935. plt.close()
  936. # 座号数据表格
  937. st.dataframe(seat_counts, use_container_width=True)
  938. # --- 异常座号检测 ---
  939. st.divider()
  940. st.subheader("异常座号检测")
  941. all_seat_stats = filtered_df.groupby(["equipment_id", "seat_id"]).size().reset_index(name="缺陷数")
  942. overall_mean = all_seat_stats["缺陷数"].mean()
  943. overall_std = all_seat_stats["缺陷数"].std()
  944. threshold_1x = overall_mean + overall_std
  945. threshold_2x = overall_mean + 2 * overall_std
  946. st.info(f"📊 全局统计: 平均每个座号 **{overall_mean:.1f}** 个缺陷 | 标准差 **{overall_std:.1f}**")
  947. col_anom1, col_anom2 = st.columns(2)
  948. with col_anom1:
  949. st.markdown(f"**⚠️ 1σ 预警座号** (缺陷数 > {threshold_1x:.0f})")
  950. warning_seats = all_seat_stats[all_seat_stats["缺陷数"] > threshold_1x].sort_values("缺陷数", ascending=False)
  951. if len(warning_seats) > 0:
  952. st.dataframe(warning_seats.reset_index(drop=True), use_container_width=True)
  953. else:
  954. st.success("无预警座号")
  955. with col_anom2:
  956. st.markdown(f"**🔴 2σ 异常座号** (缺陷数 > {threshold_2x:.0f})")
  957. critical_seats = all_seat_stats[all_seat_stats["缺陷数"] > threshold_2x].sort_values("缺陷数", ascending=False)
  958. if len(critical_seats) > 0:
  959. st.dataframe(critical_seats.reset_index(drop=True), use_container_width=True)
  960. else:
  961. st.success("无异常座号")
  962. # --- 座号 × 缺陷类型 交叉分析 ---
  963. st.divider()
  964. st.subheader("座号 × 缺陷类型 交叉分析")
  965. st.markdown("识别哪些座号偏向产生特定类型的缺陷(如 R2C3 座号主要产生气泡 → 吸嘴问题)")
  966. if eq_info:
  967. eq_seat_type = eq_data.groupby(["seat_id", "defect_type"]).size().unstack(fill_value=0)
  968. fig_ct, ax_ct = plt.subplots(figsize=(10, 6))
  969. sns.heatmap(eq_seat_type, annot=True, fmt="d", cmap="YlOrRd", ax=ax_ct,
  970. linewidths=0.5, linecolor="white")
  971. ax_ct.set_title(f"{eq_for_seat} 座号 × 缺陷类型 热力图")
  972. st.pyplot(fig_ct)
  973. plt.close()
  974. # ========== Tab 6: 关联分析 ==========
  975. _t = get_tab("🔗 关联分析")
  976. if _t:
  977. with _t:
  978. st.header("缺陷关联分析")
  979. col1, col2 = st.columns(2)
  980. with col1:
  981. # 缺陷类型 x 严重程度 交叉表
  982. ct = pd.crosstab(filtered_df["defect_type"], filtered_df["severity"])
  983. fig1, ax1 = plt.subplots(figsize=(8, 5))
  984. sns.heatmap(ct, annot=True, fmt="d", cmap="YlOrRd", ax=ax1,
  985. linewidths=0.5, linecolor="white")
  986. ax1.set_title("缺陷类型 × 严重程度 热力图")
  987. st.pyplot(fig1)
  988. plt.close()
  989. with col2:
  990. # 缺陷类型 x 班次 交叉表
  991. ct2 = pd.crosstab(filtered_df["defect_type"], filtered_df["shift"])
  992. fig2, ax2 = plt.subplots(figsize=(8, 5))
  993. sns.heatmap(ct2, annot=True, fmt="d", cmap="Blues", ax=ax2,
  994. linewidths=0.5, linecolor="white")
  995. ax2.set_title("缺陷类型 × 班次 热力图")
  996. st.pyplot(fig2)
  997. plt.close()
  998. # 面板缺陷 TOP10
  999. st.subheader("缺陷最多的面板 TOP10")
  1000. panel_defects = filtered_df.groupby("panel_id").agg({
  1001. "defect_id": "count",
  1002. "defect_type": lambda x: x.mode().iloc[0] if len(x) > 0 else "N/A"
  1003. }).rename(columns={"defect_id": "缺陷数", "defect_type": "主要缺陷类型"})
  1004. panel_defects = panel_defects.sort_values("缺陷数", ascending=False).head(10)
  1005. st.dataframe(panel_defects, use_container_width=True)
  1006. # 面板缺陷分布
  1007. fig3, ax3 = plt.subplots(figsize=(8, 4))
  1008. panel_counts = filtered_df.groupby("panel_id").size()
  1009. ax3.hist(panel_counts, bins=20, color="steelblue", alpha=0.8, edgecolor="white")
  1010. ax3.set_title("单面板缺陷数量分布")
  1011. ax3.set_xlabel("缺陷数/面板")
  1012. ax3.set_ylabel("面板数量")
  1013. ax3.axvline(x=panel_counts.mean(), color="red", linestyle="--", label=f"平均: {panel_counts.mean():.1f}")
  1014. ax3.legend()
  1015. st.pyplot(fig3)
  1016. plt.close()
  1017. # --- 智能缺陷聚类 (DBSCAN + PCA) ---
  1018. _t = get_tab("🧠 智能缺陷聚类 (DBSCAN)")
  1019. if _t:
  1020. with _t:
  1021. st.header("🧠 DBSCAN 智能缺陷空间聚类")
  1022. st.markdown(
  1023. "**原理**: DBSCAN 是基于密度的空间聚类算法,能自动识别任意形状的缺陷聚集区域,"
  1024. "无需预设聚类数量,自动过滤随机散落的噪声缺陷。"
  1025. "行业标准:半导体晶圆/面板缺陷模式识别首选算法。"
  1026. )
  1027. col1, col2 = st.columns([2, 1])
  1028. with col1:
  1029. # --- 参数控制 ---
  1030. st.subheader("参数设置")
  1031. p_col1, p_col2 = st.columns(2)
  1032. with p_col1:
  1033. eps = st.slider(
  1034. "eps (邻域半径 mm)",
  1035. min_value=5.0, max_value=100.0, value=25.0, step=5.0,
  1036. help="两个点被视为'邻居'的最大距离。值越大,簇越大。"
  1037. )
  1038. with p_col2:
  1039. min_samples = st.slider(
  1040. "min_samples (最小簇点数)",
  1041. min_value=3, max_value=50, value=10,
  1042. help="形成一个簇所需的最小点数。值越大,越严格的聚集才算簇。"
  1043. )
  1044. # --- 执行聚类 ---
  1045. coords = filtered_df[["x_mm", "y_mm"]].values
  1046. scaler = StandardScaler()
  1047. coords_scaled = scaler.fit_transform(coords)
  1048. dbscan = DBSCAN(eps=eps / scaler.scale_[0], min_samples=min_samples)
  1049. filtered_df["cluster"] = dbscan.fit_predict(coords_scaled)
  1050. # 统计聚类结果
  1051. n_clusters = len(set(dbscan.labels_)) - (1 if -1 in dbscan.labels_ else 0)
  1052. n_noise = list(dbscan.labels_).count(-1)
  1053. st.info(f"📊 **聚类结果**: 发现 **{n_clusters}** 个缺陷聚集区域,**{n_noise}** 个噪声点(随机散落缺陷)")
  1054. # --- 可视化 ---
  1055. fig, axes = plt.subplots(1, 2, figsize=(14, 6))
  1056. # 左图:聚类结果(空间位置)
  1057. labels = filtered_df["cluster"].values
  1058. unique_labels = set(labels)
  1059. colors = plt.cm.get_cmap("tab20", len(unique_labels) if len(unique_labels) > 0 else 1)
  1060. for k in unique_labels:
  1061. if k == -1:
  1062. # 噪声点
  1063. xy = filtered_df[labels == k][["x_mm", "y_mm"]].values
  1064. axes[0].scatter(xy[:, 0], xy[:, 1], c="lightgray", s=3, alpha=0.3, label="噪声")
  1065. else:
  1066. xy = filtered_df[labels == k][["x_mm", "y_mm"]].values
  1067. axes[0].scatter(xy[:, 0], xy[:, 1], c=[colors(k)], s=15, alpha=0.7,
  1068. label=f"簇 {k+1} ({len(xy)} 点)")
  1069. axes[0].set_title(f"DBSCAN 空间聚类结果 (eps={eps}, min_samples={min_samples})")
  1070. axes[0].set_xlabel("X (mm)")
  1071. axes[0].set_ylabel("Y (mm)")
  1072. axes[0].set_aspect("equal")
  1073. axes[0].legend(fontsize=7, loc="upper right", ncol=2)
  1074. # 右图:PCA 降维可视化(加入更多特征维度)
  1075. if len(filtered_df) > 2:
  1076. # 构建多维特征:x, y, hour, defect_type编码, severity编码
  1077. feature_df = filtered_df[["x_mm", "y_mm", "hour"]].copy()
  1078. # 缺陷类型编码
  1079. type_map = {t: i for i, t in enumerate(filtered_df["defect_type"].unique())}
  1080. feature_df["type_code"] = filtered_df["defect_type"].map(type_map).astype(float)
  1081. # 严重程度编码
  1082. sev_map = {"轻微": 0, "中等": 1, "严重": 2}
  1083. feature_df["sev_code"] = filtered_df["severity"].map(sev_map).astype(float)
  1084. features = feature_df.values
  1085. features_scaled = StandardScaler().fit_transform(features)
  1086. # PCA 降维到 2D
  1087. n_components = min(2, features_scaled.shape[1])
  1088. pca = PCA(n_components=n_components)
  1089. pca_result = pca.fit_transform(features_scaled)
  1090. explained_var = pca.explained_variance_ratio_
  1091. for k in unique_labels:
  1092. mask_k = labels == k
  1093. if k == -1:
  1094. axes[1].scatter(pca_result[mask_k, 0], pca_result[mask_k, 1],
  1095. c="lightgray", s=3, alpha=0.3, label="噪声")
  1096. else:
  1097. axes[1].scatter(pca_result[mask_k, 0], pca_result[mask_k, 1],
  1098. c=[colors(k)], s=15, alpha=0.7, label=f"簇 {k+1}")
  1099. axes[1].set_title(
  1100. f"PCA 多维特征降维\n"
  1101. f"PC1: {explained_var[0]*100:.1f}% | PC2: {explained_var[1]*100:.1f}%"
  1102. )
  1103. axes[1].set_xlabel("主成分 1")
  1104. axes[1].set_ylabel("主成分 2")
  1105. axes[1].legend(fontsize=7, loc="upper right")
  1106. st.pyplot(fig)
  1107. plt.close()
  1108. # --- 簇特征统计 ---
  1109. if n_clusters > 0:
  1110. st.divider()
  1111. st.subheader("各簇特征分析")
  1112. cluster_data = []
  1113. for k in sorted([c for c in unique_labels if c != -1]):
  1114. cluster_df = filtered_df[labels == k]
  1115. cluster_data.append({
  1116. "簇编号": k + 1,
  1117. "缺陷数量": len(cluster_df),
  1118. "占比": f"{len(cluster_df)/len(filtered_df)*100:.1f}%",
  1119. "中心X(mm)": round(cluster_df["x_mm"].mean(), 1),
  1120. "中心Y(mm)": round(cluster_df["y_mm"].mean(), 1),
  1121. "X范围": f"{cluster_df['x_mm'].min():.0f}~{cluster_df['x_mm'].max():.0f}",
  1122. "Y范围": f"{cluster_df['y_mm'].min():.0f}~{cluster_df['y_mm'].max():.0f}",
  1123. "主要缺陷": cluster_df["defect_type"].mode().iloc[0] if len(cluster_df) > 0 else "-",
  1124. "主要严重度": cluster_df["severity"].mode().iloc[0] if len(cluster_df) > 0 else "-",
  1125. "涉及批次": cluster_df["batch_id"].nunique(),
  1126. "涉及面板": cluster_df["panel_id"].nunique(),
  1127. })
  1128. st.dataframe(pd.DataFrame(cluster_data), use_container_width=True)
  1129. with col2:
  1130. # --- 聚类结果说明 ---
  1131. st.subheader("📖 结果解读")
  1132. st.markdown(
  1133. f"""
  1134. **当前参数**: eps={eps}mm, min_samples={min_samples}
  1135. **聚类统计**:
  1136. - 缺陷聚集区域: {n_clusters} 个
  1137. - 随机散落噪声: {n_noise} 个
  1138. - 噪声占比: {n_noise/len(filtered_df)*100:.1f}%
  1139. **参数调优建议**:
  1140. - **eps 调大** → 簇数量减少,簇变大
  1141. - **eps 调小** → 簇数量增加,更精细
  1142. - **min_samples 调大** → 只有高度密集区域才算簇
  1143. - **min_samples 调小** → 更多区域被识别为簇
  1144. **工业应用**:
  1145. - 每个"簇"代表一个**系统性缺陷源**
  1146. (如某台设备、某道工序、某个物料批次)
  1147. - "噪声"点是随机缺陷,通常无需特别关注
  1148. - 重点关注**缺陷数量多、涉及批次集中**的簇
  1149. """
  1150. )
  1151. # --- 簇分布饼图 ---
  1152. if n_clusters > 0:
  1153. st.subheader("簇规模分布")
  1154. cluster_counts = filtered_df[labels >= 0]["cluster"].value_counts().sort_index()
  1155. fig_pie, ax_pie = plt.subplots(figsize=(5, 5))
  1156. pie_labels = [f"簇{i+1}" for i in cluster_counts.index]
  1157. ax_pie.pie(cluster_counts.values, labels=pie_labels, autopct="%1.1f%%",
  1158. colors=plt.cm.tab20.colors[:len(cluster_counts)], startangle=90)
  1159. ax_pie.set_title("各簇缺陷占比")
  1160. st.pyplot(fig_pie)
  1161. plt.close()
  1162. # --- DBSCAN vs K-Means 对比 ---
  1163. st.subheader("为什么选 DBSCAN?")
  1164. st.markdown(
  1165. """
  1166. | 维度 | DBSCAN | K-Means |
  1167. |------|--------|---------|
  1168. | 形状适应 | ✅ 任意形状 | ❌ 仅球形 |
  1169. | 预设K值 | ❌ 不需要 | ✅ 必须 |
  1170. | 噪声处理 | ✅ 自动过滤 | ❌ 干扰聚类 |
  1171. | 环形/线形缺陷 | ✅ 能识别 | ❌ 识别不了 |
  1172. """
  1173. )
  1174. # ========== Tab 8: SPC 控制图与预警 ==========
  1175. _t = get_tab("🚨 SPC 控制图与预警")
  1176. if _t:
  1177. with _t:
  1178. st.header("🚨 SPC 统计过程控制")
  1179. st.markdown(
  1180. "基于统计过程控制(SPC)方法,监控每日缺陷率是否在控制限内,"
  1181. "自动检测异常趋势并给出改善/恶化结论。"
  1182. )
  1183. # --- 数据准备:按天计算缺陷率 ---
  1184. # 需要知道每天检测了多少面板才能算缺陷率
  1185. # 用 batch_id 近似日期
  1186. spc_metrics = calculate_spc_metrics(df)
  1187. daily_all = spc_metrics["daily"]
  1188. if len(daily_all) < 2:
  1189. st.warning("数据天数不足,无法生成控制图")
  1190. else:
  1191. # 控制限计算
  1192. p_bar = spc_metrics["p_bar"]
  1193. sigma_p = spc_metrics["sigma_p"]
  1194. UCL = spc_metrics["ucl"]
  1195. LCL = spc_metrics["lcl"]
  1196. UWL = spc_metrics["uwl"]
  1197. LWL = spc_metrics["lwl"]
  1198. # --- Western Electric 规则检测 ---
  1199. we_violations = []
  1200. # 规则1: 单点超出 3σ 控制限
  1201. for i, row in daily_all.iterrows():
  1202. if row["defect_rate"] > UCL or row["defect_rate"] < LCL:
  1203. we_violations.append({
  1204. "日期": row["day"].strftime("%Y-%m-%d"),
  1205. "规则": "Rule 1: 超出3σ控制限",
  1206. "值": f"{row['defect_rate']:.2%}"
  1207. })
  1208. # 规则2: 连续7点上升或下降
  1209. rates = daily_all["defect_rate"].values
  1210. if len(rates) >= 7:
  1211. for i in range(len(rates) - 6):
  1212. window = rates[i:i+7]
  1213. if all(window[j] < window[j+1] for j in range(6)):
  1214. we_violations.append({
  1215. "日期": daily_all.loc[i+6, "day"].strftime("%Y-%m-%d"),
  1216. "规则": "Rule 2: 连续7点上升",
  1217. "值": f"{rates[i]:.2%} → {rates[i+6]:.2%}"
  1218. })
  1219. elif all(window[j] > window[j+1] for j in range(6)):
  1220. we_violations.append({
  1221. "日期": daily_all.loc[i+6, "day"].strftime("%Y-%m-%d"),
  1222. "规则": "Rule 2: 连续7点下降",
  1223. "值": f"{rates[i]:.2%} → {rates[i+6]:.2%}"
  1224. })
  1225. # 规则3: 连续7点在中心线同一侧
  1226. for i in range(len(rates) - 6):
  1227. window = rates[i:i+7]
  1228. if all(v > p_bar for v in window):
  1229. we_violations.append({
  1230. "日期": daily_all.loc[i+6, "day"].strftime("%Y-%m-%d"),
  1231. "规则": "Rule 3: 连续7点在CL上方",
  1232. "值": f"持续偏高"
  1233. })
  1234. elif all(v < p_bar for v in window):
  1235. we_violations.append({
  1236. "日期": daily_all.loc[i+6, "day"].strftime("%Y-%m-%d"),
  1237. "规则": "Rule 3: 连续7点在CL下方",
  1238. "值": f"持续偏低"
  1239. })
  1240. # --- 趋势分析 ---
  1241. from numpy.polynomial import polynomial as P
  1242. x = np.arange(len(daily_all))
  1243. coeffs = np.polyfit(x, rates, 1)
  1244. slope = coeffs[0]
  1245. daily_all["trend"] = np.polyval(coeffs, x)
  1246. if abs(slope) < sigma_p * 0.1:
  1247. trend_status = "稳定"
  1248. trend_icon = "➡️"
  1249. trend_color = "normal"
  1250. elif slope > 0:
  1251. trend_status = "恶化中"
  1252. trend_icon = "📈"
  1253. trend_color = "inverse"
  1254. else:
  1255. trend_status = "改善中"
  1256. trend_icon = "📉"
  1257. trend_color = "normal"
  1258. # --- KPI 行 ---
  1259. kpi_spc1, kpi_spc2, kpi_spc3, kpi_spc4 = st.columns(4)
  1260. kpi_spc1.metric("平均缺陷率", f"{p_bar:.2%}")
  1261. kpi_spc2.metric("控制限 (UCL/LCL)", f"{UCL:.2%} / {LCL:.2%}")
  1262. kpi_spc3.metric("趋势判断", f"{trend_icon} {trend_status}", delta=f"斜率: {slope*100:.3f}%/天", delta_color=trend_color)
  1263. kpi_spc4.metric("Western Electric 告警", f"{len(we_violations)} 次", delta="需关注" if len(we_violations) > 0 else "正常")
  1264. # --- 控制图 ---
  1265. st.divider()
  1266. st.subheader("X-bar 控制图 (每日缺陷率)")
  1267. fig_spc, ax_spc = plt.subplots(figsize=(14, 5))
  1268. # 数据点
  1269. ax_spc.plot(daily_all["day"], daily_all["defect_rate"],
  1270. marker="o", markersize=4, linewidth=1.5, color="steelblue", label="日缺陷率")
  1271. ax_spc.fill_between(daily_all["day"], daily_all["defect_rate"], alpha=0.15, color="steelblue")
  1272. # 控制限线
  1273. ax_spc.axhline(y=p_bar, color="green", linestyle="-", linewidth=1.5, label=f"CL (中心线): {p_bar:.2%}")
  1274. ax_spc.axhline(y=UCL, color="red", linestyle="--", linewidth=1, label=f"UCL: {UCL:.2%}")
  1275. ax_spc.axhline(y=LCL, color="red", linestyle="--", linewidth=1, label=f"LCL: {LCL:.2%}")
  1276. ax_spc.axhline(y=UWL, color="orange", linestyle=":", linewidth=1, alpha=0.6, label=f"UWL (2σ): {UWL:.2%}")
  1277. ax_spc.axhline(y=LWL, color="orange", linestyle=":", linewidth=1, alpha=0.6, label=f"LWL (2σ): {LWL:.2%}")
  1278. # 标注异常点
  1279. for v in we_violations:
  1280. if "Rule 1" in v["规则"]:
  1281. anomaly_date = pd.Timestamp(v["日期"])
  1282. val = float(v["值"].rstrip("%")) / 100
  1283. ax_spc.annotate("⚠️", (anomaly_date, val), fontsize=12,
  1284. ha="center", va="bottom", color="red")
  1285. ax_spc.set_title("SPC 控制图 - 每日缺陷率")
  1286. ax_spc.set_ylabel("缺陷率")
  1287. ax_spc.tick_params(axis="x", rotation=45)
  1288. ax_spc.legend(fontsize=8, loc="upper right")
  1289. ax_spc.grid(True, alpha=0.3)
  1290. st.pyplot(fig_spc)
  1291. plt.close()
  1292. # --- 趋势图 ---
  1293. st.subheader("缺陷率趋势 (含线性回归)")
  1294. fig_trend, ax_trend = plt.subplots(figsize=(14, 4))
  1295. ax_trend.plot(daily_all["day"], daily_all["defect_rate"],
  1296. marker="o", markersize=3, linewidth=1.5, color="steelblue", label="日缺陷率")
  1297. ax_trend.plot(daily_all["day"], daily_all["trend"],
  1298. color="red", linestyle="--", linewidth=2, label=f"趋势线 (斜率: {slope*100:.3f}%/天)")
  1299. ax_trend.fill_between(daily_all["day"], daily_all["defect_rate"], alpha=0.1, color="steelblue")
  1300. ax_trend.axhline(y=p_bar, color="green", linestyle="--", alpha=0.5, label=f"平均: {p_bar:.2%}")
  1301. ax_trend.set_ylabel("缺陷率")
  1302. ax_trend.tick_params(axis="x", rotation=45)
  1303. ax_trend.legend(fontsize=8)
  1304. ax_trend.grid(True, alpha=0.3)
  1305. st.pyplot(fig_trend)
  1306. plt.close()
  1307. # --- 告警清单 ---
  1308. st.divider()
  1309. st.subheader("⚠️ Western Electric 规则告警清单")
  1310. if we_violations:
  1311. we_df = pd.DataFrame(we_violations)
  1312. st.dataframe(we_df, use_container_width=True)
  1313. st.warning(f"共发现 **{len(we_violations)}** 次统计异常,建议关注对应日期的工艺参数和人员排班")
  1314. else:
  1315. st.success("✅ 未触发 Western Electric 规则告警,过程处于统计控制状态")
  1316. # --- 结论 ---
  1317. st.divider()
  1318. st.subheader("📋 过程能力结论")
  1319. if trend_status == "改善中":
  1320. st.success(
  1321. f"**趋势改善中** 📉\n\n"
  1322. f"每日缺陷率以平均 {abs(slope)*100:.3f}%/天 的速度下降。\n"
  1323. f"当前平均缺陷率为 {p_bar:.2%},控制上限 {UCL:.2%}。\n"
  1324. f"{'已触发' if we_violations else '未触发'} Western Electric 规则告警。"
  1325. )
  1326. elif trend_status == "恶化中":
  1327. st.error(
  1328. f"**趋势恶化中** 📈\n\n"
  1329. f"每日缺陷率以平均 {slope*100:.3f}%/天 的速度上升。\n"
  1330. f"当前平均缺陷率为 {p_bar:.2%},控制上限 {UCL:.2%}。\n"
  1331. f"{'已触发' if we_violations else '未触发'} Western Electric 规则告警。\n\n"
  1332. f"建议:检查近期工艺参数变化、设备状态和原材料批次。"
  1333. )
  1334. else:
  1335. st.info(
  1336. f"**过程稳定** ➡️\n\n"
  1337. f"缺陷率趋势平稳,斜率 {slope*100:.3f}%/天,无显著上升或下降。\n"
  1338. f"当前平均缺陷率为 {p_bar:.2%},控制限 [{LCL:.2%}, {UCL:.2%}]。\n"
  1339. f"{'已触发' if we_violations else '未触发'} Western Electric 规则告警。"
  1340. )
  1341. # ========== 重复缺陷坐标检测 ==========
  1342. _t = get_tab("🗺️ 空间集中性")
  1343. if _t:
  1344. with _t:
  1345. st.divider()
  1346. st.subheader("🎯 重复缺陷坐标检测")
  1347. st.markdown(
  1348. "检测在不同面板上重复出现的缺陷坐标。随机缺陷不会在同一位置反复出现,"
  1349. "而设备硬伤(如吸嘴划伤、夹具压痕)会在相同位置持续产生缺陷。"
  1350. "这是从'描述分析'跨入'根因诊断'的关键一步。"
  1351. )
  1352. # 坐标分桶:将面板划分为网格,找出跨面板重复的缺陷桶
  1353. repeat_bin_size = st.slider("坐标分桶大小 (mm)", min_value=5, max_value=50, value=15, step=5,
  1354. help="将坐标按此大小分桶,同一桶内出现于不同面板的缺陷视为'重复'")
  1355. pw = df["panel_width_mm"].iloc[0]
  1356. ph = df["panel_height_mm"].iloc[0]
  1357. # 计算桶ID
  1358. df_copy = filtered_df.copy()
  1359. df_copy["x_bin"] = (df_copy["x_mm"] // repeat_bin_size).astype(int)
  1360. df_copy["y_bin"] = (df_copy["y_mm"] // repeat_bin_size).astype(int)
  1361. df_copy["bin_key"] = df_copy["x_bin"].astype(str) + "_" + df_copy["y_bin"].astype(str)
  1362. # 统计每个桶出现在多少不同面板上
  1363. bin_panels = df_copy.groupby("bin_key").agg(
  1364. panel_count=("panel_id", "nunique"),
  1365. defect_count=("defect_id", "count"),
  1366. x_center=("x_mm", "mean"),
  1367. y_center=("y_mm", "mean"),
  1368. dominant_type=("defect_type", lambda x: x.mode().iloc[0] if len(x) > 0 else "-"),
  1369. dominant_severity=("severity", lambda x: x.mode().iloc[0] if len(x) > 0 else "-"),
  1370. ).reset_index()
  1371. repeat_threshold = st.slider("重复判定阈值 (跨面板数)", min_value=2, max_value=10, value=3)
  1372. repeated_bins = bin_panels[bin_panels["panel_count"] >= repeat_threshold].sort_values("panel_count", ascending=False)
  1373. col_repeat1, col_repeat2 = st.columns([1, 2])
  1374. with col_repeat1:
  1375. st.metric("重复缺陷桶数", f"{len(repeated_bins)}",
  1376. delta=f"阈值: ≥{repeat_threshold} 块面板")
  1377. if len(repeated_bins) > 0:
  1378. st.dataframe(
  1379. repeated_bins[["panel_count", "defect_count", "x_center", "y_center", "dominant_type", "dominant_severity"]]
  1380. .rename(columns={"panel_count": "涉及面板", "defect_count": "缺陷总数",
  1381. "x_center": "中心X", "y_center": "中心Y",
  1382. "dominant_type": "主要类型", "dominant_severity": "主要严重度"}),
  1383. use_container_width=True, height=400
  1384. )
  1385. else:
  1386. st.info(f"未发现跨 {repeat_threshold}+ 块面板的重复缺陷坐标")
  1387. with col_repeat2:
  1388. if len(repeated_bins) > 0:
  1389. # 在面板图上标注重复缺陷桶
  1390. fig_repeat, ax_repeat = plt.subplots(figsize=(4, 6))
  1391. # 面板背景
  1392. ax_repeat.add_patch(plt.Rectangle((0, 0), pw, ph, facecolor="#1a1a2e", edgecolor="#444", linewidth=2))
  1393. ax_repeat.add_patch(plt.Rectangle((8, 8), pw-16, ph-16, facecolor="#16213e", edgecolor="#0f3460", linewidth=1.5))
  1394. # 所有缺陷散点(淡)
  1395. ax_repeat.scatter(filtered_df["x_mm"], filtered_df["y_mm"],
  1396. alpha=0.1, s=2, c="gray", edgecolors="none", zorder=1)
  1397. # 重复缺陷桶标注重叠圈
  1398. max_count = repeated_bins["panel_count"].max()
  1399. for _, row in repeated_bins.iterrows():
  1400. size = 100 + (row["panel_count"] / max_count) * 400
  1401. ax_repeat.scatter(row["x_center"], row["y_center"],
  1402. s=size, c="red", alpha=0.3, edgecolors="red",
  1403. linewidth=2, zorder=3)
  1404. ax_repeat.text(row["x_center"], row["y_center"],
  1405. str(row["panel_count"]), ha="center", va="center",
  1406. fontsize=8, color="white", fontweight="bold", zorder=4)
  1407. ax_repeat.set_xlim(-5, pw + 5)
  1408. ax_repeat.set_ylim(-5, ph + 5)
  1409. ax_repeat.set_title(f"重复缺陷坐标 (≥{repeat_threshold} 块面板)", fontsize=11)
  1410. ax_repeat.set_xlabel("X (mm)")
  1411. ax_repeat.set_ylabel("Y (mm)")
  1412. ax_repeat.set_aspect("equal")
  1413. ax_repeat.grid(True, alpha=0.1, color="gray")
  1414. st.pyplot(fig_repeat)
  1415. plt.close()
  1416. else:
  1417. st.info("调整分桶大小或阈值以检测重复缺陷")
  1418. # ========== Tab 9: 缺陷模式识别 ==========
  1419. _t = get_tab("🔬 缺陷模式识别")
  1420. if _t:
  1421. with _t:
  1422. st.header("🔬 缺陷空间模式自动识别")
  1423. st.markdown(
  1424. "参考 WM811K 晶圆缺陷图谱分类标准,对每块面板的缺陷分布进行模式评分。"
  1425. "不同模式对应不同的根因机制(如边缘型→贴合工艺,角落型→夹具应力,"
  1426. "中心型→压力不均,线条型→机械刮伤,随机型→来料污染)。"
  1427. )
  1428. from scipy.spatial import ConvexHull
  1429. from scipy.spatial.distance import cdist
  1430. pw = df["panel_width_mm"].iloc[0]
  1431. ph = df["panel_height_mm"].iloc[0]
  1432. # 按面板分组,逐块分析模式
  1433. panel_groups = filtered_df.groupby("panel_id")
  1434. patterns_results = []
  1435. for panel_id, panel_data in panel_groups:
  1436. if len(panel_data) < 3:
  1437. continue
  1438. coords = panel_data[["x_mm", "y_mm"]].values
  1439. # 归一化坐标到 [0,1]
  1440. x_norm = panel_data["x_mm"].values / pw
  1441. y_norm = panel_data["y_mm"].values / ph
  1442. # --- 模式1: 边缘型 (缺陷靠近面板四边) ---
  1443. # 计算每个点到最近边缘的距离比例
  1444. edge_dist = np.minimum(np.minimum(x_norm, 1 - x_norm),
  1445. np.minimum(y_norm, 1 - y_norm))
  1446. edge_ratio = (edge_dist < 0.12).mean() # 12% 以内的点视为边缘点
  1447. edge_score = edge_ratio
  1448. # --- 模式2: 角落型 (缺陷集中在四个角落) ---
  1449. corner_threshold = 0.15 # 15% 范围
  1450. in_corner = (
  1451. ((x_norm < corner_threshold) & (y_norm < corner_threshold)) | # 左下
  1452. ((x_norm < corner_threshold) & (y_norm > 1 - corner_threshold)) | # 左上
  1453. ((x_norm > 1 - corner_threshold) & (y_norm < corner_threshold)) | # 右下
  1454. ((x_norm > 1 - corner_threshold) & (y_norm > 1 - corner_threshold)) # 右上
  1455. )
  1456. corner_score = in_corner.mean()
  1457. # --- 模式3: 中心型 (缺陷集中在面板中心区域) ---
  1458. center_x, center_y = 0.5, 0.5
  1459. dist_to_center = np.sqrt((x_norm - center_x)**2 + (y_norm - center_y)**2)
  1460. center_radius = 0.18 # 18% 半径
  1461. center_score = (dist_to_center < center_radius).mean()
  1462. # --- 模式4: 线条型 (缺陷沿一条线分布) ---
  1463. # 用 PCA 第一主成分占比来判断线性程度
  1464. if len(coords) >= 3:
  1465. from sklearn.decomposition import PCA
  1466. pca = PCA(n_components=2)
  1467. pca.fit(coords)
  1468. linearity = pca.explained_variance_ratio_[0] # 第一主成分占比
  1469. line_score = linearity
  1470. else:
  1471. line_score = 0
  1472. # --- 模式5: 随机型 (均匀分布,无明显模式) ---
  1473. # 用空间变异系数:将面板分为网格,计算各格缺陷数的变异系数
  1474. grid_n = 5
  1475. x_edges = np.linspace(0, pw, grid_n + 1)
  1476. y_edges = np.linspace(0, ph, grid_n + 1)
  1477. H, _, _ = np.histogram2d(panel_data["x_mm"].values, panel_data["y_mm"].values,
  1478. bins=[x_edges, y_edges])
  1479. if H.sum() > 0 and H.std() > 0:
  1480. cv = H.std() / H.mean() if H.mean() > 0 else 999
  1481. # cv 越小越均匀(随机)
  1482. randomness_score = max(0, 1 - cv / 3) # 归一化到 [0,1]
  1483. else:
  1484. randomness_score = 0
  1485. # --- 主导模式判定 ---
  1486. scores = {
  1487. "边缘型": edge_score,
  1488. "角落型": corner_score,
  1489. "中心型": center_score,
  1490. "线条型": line_score,
  1491. "随机型": randomness_score,
  1492. }
  1493. dominant_pattern = max(scores, key=scores.get)
  1494. patterns_results.append({
  1495. "面板ID": panel_id,
  1496. "缺陷数": len(panel_data),
  1497. "主导模式": dominant_pattern,
  1498. "边缘型": round(edge_score, 2),
  1499. "角落型": round(corner_score, 2),
  1500. "中心型": round(center_score, 2),
  1501. "线条型": round(line_score, 2),
  1502. "随机型": round(randomness_score, 2),
  1503. })
  1504. if patterns_results:
  1505. pattern_df = pd.DataFrame(patterns_results)
  1506. # --- 模式统计 ---
  1507. col_pat1, col_pat2, col_pat3 = st.columns([1, 1, 2])
  1508. with col_pat1:
  1509. pattern_counts = pattern_df["主导模式"].value_counts()
  1510. fig_pat, ax_pat = plt.subplots(figsize=(8, 5))
  1511. colors_pat = {"边缘型": "#FF6B6B", "角落型": "#FFA500", "中心型": "#4ECDC4",
  1512. "线条型": "#9B59B6", "随机型": "#95A5A6"}
  1513. bars = ax_pat.bar(pattern_counts.index, pattern_counts.values,
  1514. color=[colors_pat.get(p, "#888") for p in pattern_counts.index],
  1515. alpha=0.8)
  1516. for bar, count in zip(bars, pattern_counts.values):
  1517. ax_pat.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.5,
  1518. str(count), ha="center", va="bottom", fontsize=11, fontweight="bold")
  1519. ax_pat.set_title("缺陷模式分布")
  1520. ax_pat.set_ylabel("面板数量")
  1521. st.pyplot(fig_pat)
  1522. plt.close()
  1523. with col_pat2:
  1524. st.subheader("模式占比")
  1525. total_panels = len(pattern_df)
  1526. for pattern in ["边缘型", "角落型", "中心型", "线条型", "随机型"]:
  1527. count = (pattern_df["主导模式"] == pattern).sum()
  1528. pct = count / total_panels * 100
  1529. st.metric(pattern, f"{count} 块", f"{pct:.1f}%")
  1530. with col_pat3:
  1531. # --- 模式-根因映射 ---
  1532. st.subheader("模式 → 可能根因")
  1533. root_cause_map = {
  1534. "边缘型": {
  1535. "可能原因": "贴合工艺参数异常、边缘夹具压力不均、涂胶厚度不均",
  1536. "建议排查": "检查贴合压力、边缘密封工艺、涂胶均匀性"
  1537. },
  1538. "角落型": {
  1539. "可能原因": "夹具应力集中、面板放置定位偏差、角落散热不良",
  1540. "建议排查": "检查夹具对齐、面板定位精度、角落温度分布"
  1541. },
  1542. "中心型": {
  1543. "可能原因": "压力中心不均、FPC绑定区域工艺异常、中心温度过高",
  1544. "建议排查": "检查压力分布曲线、FPC绑定参数、加热板温度"
  1545. },
  1546. "线条型": {
  1547. "可能原因": "机械刮伤、传送带划痕、清洗刷毛磨损、吸嘴移动轨迹",
  1548. "建议排查": "检查传送带状态、清洗设备、吸嘴运动轨迹"
  1549. },
  1550. "随机型": {
  1551. "可能原因": "来料污染、环境尘埃、化学药液杂质",
  1552. "建议排查": "检查洁净室等级、来料检验记录、药液过滤状态"
  1553. },
  1554. }
  1555. for pattern in ["边缘型", "角落型", "中心型", "线条型", "随机型"]:
  1556. count = (pattern_df["主导模式"] == pattern).sum()
  1557. if count == 0:
  1558. continue
  1559. rc = root_cause_map[pattern]
  1560. with st.expander(f"{pattern} ({count} 块面板)"):
  1561. st.markdown(f"**可能原因**: {rc['可能原因']}")
  1562. st.markdown(f"**建议排查**: {rc['建议排查']}")
  1563. # --- 详细数据表 ---
  1564. st.divider()
  1565. st.subheader("面板模式评分明细")
  1566. st.dataframe(pattern_df, use_container_width=True, height=400)
  1567. else:
  1568. st.warning("当前筛选条件下无足够面板数据进行模式分析(需至少 3 个缺陷/面板)")
  1569. # ========== Tab 10: 设备健康与共性分析 ==========
  1570. _t = get_tab("💚 设备健康与共性分析")
  1571. if _t:
  1572. with _t:
  1573. st.header("💚 设备健康评分 & 共性分析")
  1574. st.markdown(
  1575. "综合评估各台设备的健康状态,并在发现异常批次时自动分析其共性特征。"
  1576. )
  1577. # --- 设备健康评分 ---
  1578. st.subheader("设备健康评分 (0-100)")
  1579. st.markdown("评分维度:缺陷率(40%) + 座号集中度(30%) + 严重度分布(30%)")
  1580. health_data = []
  1581. for eq_id in sorted(df["equipment_id"].unique()):
  1582. eq_all = df[df["equipment_id"] == eq_id]
  1583. eq_filtered = filtered_df[filtered_df["equipment_id"] == eq_id]
  1584. # 维度1: 缺陷率评分 (40%)
  1585. eq_panels = eq_all["panel_id"].nunique()
  1586. eq_defects = len(eq_all)
  1587. eq_defect_rate = eq_defects / max(eq_panels, 1)
  1588. # 缺陷率越低分越高,线性归一化
  1589. # 以 5 个缺陷/面板为最差(0分),0 为最好(100分)
  1590. rate_score = max(0, 100 * (1 - eq_defect_rate / 5))
  1591. # 维度2: 座号集中度评分 (30%)
  1592. # 座号分布越均匀分越高,集中分越低
  1593. eq_seat_counts = eq_all.groupby("seat_id").size()
  1594. if len(eq_seat_counts) > 1:
  1595. seat_cv = eq_seat_counts.std() / max(eq_seat_counts.mean(), 0.001)
  1596. # cv 越小越均匀,得分越高
  1597. seat_score = max(0, 100 * (1 - seat_cv / 3))
  1598. else:
  1599. seat_score = 50
  1600. # 维度3: 严重度评分 (30%)
  1601. eq_sev = eq_all["severity"].value_counts()
  1602. severe_ratio = eq_sev.get("严重", 0) / max(len(eq_all), 1)
  1603. sev_score = max(0, 100 * (1 - severe_ratio * 3)) # 严重占比 33% 时为 0 分
  1604. # 综合得分
  1605. total_score = rate_score * 0.4 + seat_score * 0.3 + sev_score * 0.3
  1606. health_data.append({
  1607. "设备ID": eq_id,
  1608. "缺陷总数": eq_defects,
  1609. "缺陷率": f"{eq_defect_rate:.2f}",
  1610. "座号集中度(CV)": f"{seat_cv:.2f}" if len(eq_seat_counts) > 1 else "N/A",
  1611. "严重占比": f"{severe_ratio:.1%}",
  1612. "缺陷率分(40%)": round(rate_score, 1),
  1613. "座号分(30%)": round(seat_score, 1),
  1614. "严重度分(30%)": round(sev_score, 1),
  1615. "健康总分": round(total_score, 1),
  1616. })
  1617. health_df = pd.DataFrame(health_data).sort_values("健康总分", ascending=False)
  1618. # 显示健康评分
  1619. col_h1, col_h2 = st.columns([3, 2])
  1620. with col_h1:
  1621. st.dataframe(health_df, use_container_width=True, hide_index=True)
  1622. with col_h2:
  1623. # 可视化排名
  1624. fig_health, ax_health = plt.subplots(figsize=(6, 4))
  1625. health_sorted = health_df.sort_values("健康总分", ascending=True)
  1626. colors_health = ["#4CAF50" if s >= 70 else "#FF9800" if s >= 40 else "#F44336"
  1627. for s in health_sorted["健康总分"]]
  1628. bars = ax_health.barh(health_sorted["设备ID"], health_sorted["健康总分"],
  1629. color=colors_health, alpha=0.8, height=0.5)
  1630. for bar, score in zip(bars, health_sorted["健康总分"]):
  1631. ax_health.text(bar.get_width() + 1, bar.get_y() + bar.get_height()/2,
  1632. f"{score:.0f}", ha="left", va="center", fontsize=12, fontweight="bold")
  1633. ax_health.set_xlabel("健康评分 (0-100)")
  1634. ax_health.set_title("设备健康排名")
  1635. ax_health.set_xlim(0, 110)
  1636. st.pyplot(fig_health)
  1637. plt.close()
  1638. # --- 共性分析 ---
  1639. st.divider()
  1640. st.subheader("🔍 异常批次共性分析")
  1641. st.markdown("选中异常批次后,自动分析这些批次的共同特征(设备/时段/座号/缺陷类型)。")
  1642. # 自动检测异常批次(基于缺陷率)
  1643. batch_stats = df.groupby("batch_id").agg(
  1644. defects=("defect_id", "count"),
  1645. panels=("panel_id", "nunique")
  1646. )
  1647. batch_stats["defect_rate"] = batch_stats["defects"] / batch_stats["panels"]
  1648. threshold = batch_stats["defect_rate"].mean() + batch_stats["defect_rate"].std()
  1649. abnormal_batches = batch_stats[batch_stats["defect_rate"] > threshold].index.tolist()
  1650. st.info(f"自动检测到的异常批次 (缺陷率 > {threshold:.2%}): **{len(abnormal_batches)}** 个")
  1651. st.write(", ".join(abnormal_batches[:10]))
  1652. if abnormal_batches:
  1653. col_c1, col_c2 = st.columns(2)
  1654. with col_c1:
  1655. # 选择要分析的批次
  1656. selected_abnormal = st.multiselect(
  1657. "选择要分析的异常批次",
  1658. options=abnormal_batches,
  1659. default=abnormal_batches[:3] if len(abnormal_batches) >= 3 else abnormal_batches,
  1660. key="commonality_batch"
  1661. )
  1662. if selected_abnormal:
  1663. abnormal_df = df[df["batch_id"].isin(selected_abnormal)]
  1664. normal_df = df[~df["batch_id"].isin(selected_abnormal)]
  1665. st.divider()
  1666. st.markdown(f"**分析对象**: {len(selected_abnormal)} 个异常批次, "
  1667. f"{len(abnormal_df)} 条缺陷记录")
  1668. # 共性分析:设备
  1669. st.subheader("共性特征 TOP3")
  1670. col_common1, col_common2, col_common3 = st.columns(3)
  1671. with col_common1:
  1672. # 设备共性
  1673. abnormal_eq_rate = abnormal_df.groupby("equipment_id").size() / len(abnormal_df)
  1674. normal_eq_rate = normal_df.groupby("equipment_id").size() / len(normal_df)
  1675. eq_boost = {}
  1676. for eq in abnormal_df["equipment_id"].unique():
  1677. a_rate = abnormal_eq_rate.get(eq, 0)
  1678. n_rate = normal_eq_rate.get(eq, 0)
  1679. if n_rate > 0:
  1680. eq_boost[eq] = (a_rate - n_rate) / n_rate * 100
  1681. else:
  1682. eq_boost[eq] = 999
  1683. eq_top = sorted(eq_boost.items(), key=lambda x: x[1], reverse=True)[:3]
  1684. st.markdown("**设备共用性**")
  1685. for eq, boost in eq_top:
  1686. st.markdown(f"- {eq}: 异常占比 {abnormal_eq_rate.get(eq, 0):.1%}, "
  1687. f"相对正常 **+{boost:.0f}%**")
  1688. with col_common2:
  1689. # 时段共性
  1690. abnormal_hour = abnormal_df.groupby("hour").size() / len(abnormal_df)
  1691. normal_hour = normal_df.groupby("hour").size() / len(normal_df)
  1692. # 按班次聚合
  1693. abnormal_shift = abnormal_df.groupby("shift").size() / len(abnormal_df)
  1694. normal_shift = normal_df.groupby("shift").size() / len(normal_df)
  1695. st.markdown("**时段共性**")
  1696. for shift in ["白班", "夜班"]:
  1697. a_rate = abnormal_shift.get(shift, 0)
  1698. n_rate = normal_shift.get(shift, 0)
  1699. if n_rate > 0:
  1700. boost = (a_rate - n_rate) / n_rate * 100
  1701. else:
  1702. boost = 999
  1703. st.markdown(f"- {shift}: 异常占比 {a_rate:.1%}, "
  1704. f"相对正常 **{'+' if boost > 0 else ''}{boost:.0f}%**")
  1705. with col_common3:
  1706. # 座号共性
  1707. abnormal_seat = abnormal_df.groupby("seat_id").size() / len(abnormal_df)
  1708. normal_seat = normal_df.groupby("seat_id").size() / len(normal_df)
  1709. seat_boost = {}
  1710. for seat in abnormal_df["seat_id"].unique():
  1711. a_rate = abnormal_seat.get(seat, 0)
  1712. n_rate = normal_seat.get(seat, 0)
  1713. if n_rate > 0:
  1714. seat_boost[seat] = (a_rate - n_rate) / n_rate * 100
  1715. else:
  1716. seat_boost[seat] = 999
  1717. seat_top = sorted(seat_boost.items(), key=lambda x: x[1], reverse=True)[:3]
  1718. st.markdown("**座号共性**")
  1719. for seat, boost in seat_top:
  1720. st.markdown(f"- {seat}: 异常占比 {abnormal_seat.get(seat, 0):.1%}, "
  1721. f"相对正常 **+{boost:.0f}%**")
  1722. # --- 缺陷类型偏差 ---
  1723. st.subheader("异常批次缺陷类型偏差")
  1724. abnormal_type = abnormal_df.groupby("defect_type").size() / len(abnormal_df)
  1725. normal_type = normal_df.groupby("defect_type").size() / len(normal_df)
  1726. type_diff = []
  1727. for t in set(list(abnormal_type.index) + list(normal_type.index)):
  1728. a_rate = abnormal_type.get(t, 0)
  1729. n_rate = normal_type.get(t, 0)
  1730. type_diff.append({
  1731. "缺陷类型": t,
  1732. "异常占比": f"{a_rate:.1%}",
  1733. "正常占比": f"{n_rate:.1%}",
  1734. "偏差": f"{'+' if a_rate > n_rate else ''}{(a_rate - n_rate) / max(n_rate, 0.001) * 100:.0f}%",
  1735. })
  1736. st.dataframe(pd.DataFrame(type_diff).sort_values("偏差", key=lambda x: x.str.rstrip("%").astype(float), ascending=False),
  1737. use_container_width=True, hide_index=True)
  1738. # ========== Tab 11: 多层叠加分析 ==========
  1739. _t = get_tab("🔲 多层叠加分析")
  1740. if _t:
  1741. with _t:
  1742. st.header("🔲 多层叠加分析")
  1743. st.markdown(
  1744. "将缺陷数据与面板物理区域、设备座号、时间维度叠加在同一视图上,"
  1745. "揭示单一维度看不到的深层关联。"
  1746. )
  1747. pw = df["panel_width_mm"].iloc[0]
  1748. ph = df["panel_height_mm"].iloc[0]
  1749. # --- 自定义区域定义 ---
  1750. st.subheader("📐 自定义区域缺陷统计")
  1751. st.markdown("将面板划分为不同功能区域,统计各区域缺陷分布")
  1752. # 定义区域:(名称, 判定函数)
  1753. # 边缘区:距四边 < 15%
  1754. # 中心区:距中心 < 20% 半径
  1755. # 角落区:四个角的 15% 范围
  1756. # FPC区:Y > 70% 高度
  1757. # 上半区/下半区
  1758. def classify_zone(x_norm, y_norm):
  1759. """将每个缺陷点分类到区域"""
  1760. zones = []
  1761. for i in range(len(x_norm)):
  1762. zx, zy = x_norm[i], y_norm[i]
  1763. zone_list = []
  1764. # 边缘区
  1765. if min(zx, 1 - zx, zy, 1 - zy) < 0.15:
  1766. zone_list.append("边缘区")
  1767. # 中心区
  1768. if np.sqrt((zx - 0.5)**2 + (zy - 0.5)**2) < 0.20:
  1769. zone_list.append("中心区")
  1770. # 角落区
  1771. if (zx < 0.15 or zx > 0.85) and (zy < 0.15 or zy > 0.85):
  1772. zone_list.append("角落区")
  1773. # FPC区
  1774. if zy > 0.70:
  1775. zone_list.append("FPC区")
  1776. # 上半区
  1777. if zy < 0.50:
  1778. zone_list.append("上半区")
  1779. # 下半区
  1780. if zy > 0.50:
  1781. zone_list.append("下半区")
  1782. if not zone_list:
  1783. zone_list.append("其他区域")
  1784. zones.append(", ".join(zone_list))
  1785. return zones
  1786. # 计算每个缺陷的区域归属
  1787. x_norm_arr = filtered_df["x_mm"].values / pw
  1788. y_norm_arr = filtered_df["y_mm"].values / ph
  1789. filtered_df_copy = filtered_df.copy()
  1790. filtered_df_copy["zone"] = classify_zone(x_norm_arr, y_norm_arr)
  1791. # 统计各区域缺陷数
  1792. zone_counts = {}
  1793. zone_types = ["边缘区", "中心区", "角落区", "FPC区", "上半区", "下半区", "其他区域"]
  1794. for z in zone_types:
  1795. count = filtered_df_copy["zone"].str.contains(z).sum()
  1796. zone_counts[z] = count
  1797. col_z1, col_z2 = st.columns([1, 2])
  1798. with col_z1:
  1799. st.subheader("区域缺陷统计")
  1800. for z in zone_types:
  1801. count = zone_counts.get(z, 0)
  1802. pct = count / max(len(filtered_df_copy), 1) * 100
  1803. bar_len = int(pct / 100 * 200)
  1804. bar = "█" * max(bar_len, 0)
  1805. st.markdown(f"{z} | {bar} **{count}** ({pct:.1f}%)")
  1806. with col_z2:
  1807. # 区域可视化
  1808. fig_zone, ax_zone = plt.subplots(figsize=(4, 6))
  1809. # 面板背景
  1810. ax_zone.add_patch(plt.Rectangle((0, 0), pw, ph, facecolor="#1a1a2e", edgecolor="#444", linewidth=2))
  1811. # 区域边界
  1812. # 边缘区 (15% 边界)
  1813. margin_x = pw * 0.15
  1814. margin_y = ph * 0.15
  1815. ax_zone.add_patch(plt.Rectangle((0, 0), margin_x, ph, fill=False, edgecolor="yellow", linewidth=1, alpha=0.4, linestyle="--"))
  1816. ax_zone.add_patch(plt.Rectangle((pw - margin_x, 0), margin_x, ph, fill=False, edgecolor="yellow", linewidth=1, alpha=0.4, linestyle="--"))
  1817. ax_zone.add_patch(plt.Rectangle((0, 0), pw, margin_y, fill=False, edgecolor="yellow", linewidth=1, alpha=0.4, linestyle="--"))
  1818. ax_zone.add_patch(plt.Rectangle((0, ph - margin_y), pw, margin_y, fill=False, edgecolor="yellow", linewidth=1, alpha=0.4, linestyle="--"))
  1819. # 中心区 (20% 半径)
  1820. center_r = 0.20 * max(pw, ph) / 2
  1821. circle = plt.Circle((pw/2, ph/2), center_r, fill=False, edgecolor="cyan", linewidth=1.5, alpha=0.5, linestyle="--")
  1822. ax_zone.add_patch(circle)
  1823. # FPC区
  1824. fpc_y = ph * 0.70
  1825. ax_zone.add_patch(plt.Rectangle((0, fpc_y), pw, ph - fpc_y, fill=False, edgecolor="magenta", linewidth=1.5, alpha=0.5, linestyle="--"))
  1826. # 缺陷散点
  1827. scatter_colors = {"边缘区": "yellow", "中心区": "cyan", "角落区": "orange",
  1828. "FPC区": "magenta", "上半区": "#4ECDC4", "下半区": "#45B7D1", "其他区域": "gray"}
  1829. for z_name in zone_types:
  1830. z_mask = filtered_df_copy["zone"].str.contains(z_name)
  1831. if z_mask.sum() > 0:
  1832. z_data = filtered_df_copy[z_mask]
  1833. ax_zone.scatter(z_data["x_mm"], z_data["y_mm"],
  1834. c=scatter_colors.get(z_name, "gray"), s=5, alpha=0.3,
  1835. label=f"{z_name} ({z_mask.sum()})", edgecolors="none", zorder=2)
  1836. ax_zone.set_xlim(-5, pw + 5)
  1837. ax_zone.set_ylim(-5, ph + 5)
  1838. ax_zone.set_title("缺陷区域叠加图 (虚线=区域边界)")
  1839. ax_zone.set_xlabel("X (mm)")
  1840. ax_zone.set_ylabel("Y (mm)")
  1841. ax_zone.set_aspect("equal")
  1842. ax_zone.legend(fontsize=7, loc="upper right", ncol=1, framealpha=0.7)
  1843. st.pyplot(fig_zone)
  1844. plt.close()
  1845. # --- 跨批次同座号面板对比 ---
  1846. st.divider()
  1847. st.subheader("🔀 跨批次同座号面板对比")
  1848. st.markdown(
  1849. "选择一台设备和一个座号,查看该座号在不同批次生产的面板上缺陷分布的对比。"
  1850. "如果同一座号持续在相同位置产生缺陷 → 该座号存在系统性问题。"
  1851. )
  1852. col_cmp1, col_cmp2, col_cmp3 = st.columns(3)
  1853. with col_cmp1:
  1854. cmp_eq = st.selectbox("选择设备", options=sorted(df["equipment_id"].unique()), key="cmp_eq")
  1855. with col_cmp2:
  1856. eq_seats = sorted(df[(df["equipment_id"] == cmp_eq)]["seat_id"].unique())
  1857. cmp_seat = st.selectbox("选择座号", options=eq_seats, key="cmp_seat")
  1858. with col_cmp3:
  1859. # 找出有该设备座号缺陷的批次
  1860. eq_seat_batches = sorted(df[(df["equipment_id"] == cmp_eq) & (df["seat_id"] == cmp_seat)]["batch_id"].unique())
  1861. cmp_batches = st.multiselect("选择对比批次", options=eq_seat_batches, default=eq_seat_batches[:3] if len(eq_seat_batches) >= 3 else eq_seat_batches)
  1862. if cmp_batches and len(cmp_batches) >= 2:
  1863. n_cols = min(len(cmp_batches), 3)
  1864. n_rows = (len(cmp_batches) + n_cols - 1) // n_cols
  1865. fig_cmp, axes_cmp = plt.subplots(n_rows, n_cols, figsize=(3.5 * n_cols, 5 * n_rows))
  1866. axes_cmp = axes_cmp.flatten() if n_cols * n_rows > 1 else [axes_cmp]
  1867. for i, batch in enumerate(cmp_batches):
  1868. ax = axes_cmp[i]
  1869. batch_data = df[(df["equipment_id"] == cmp_eq) & (df["seat_id"] == cmp_seat) & (df["batch_id"] == batch)]
  1870. # 面板背景
  1871. ax.add_patch(plt.Rectangle((0, 0), pw, ph, facecolor="#1a1a2e", edgecolor="#444", linewidth=1))
  1872. if len(batch_data) > 0:
  1873. # 按缺陷类型着色
  1874. type_colors = {"划痕": "red", "亮点": "yellow", "暗点": "black", "气泡": "cyan",
  1875. "色差": "magenta", "漏光": "orange", "裂纹": "darkred", "异物": "green"}
  1876. for _, row in batch_data.iterrows():
  1877. c = type_colors.get(row["defect_type"], "white")
  1878. ax.scatter(row["x_mm"], row["y_mm"], c=c, s=30, alpha=0.7, edgecolors="white", linewidth=0.3, zorder=3)
  1879. ax.set_xlim(-3, pw + 3)
  1880. ax.set_ylim(-3, ph + 3)
  1881. ax.set_title(f"{batch}\n{len(batch_data)} 缺陷", fontsize=9)
  1882. ax.set_aspect("equal")
  1883. ax.grid(True, alpha=0.1, color="gray")
  1884. ax.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False)
  1885. # 隐藏多余子图
  1886. for j in range(len(cmp_batches), len(axes_cmp)):
  1887. axes_cmp[j].set_visible(False)
  1888. fig_cmp.suptitle(f"{cmp_eq} / {cmp_seat} 跨批次对比", fontsize=12, y=1.01)
  1889. plt.tight_layout()
  1890. st.pyplot(fig_cmp)
  1891. plt.close()
  1892. # 对比统计
  1893. st.subheader("对比统计")
  1894. comp_stats = []
  1895. for batch in cmp_batches:
  1896. batch_data = df[(df["equipment_id"] == cmp_eq) & (df["seat_id"] == cmp_seat) & (df["batch_id"] == batch)]
  1897. comp_stats.append({
  1898. "批次": batch,
  1899. "缺陷数": len(batch_data),
  1900. "主要类型": batch_data["defect_type"].mode().iloc[0] if len(batch_data) > 0 else "-",
  1901. "严重占比": f"{(batch_data['severity']=='严重').sum() / max(len(batch_data), 1):.0%}",
  1902. "中心X": round(batch_data["x_mm"].mean(), 1) if len(batch_data) > 0 else "-",
  1903. "中心Y": round(batch_data["y_mm"].mean(), 1) if len(batch_data) > 0 else "-",
  1904. })
  1905. st.dataframe(pd.DataFrame(comp_stats), use_container_width=True, hide_index=True)
  1906. # 趋势判断
  1907. if len(cmp_batches) >= 3:
  1908. defect_counts = [len(df[(df["equipment_id"] == cmp_eq) & (df["seat_id"] == cmp_seat) & (df["batch_id"] == b)]) for b in cmp_batches]
  1909. x_trend = np.arange(len(cmp_batches))
  1910. coeffs = np.polyfit(x_trend, defect_counts, 1)
  1911. slope = coeffs[0]
  1912. if slope > 0.5:
  1913. st.warning(f"⚠️ **{cmp_eq}/{cmp_seat}** 缺陷数呈**上升趋势** (斜率: {slope:.1f}/批次),建议安排设备检修")
  1914. elif slope < -0.5:
  1915. st.success(f"✅ **{cmp_eq}/{cmp_seat}** 缺陷数呈**改善趋势** (斜率: {slope:.1f}/批次)")
  1916. else:
  1917. st.info(f"➡️ **{cmp_eq}/{cmp_seat}** 缺陷数**平稳** (斜率: {slope:.1f}/批次)")
  1918. else:
  1919. st.info("请选择至少 2 个批次进行对比")
  1920. # --- 缺陷传播追踪 ---
  1921. st.divider()
  1922. st.subheader("📡 缺陷坐标传播追踪")
  1923. st.markdown(
  1924. "追踪同一坐标区域在时间轴上的缺陷演变,识别持续恶化的位置。"
  1925. "如果某坐标的缺陷数量随时间递增 → 该位置存在渐进性损伤(如吸嘴持续磨损)。"
  1926. )
  1927. # 坐标分桶 + 时间维度
  1928. prop_bin = st.slider("传播追踪分桶大小 (mm)", min_value=10, max_value=50, value=20, step=10)
  1929. df_time = df.copy()
  1930. df_time["x_bin"] = (df_time["x_mm"] // prop_bin).astype(int)
  1931. df_time["y_bin"] = (df_time["y_mm"] // prop_bin).astype(int)
  1932. # 按桶 + 日期聚合
  1933. prop_df = df_time.groupby(["x_bin", "y_bin", "day"]).size().reset_index(name="defect_count")
  1934. # 找出至少有 3 天数据的桶
  1935. bucket_days = prop_df.groupby(["x_bin", "y_bin"])["day"].nunique()
  1936. active_buckets = bucket_days[bucket_days >= 3].index.tolist()
  1937. if active_buckets:
  1938. # 选择要追踪的桶
  1939. bucket_options = [f"({bx},{by})" for bx, by in active_buckets]
  1940. bucket_counts = prop_df.groupby(["x_bin", "y_bin"])["defect_count"].sum().sort_values(ascending=False)
  1941. # 默认选缺陷最多的桶
  1942. default_top = bucket_counts.index[0]
  1943. selected_bucket = st.selectbox(
  1944. "选择要追踪的坐标桶",
  1945. options=bucket_options,
  1946. index=0,
  1947. format_func=lambda x: f"{x} (总缺陷: {bucket_counts.loc[tuple(map(int, x.strip('()').split(',')))]:.0f})"
  1948. )
  1949. bx, by = map(int, selected_bucket.strip("()").split(","))
  1950. bucket_timeline = prop_df[(prop_df["x_bin"] == bx) & (prop_df["y_bin"] == by)].sort_values("day")
  1951. bucket_timeline["day"] = pd.to_datetime(bucket_timeline["day"])
  1952. # 传播趋势图
  1953. fig_prop, ax_prop = plt.subplots(figsize=(12, 4))
  1954. ax_prop.bar(bucket_timeline["day"], bucket_timeline["defect_count"],
  1955. color="steelblue", alpha=0.7, width=0.8)
  1956. # 趋势线
  1957. if len(bucket_timeline) >= 2:
  1958. x_t = np.arange(len(bucket_timeline))
  1959. coeffs_p = np.polyfit(x_t, bucket_timeline["defect_count"].values, 1)
  1960. slope_p = coeffs_p[0]
  1961. trend_y = np.polyval(coeffs_p, x_t)
  1962. ax_prop.plot(bucket_timeline["day"], trend_y, color="red", linestyle="--",
  1963. linewidth=2, label=f"趋势 (斜率: {slope_p:.2f}/天)")
  1964. if slope_p > 0.3:
  1965. ax_prop.set_title(f"坐标桶 ({bx},{by}) — 缺陷数上升 (恶化趋势)")
  1966. elif slope_p < -0.3:
  1967. ax_prop.set_title(f"坐标桶 ({bx},{by}) — 缺陷数下降 (改善趋势)")
  1968. else:
  1969. ax_prop.set_title(f"坐标桶 ({bx},{by}) — 缺陷数平稳")
  1970. else:
  1971. ax_prop.set_title(f"坐标桶 ({bx},{by})")
  1972. ax_prop.set_ylabel("缺陷数量")
  1973. ax_prop.tick_params(axis="x", rotation=45)
  1974. ax_prop.legend()
  1975. ax_prop.grid(True, alpha=0.3, axis="y")
  1976. st.pyplot(fig_prop)
  1977. plt.close()
  1978. # 该桶的缺陷类型演变
  1979. bucket_data = df_time[(df_time["x_bin"] == bx) & (df_time["y_bin"] == by)]
  1980. st.markdown(f"**坐标桶 ({bx},{by}) 缺陷类型演变** (对应面板区域: X {bx*prop_bin}-{(bx+1)*prop_bin}mm, Y {by*prop_bin}-{(by+1)*prop_bin}mm)")
  1981. bucket_type_timeline = bucket_data.groupby(["day", "defect_type"]).size().unstack(fill_value=0)
  1982. bucket_type_timeline.index = pd.to_datetime(bucket_type_timeline.index)
  1983. st.dataframe(bucket_type_timeline, use_container_width=True, height=300)
  1984. else:
  1985. st.info("当前数据中无足够多天数的连续缺陷坐标桶 (需 ≥3 天)")
  1986. # --- 底部:数据导出 ---
  1987. st.divider()
  1988. if current_config["show_export"]:
  1989. st.subheader("📥 数据导出")
  1990. # 综合报告导出
  1991. st.subheader("📋 一键导出综合报告")
  1992. st.markdown("包含所有分析模块的关键结论,适合汇报和存档。")
  1993. report_parts = []
  1994. report_parts.append("# 缺陷集中性分析综合报告\n")
  1995. report_parts.append(f"**生成时间**: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
  1996. report_parts.append(f"**数据范围**: {start_date.strftime('%Y-%m-%d')} ~ {end_date.strftime('%Y-%m-%d')}")
  1997. report_parts.append(f"**筛选后缺陷数**: {len(filtered_df)} 条")
  1998. report_parts.append(f"**涉及面板**: {filtered_df['panel_id'].nunique()} 块")
  1999. report_parts.append(f"**视图模式**: {view_mode}\n")
  2000. # 1. KPI 摘要
  2001. report_parts.append("## 1. KPI 摘要\n")
  2002. report_kpis = calculate_kpis(df, filtered_df)
  2003. total_panels_inspected_r = report_kpis["total_panels_inspected"]
  2004. defective_panels_r = report_kpis["defective_panels"]
  2005. yield_rate_r = report_kpis["yield_rate"]
  2006. report_parts.append(f"- 检测面板数: {total_panels_inspected_r} 块")
  2007. defective_rate_r = defective_panels_r / max(total_panels_inspected_r, 1) * 100
  2008. report_parts.append(f"- 不良面板数: {defective_panels_r} 块 ({defective_rate_r:.1f}%)")
  2009. report_parts.append(f"- 综合良率: {yield_rate_r:.1f}%")
  2010. report_parts.append(f"- 缺陷总数: {len(filtered_df)} 个")
  2011. report_parts.append(f"- 严重缺陷: {(filtered_df['severity']=='严重').sum()} 个\n")
  2012. # 2. 缺陷类型
  2013. report_parts.append("## 2. 缺陷类型分布\n")
  2014. type_counts_r = filtered_df["defect_type"].value_counts()
  2015. for t, c in type_counts_r.items():
  2016. report_parts.append(f"- {t}: {c} ({c/len(filtered_df)*100:.1f}%)")
  2017. report_parts.append("")
  2018. # 3. 设备/座号
  2019. if "equipment_id" in filtered_df.columns:
  2020. report_parts.append("## 3. 设备与座号分布\n")
  2021. eq_counts = filtered_df["equipment_id"].value_counts()
  2022. for e, c in eq_counts.items():
  2023. report_parts.append(f"- {e}: {c} 个缺陷")
  2024. seat_top = filtered_df["seat_id"].value_counts().head(5)
  2025. report_parts.append(f"\n**缺陷座号 TOP5**:")
  2026. for i, (s, c) in enumerate(seat_top.items(), 1):
  2027. report_parts.append(f" {i}. {s}: {c} 个")
  2028. report_parts.append("")
  2029. # 4. 趋势
  2030. report_parts.append("## 4. 趋势分析\n")
  2031. daily_r = filtered_df.groupby("day").size()
  2032. if len(daily_r) >= 2:
  2033. x_r = np.arange(len(daily_r))
  2034. coeffs_r = np.polyfit(x_r, daily_r.values.astype(float), 1)
  2035. slope_r = coeffs_r[0]
  2036. if slope_r > 0:
  2037. report_parts.append(f"- 缺陷数趋势: **上升** (斜率 {slope_r:.1f}/天)")
  2038. else:
  2039. report_parts.append(f"- 缺陷数趋势: **下降** (斜率 {slope_r:.1f}/天)")
  2040. report_parts.append("")
  2041. # 5. 异常座号
  2042. report_parts.append("## 5. 异常检测\n")
  2043. if "seat_id" in filtered_df.columns:
  2044. all_seat_stats_r = filtered_df.groupby(["equipment_id", "seat_id"]).size()
  2045. mean_r = all_seat_stats_r.mean()
  2046. std_r = all_seat_stats_r.std()
  2047. threshold_2x_r = mean_r + 2 * std_r
  2048. critical_r = all_seat_stats_r[all_seat_stats_r > threshold_2x_r]
  2049. if len(critical_r) > 0:
  2050. report_parts.append(f"- ⚠️ 2σ 异常座号: {len(critical_r)} 个")
  2051. for (eq, seat), count in critical_r.items():
  2052. report_parts.append(f" - {eq}/{seat}: {count} 个缺陷")
  2053. else:
  2054. report_parts.append("- ✅ 无 2σ 异常座号")
  2055. report_parts.append("")
  2056. # 6. 建议
  2057. report_parts.append("## 6. 建议\n")
  2058. top_type = type_counts_r.index[0] if len(type_counts_r) > 0 else "-"
  2059. top_eq = eq_counts.index[0] if len(eq_counts) > 0 else "-"
  2060. report_parts.append(f"- 重点关注缺陷类型: **{top_type}**")
  2061. report_parts.append(f"- 重点关注设备: **{top_eq}**")
  2062. report_parts.append("- 建议查看 SPC 控制图确认趋势状态")
  2063. report_parts.append("- 建议检查设备健康评分\n")
  2064. report_parts.append("---\n*本报告由缺陷集中性分析系统自动生成*")
  2065. full_report = "\n".join(report_parts)
  2066. col_exp1, col_exp2, col_exp3 = st.columns(3)
  2067. with col_exp1:
  2068. st.download_button(
  2069. label="📥 综合报告 (MD)",
  2070. data=full_report.encode("utf-8"),
  2071. file_name=f"defect_report_{datetime.now().strftime('%Y%m%d')}.md",
  2072. mime="text/markdown",
  2073. use_container_width=True
  2074. )
  2075. with col_exp2:
  2076. csv_data = filtered_df.to_csv(index=False).encode("utf-8-sig")
  2077. st.download_button(
  2078. label="📥 筛选数据 (CSV)",
  2079. data=csv_data,
  2080. file_name=f"defect_data_{datetime.now().strftime('%Y%m%d')}.csv",
  2081. mime="text/csv",
  2082. use_container_width=True
  2083. )
  2084. with col_exp3:
  2085. # 精简版 TXT 报告
  2086. txt_lines = ["缺陷集中性分析报告", f"生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
  2087. f"缺陷数: {len(filtered_df)} | 面板: {filtered_df['panel_id'].nunique()}",
  2088. f"良率: {yield_rate_r:.1f}%"]
  2089. for t, c in type_counts_r.head(3).items():
  2090. txt_lines.append(f" TOP: {t} {c}个")
  2091. txt_content = "\n".join(txt_lines)
  2092. st.download_button(
  2093. label="📥 精简报告 (TXT)",
  2094. data=txt_content.encode("utf-8"),
  2095. file_name=f"defect_summary_{datetime.now().strftime('%Y%m%d')}.txt",
  2096. mime="text/plain",
  2097. use_container_width=True
  2098. )