app.py 106 KB

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