app.py 107 KB

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