app.py 119 KB

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