メインコンテンツへスキップ
見出し画像

#16 Pythonで始める工程能力分析ver2、チャレンジ AI×100業務(製造業)

    このチャレンジシリーズは工程能力分析からはじまりました(単に、計算するだけのGUIでしたが・・・)。

    今日は、前にヒストグラムの描画を実施しましたので(平均値+標準偏差入り)、工程能力分析と合わせたものとします。規格値や平均値、標準偏差が合わせて描画されている方が、一見してわかりやすいですね。


    それでは、スタートです。
    *執筆者は以下を参照してください。

    使ったツール・準備したこと

    • Visual Studio Code環境下でのPython

    やってみたこと|コード・ステップ紹介

    実行した内容の簡単な流れ

    ① ChatGPT 4oへ質問:

    以前作成していただいた、工程能力分析のアプリで、描画機能を追加してください。ヒストグラム、仕様の上限、下限、平均値、標準偏差。

    生成されたコードを実行すると以下の画面が出力されました。

    画像

    今後の展開・アイデア

    次回取り組みたいこと

    ・次はF検定と箱ひげ図を合わせます。

    ■ 今日のコード

    import matplotlib
    matplotlib.rcParams['font.family'] = 'Meiryo'  # Windows の場合
    import tkinter as tk
    from tkinter import messagebox
    import statistics
    import re
    import matplotlib.pyplot as plt
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
    
    def calculate_cp_cpk():
        try:
            raw_data = entry_data.get("1.0", tk.END)
            cleaned_data = re.sub(r"[\s\n\t]+", ",", raw_data.strip())
            data = [float(x) for x in cleaned_data.split(',') if x.strip() != '']
    
            if len(data) < 2:
                messagebox.showerror("エラー", "2点以上のデータを入力してください。")
                return
            if len(data) > 30:
                messagebox.showerror("エラー", "30点までのデータにしてください。")
                return
    
            usl = float(entry_usl.get())
            lsl = float(entry_lsl.get())
    
            mean = statistics.mean(data)
            stdev = statistics.stdev(data)
    
            cp = (usl - lsl) / (6 * stdev)
            cpu = (usl - mean) / (3 * stdev)
            cpl = (mean - lsl) / (3 * stdev)
            cpk = min(cpu, cpl)
    
            label_result.config(    text=f"Cp: {cp:.3f}, Cpk: {cpk:.3f}\n平均: {mean:.3f}, 標準偏差: {stdev:.3f}")
    
            # ヒストグラム描画
            draw_histogram(data, lsl, usl, mean, stdev)
    
        except ValueError:
            messagebox.showerror("入力エラー", "数値を正しく入力してください。")
    
    def draw_histogram(data, lsl, usl, mean, stdev):
        ax.clear()
        ax.hist(data, bins=10, alpha=0.6, color='skyblue', edgecolor='black')
        ax.axvline(lsl, color='red', linestyle='--', label='LSL')
        ax.axvline(usl, color='red', linestyle='--', label='USL')
        ax.axvline(mean, color='green', linestyle='-', label='平均')
        ax.axvline(mean - stdev, color='gray', linestyle=':', label='-1σ')
        ax.axvline(mean + stdev, color='gray', linestyle=':', label='+1σ')
        ax.set_title('測定データ ヒストグラム')
        ax.set_xlabel('値')
        ax.set_ylabel('頻度')
        ax.legend()
        canvas.draw()
    
    def on_enter(event):
        calculate_cp_cpk()
    
    # GUI 作成
    root = tk.Tk()
    root.title("工程能力分析アプリ")
    root.geometry("600x800")
    
    # データ入力欄
    tk.Label(root, text="測定データ(最大30点、改行・空白・カンマ区切り可):").pack()
    entry_data = tk.Text(root, height=5, width=60)
    entry_data.pack()
    entry_data.bind("<Return>", on_enter)
    
    # 仕様上下限
    tk.Label(root, text="上限値 (USL):").pack()
    entry_usl = tk.Entry(root)
    entry_usl.pack()
    entry_usl.bind("<Return>", on_enter)
    
    tk.Label(root, text="下限値 (LSL):").pack()
    entry_lsl = tk.Entry(root)
    entry_lsl.pack()
    entry_lsl.bind("<Return>", on_enter)
    
    # 計算ボタン
    btn_calc = tk.Button(root, text="計算", command=calculate_cp_cpk)
    btn_calc.pack(pady=10)
    btn_calc.bind("<Return>", on_enter)
    
    # 結果表示
    label_result = tk.Label(root, text="Cp: , Cpk: 平均: , 標準偏差: ")
    label_result.pack(pady=10)
    
    # ヒストグラム用のFigure
    fig, ax = plt.subplots(figsize=(6, 4))
    canvas = FigureCanvasTkAgg(fig, master=root)
    canvas_widget = canvas.get_tk_widget()
    canvas_widget.pack(pady=(30, 10))
    
    # メインループ
    root.mainloop()
     
     
    プログラマーじゃない現役の設計者が、「AIで何ができる?」を製造業の現場目線で。 シックスシグマ、カーボンニュートラル、設計理論、工場でのAI×英語学習は各マガジンへ。 ※Amazonのアソシエイトとして、当アカウントは適格販売により収入を得ています。

    あなたへのおすすめ